在 apache Spark 数据框中分解数组

Art*_*tem 5 scala explode apache-spark apache-spark-sql

我正在尝试使用嵌套字段来展平现有数据框的模式。我的数据框的结构是这样的:

root  
|-- Id: long (nullable = true)  
|-- Type: string (nullable = true)  
|-- Uri: string (nullable = true)    
|-- Type: array (nullable = true)  
|    |-- element: string (containsNull = true)  
|-- Gender: array (nullable = true)  
|    |-- element: string (containsNull = true)
Run Code Online (Sandbox Code Playgroud)

类型和性别可以包含元素数组、一个元素或空值。我尝试使用以下代码:

var resDf = df.withColumn("FlatType", explode(df("Type")))
Run Code Online (Sandbox Code Playgroud)

但结果是在生成的数据框中,我丢失了类型列具有空值的行。这意味着,例如,如果我有 10 行,并且在 7 行中类型为 null,在 3 行中类型不为 null,则在我在结果数据框中使用爆炸后,我只有三行。

如何保留具有空值的行但分解值数组?

我找到了某种解决方法,但仍然停留在一个地方。对于标准类型,我们可以执行以下操作:

def customExplode(df: DataFrame, field: String, colType: String): org.apache.spark.sql.Column = {
var exploded = None: Option[org.apache.spark.sql.Column]
colType.toLowerCase() match {
  case "string" => 
    val avoidNull = udf((column: Seq[String]) =>
    if (column == null) Seq[String](null)
    else column)
    exploded = Some(explode(avoidNull(df(field))))
  case "boolean" => 
    val avoidNull = udf((xs: Seq[Boolean]) =>
    if (xs == null) Seq[Boolean]()
    else xs)
    exploded = Some(explode(avoidNull(df(field))))
  case _ => exploded = Some(explode(df(field)))
}
exploded.get
Run Code Online (Sandbox Code Playgroud)

}

然后像这样使用它:

val explodedField = customExplode(resultDf, fieldName, fieldTypeMap(field))
resultDf = resultDf.withColumn(newName, explodedField)
Run Code Online (Sandbox Code Playgroud)

但是,我对以下类型的结构的结构类型有问题:

 |-- Address: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- AddressType: array (nullable = true)
 |    |    |    |-- element: string (containsNull = true) 
 |    |    |-- DEA: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- Number: array (nullable = true)
 |    |    |    |    |    |-- element: string (containsNull = true)
 |    |    |    |    |-- ExpirationDate: array (nullable = true)
 |    |    |    |    |    |-- element: timestamp (containsNull = true)
 |    |    |    |    |-- Status: array (nullable = true)
 |    |    |    |    |    |-- element: string (containsNull = true)
Run Code Online (Sandbox Code Playgroud)

当 DEA 为空时我们如何处理这种模式?

先感谢您。

PS 我尝试使用横向视图,但结果是相同的。

Dan*_*ula 4

也许你可以尝试使用when

val resDf = df.withColumn("FlatType", when(df("Type").isNotNull, explode(df("Type")))
Run Code Online (Sandbox Code Playgroud)

when如该函数的文档所示,null对于不符合条件的值将插入该值。