Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spark Structtype for coalesce

I use Spark 2.0.1 Scala 2.11

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

Say ...

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)

Now, df.select($"b").show results in

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

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

like image 238
mrbrahman Avatar asked Mar 01 '26 05:03

mrbrahman


1 Answers

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]|
// +---------------------------------------+
like image 173
Tzach Zohar Avatar answered Mar 03 '26 18:03

Tzach Zohar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!