【问题标题】:SparkSQL — collect_set and sort_array does not sort integer column properlySparkSQL——collect_set 和 sort_array 不能正确排序整数列
【发布时间】:2017-03-03 16:03:55
【问题描述】:

我想在 SparkSQL 中生成一个排序的、收集的集合,如下所示:

spark.sql("SELECT id, col_2, sort_array(collect_set(value)) AS collected
           FROM my_table GROUP BY id, col_2").show()

其中 valueinteger

但它无法以正确的数字顺序对数组进行排序 - 并且做了一些相当特别的事情(而不是在值中的第一个数字的开头排序?sort_array 是否对字符串进行操作?)。

所以而不是:

+----+-------+------------+                                              
| id | col_2 | collected  |
+----+-------+------------+
| 1  |   2   |  [456,1234]|
+----+-------+------------+  

我明白了:

+----+-------+------------+                                              
| id | col_2 | collected  |
+----+-------+------------+
| 1  |   2   |  [1234,456]|
+----+-------+------------+  

编辑:

查看spark.sql(…) 返回的内容很明显,该查询返回的是字符串:

DataFrame[id: string, col_2: string, collected: array<string>]

当原始数据框全是integers时怎么会这样。


编辑 2:

这似乎是与pyspark 相关的问题,因为我没有遇到spark-shell 的问题并在scala 中写相同的东西

【问题讨论】:

  • 我想知道是否有一些字符串、空白或空语句最终迫使数据类型更改为字符串。这是一个快速示例,我将各种列转换为长列(从字符串),然后执行类似的sort_array(collect_set(...)) 命令,导致collected 被正确排序。 htmlpreview.github.io/?https://github.com/dennyglee/databricks/…

标签: apache-spark pyspark apache-spark-sql hiveql


【解决方案1】:

我使用 Apache Spark 2.0.0 进行了测试。

它对我有用。为了确保我使用数据[(1, 2, 1234), (1, 2, 456)][(1, 2, 456), (1, 2, 1234)] 进行了测试。结果是一样的。

from pyspark import SparkContext
from pyspark.sql import SQLContext

sc = SparkContext()
sqlContext = SQLContext(sc)

df = sqlContext.createDataFrame([(1, 2, 1234), (1, 2, 456)], ['id', 'col_2', 'value'])
# test with reversed order, too
#df = sqlContext.createDataFrame([(1, 2, 456), (1, 2, 1234)], ['id', 'col_2', 'value'])
df.createOrReplaceTempView("my_table")


sqlContext.sql("SELECT id, col_2, sort_array(collect_set(value)) AS collected FROM my_table GROUP BY id, col_2").show()

结果

+---+-----+-----------+
| id|col_2|  collected|
+---+-----+-----------+
|  1|    2|[456, 1234]|
+---+-----+-----------+

一些观察

  • 当值为 None 时,它​​显示为 null,例如[null, 456, 1234]
  • 当有字符串值时,Spark 抛出错误“TypeError: Can not merge type LongType and StringType”

我认为问题不在于 SQL,而在于创建 DataFrame 的早期步骤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2021-11-21
    • 1970-01-01
    • 2022-12-08
    • 2021-12-04
    相关资源
    最近更新 更多