繁体   English   中英

在Scala Spark中,当源列为NULL时,如何为派生列添加默认值?

[英]In Scala Spark, How to add default values for derived columns when source column is NULL?

我有具有以下架构的“学生”列

    root
 |-- t1: integer (nullable = true)
 |-- t2: integer (nullable = true)
 |-- StudentsInfo: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- rollNumber: integer (nullable = true)
 |    |    |-- complaints: map (nullable = true)
 |    |    |    |-- key: string
 |    |    |    |-- value: struct (valueContainsNull = true)
 |    |    |    |    |-- severityOfComplaintX: integer (nullable = true)
 |    |    |    |    |-- numInstancesofComplaintX: integer (nullable = true)

我想将此“studentInfo”列转换为两个派生列

我派生了以下两列(每列都是“Map”类型):“compainSeverityOfComplaintX”“compainNumInstancesofComplaintX”。

在这里理解查询可能并不重要。 它的一些工作查询从“学生”类型的列中派生出两列(类型:地图)

但是,问题是当列(“studentInfo”)的值为 NULL 时。它会跳过整行(如预期的那样)。

我想更新我的 SQL 查询,以便当 rowX 的“studentInfo”列的值为 NULL 时,它应该添加空 MAP 作为派生列“compainSeverityOfComplaintX”和“compainNumInstancesofComplaintX”的值

在这里处理 null 值更好吗?

For row-i:
    when "students" == null:
       set newly derived column compaintSeverityOfComplaintX = empty Map
       set newly derived column compaintNumInstancesofComplaintX = empty Map
    else
       run above SQL to set proper values for newly derived columns compaintSeverityOfComplaintX and compaintNumInstancesofComplaintX

更新:我尝试添加虚拟 studentInfo 但它给出了错误


withColumn("students", when($"students".isNull, typedLit(Seq.empty[Any])).otherwise($"students"))

错误:java.lang.RuntimeException:不支持的文字类型 class scala.collection.immutable.Nil$ List()

例如,假设您知道新派生列的类型,在您的例子中是 Map[K,V]。

你可以尝试这样的事情

val derivedColumn = joinMap(col("severityOfComplaintXMapList"))

dataframe.withColumn("compaintSeverityOfComplaintX", when(col("students").isNull, typeLit[Map[String, Int]](Map.empty[String, Int]))).otherwise(derivedColumn)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM