在Spark中分解结构列时出错

shi*_*404 5 scala apache-spark apache-spark-sql pyspark spark-dataframe

我有一个数据框架,其架构如下所示:

event: struct (nullable = true)
|    | event_category: string (nullable = true)
|    | event_name: string (nullable = true)
|    | properties: struct (nullable = true)
|    |    | ErrorCode: string (nullable = true)
|    |    | ErrorDescription: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下代码爆炸该structproperties

df_json.withColumn("event_properties", explode($"event.properties"))
Run Code Online (Sandbox Code Playgroud)

但这引发了以下异常:

cannot resolve 'explode(`event`.`properties`)' due to data type mismatch: 
input to function explode should be array or map type, 
not StructType(StructField(IDFA,StringType,true),
Run Code Online (Sandbox Code Playgroud)

如何爆炸列properties

Rap*_*oth 7

正如错误消息所说,您只能分解数组或映射类型,而不能分解结构类型列。

你可以做

df_json.withColumn("event_properties", $"event.properties")
Run Code Online (Sandbox Code Playgroud)

这将生成一个新列event_properties,它也是结构类型

如果要将结构的每个元素都转换为新列,则不能使用withColumn,您需要select使用通配符执行 a *

df_json.select($"event.properties.*")
Run Code Online (Sandbox Code Playgroud)


Ram*_*jan 6

您可以explodearraymap 列中使用,因此您需要将转换properties structarray,然后explode按如下所示应用函数

import org.apache.spark.sql.functions._
df_json.withColumn("event_properties", explode(array($"event.properties.*"))).show(false)
Run Code Online (Sandbox Code Playgroud)

您应该有所需的要求

  • 怎么会爆炸成地图。我也需要键名 (3认同)