用于合并的Spark结构类型 [英] Spark Structtype for coalesce

查看:64
本文介绍了用于合并的Spark结构类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spark 2.0.1 Scala 2.11

I use Spark 2.0.1 Scala 2.11

如何使用 coalesce 为列提供默认值那是 StructType

How to provide a default value using coalesce for a column that's a StructType?

说...

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|
+-----+

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

My question is how can I provide a default value (say [0,0]) using coalesce?

推荐答案

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

You can use the struct function, passing two lit(0) values named to match the names of the struct you already have:

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]|
// +---------------------------------------+

这篇关于用于合并的Spark结构类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆