Gab*_*Gab 2 scala apache-spark apache-spark-sql
我正在尝试修改由外部库生成的数据框。我收到一个具有以下架构的数据框:
root
|-- child: struct (nullable = true)
| |-- child_id: long (nullable = true)
Run Code Online (Sandbox Code Playgroud)
我想将上面的子结构包装到一个Array中,如下框所示。
root
|-- child: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- child_id: long (nullable = true)
Run Code Online (Sandbox Code Playgroud)
我尝试定义一个 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"))
Run Code Online (Sandbox Code Playgroud)
但我得到一个例外:“不支持 org.apache.spark.sql.Row 类型的架构”
我正在使用Spark 2.1.1。
真正的DataFrame非常复杂,是否有一种解决方案允许修改架构而不列出子表中字段的名称或位置?出于同样的原因,我也宁愿不映射到显式案例类。
预先感谢您的任何帮助!
您可以使用array内置函数来获得您想要的结果
import org.apache.spark.sql.functions._
val df2 = df.withColumn("child", array("child"))
Run Code Online (Sandbox Code Playgroud)
这将更新同一列,如果您希望将其放在单独的列中,则执行以下操作
import org.apache.spark.sql.functions._
val df2 = df.withColumn("children", array("child"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4927 次 |
| 最近记录: |