gpt4 book ai didi

scala - Spark DataFrame 将 struct<.. 包装到 struct<. 的数组中

转载 作者:行者123 更新时间:2023-12-02 00:43:04 26 4
gpt4 key购买 nike

我正在尝试修改由外部库生成的 Dataframe。我收到一个具有此架构的数据框:

root
|-- child: struct (nullable = true)
| |-- child_id: long (nullable = true)

我想将上面的 child 结构包装到一个 Array 中,如下方框所示。

root
|-- child: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- child_id: long (nullable = true)

我尝试定义一个 UDF:

//the two lines below are an example, in real i get the Dataframe from an  external library. 
val seq = sc.parallelize(Seq("""{ "child": { "child_id": 1}}"""))
val df = sqlContext.read.json(seq)

val myUDF = udf((x: Row) => Array(x))
val df2 = df.withColumn("children",myUDF($"child"))

但我得到一个异常:“不支持 org.apache.spark.sql.Row 类型的架构

我正在使用 Spark 2.1.1

真正的DataFrame是很复杂的,有没有一种方案可以修改schema而不列出子表中字段的名称或位置?出于同样的原因,我也不想映射到显式案例类。

提前感谢您的帮助!

最佳答案

您可以使用array 内置函数来获得您想要的结果

import org.apache.spark.sql.functions._
val df2 = df.withColumn("child", array("child"))

这将更新同一列,如果你想在单独的列中进行更新

import org.apache.spark.sql.functions._
val df2 = df.withColumn("children", array("child"))

关于scala - Spark DataFrame 将 struct<.. 包装到 struct<. 的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45499361/

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