Apache Spark 2.0:表达式字符串到 orderBy() / sort() 列降序

Apache Spark 2.0: Expression-string to orderBy() / sort() column in descending order

我正在查看与以下内容类似(几乎相同)的书籍示例:

>>> from pyspark.sql import functions as sFn
>>>   # Note: I import Spark functions this way to avoid name collisions w/ Python.
>>>   # Usage below: sFn.expr(), sFn.col(), etc.

>>> col0 = [0, 1, 2, 3]
>>> col1 = [4, 5, 6, 7]

>>> myDF = spark.createDataFrame(zip(col0, col1),
                                 schema=['col0', 'col1'])
>>> print(myDF)
>>> myDF.show()
>>> myDF.orderBy(sFn.expr('col0 desc')).show() # <--- Problem line. Doesn't descend.

现在书上的例子声称最后一条语句将按 col0 降序排列,但事实并非如此:

DataFrame[col0: bigint, col1: bigint]

+----+----+
|col0|col1|
+----+----+
|   0|   4|
|   1|   5|
|   2|   6|
|   3|   7|
+----+----+

+----+----+
|col0|col1|
+----+----+
|   0|   4|
|   1|   5|
|   2|   6|
|   3|   7|
+----+----+

然而,这种语法变体对我一直有效:

myDF.orderBy(sFn.col("col0").desc()).show()

有问题的变体是不是打字错误或勘误表?如果是拼写错误或勘误表,需要进行哪些调整才能使其生效?

谢谢。

sFn.expr('col0 desc') 中,desc 被翻译为别名而不是 order by modifier,正如您在控制台中键入它所看到的:

sFn.expr('col0 desc')
# Column<col0 AS `desc`>

您可以根据需要选择其他几个选项:

 myDF.orderBy('col0', ascending=0).show()
+----+----+
|col0|col1|
+----+----+
|   3|   7|
|   2|   6|
|   1|   5|
|   0|   4|
+----+----+


myDF.orderBy(sFn.desc('col0')).show()
+----+----+
|col0|col1|
+----+----+
|   3|   7|
|   2|   6|
|   1|   5|
|   0|   4|
+----+----+

myDF.orderBy(myDF.col0.desc()).show()
+----+----+
|col0|col1|
+----+----+
|   3|   7|
|   2|   6|
|   1|   5|
|   0|   4|
+----+----+