gpt4 book ai didi

scala - 将结构数组分解为 Spark 中的列

转载 作者:行者123 更新时间:2023-12-01 03:18:37 25 4
gpt4 key购买 nike

我想将一个结构数组分解为列(由结构字段定义)。例如。

root
|-- arr: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- id: long (nullable = false)
| | |-- name: string (nullable = true)

应该转化为
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)

我可以用
df
.select(explode($"arr").as("tmp"))
.select($"tmp.*")

如何在单个 select 语句中做到这一点?

我认为这可以工作,不幸的是它没有:
df.select(explode($"arr")(".*"))

Exception in thread "main" org.apache.spark.sql.AnalysisException: No such struct field .* in col;

最佳答案

单步解决方案仅适用于 MapType列:

val df = Seq(Tuple1(Map((1L, "bar"), (2L, "foo")))).toDF

df.select(explode($"_1") as Seq("foo", "bar")).show

+---+---+
|foo|bar|
+---+---+
| 1|bar|
| 2|foo|
+---+---+

对于数组,您可以使用 flatMap :
val df = Seq(Tuple1(Array((1L, "bar"), (2L, "foo")))).toDF
df.as[Seq[(Long, String)]].flatMap(identity)

SELECT语句可以用 SQL 编写:
 df.createOrReplaceTempView("df")

spark.sql("SELECT x._1, x._2 FROM df LATERAL VIEW explode(_1) t AS x")

关于scala - 将结构数组分解为 Spark 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47553500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com