【问题标题】:Spark DataFrame wrap struct<.. into array of struct<Spark DataFrame 将 struct<.. 包装到 struct< 数组中
【发布时间】:2018-01-11 22:52:29
【问题描述】:

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

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而不列出子表中字段的名称或位置?出于同样的原因,我也不想映射到显式案例类。

提前感谢您的帮助!

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    您可以使用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"))
    

    【讨论】:

    • 否 :) 我猜你不是。感谢您的接受和支持:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多