用于合并的 Spark 结构类型

Spark Structtype for coalesce

我使用 Spark 2.0.1 Scala 2.11

如何使用 coalesceStructType 的列提供默认值?

说...

val ss = new StructType().add("x", IntegerType).add("y", IntegerType)

val s = new StructType()
    .add("a", IntegerType)
    .add("b", ss)

val d = Seq( Row(1, Row(1,2)), Row(2, Row(2,3)), Row(2, null) ) 

val rd = sc.parallelize(d)
val df = spark.createDataFrame(rd, s)

现在,df.select($"b").show 结果是

+-----+
| b   |
+-----+
|[1,2]|
|[2,3]|
| null|
+-----+

我的问题是如何使用 coalesce 提供默认值(比如 [0,0])?

您可以使用 struct 函数,传递两个 lit(0) 值以匹配您已有的结构的名称:

df.select(coalesce($"b", struct(lit(0).as("x"), lit(0).as("y"))))
  .show()

// +---------------------------------------+
// |coalesce(b, struct(0 AS `x`, 0 AS `y`))|
// +---------------------------------------+
// |                                  [1,2]|
// |                                  [2,3]|
// |                                  [0,0]|
// +---------------------------------------+