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)
我正在尝试使用以下代码爆炸该struct列properties:
df_json.withColumn("event_properties", explode($"event.properties"))
Run Code Online (Sandbox Code Playgroud)
但这引发了以下异常:
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),
如何爆炸列properties?
正如错误消息所说,您只能分解数组或映射类型,而不能分解结构类型列。
你可以做
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)
您可以explode在array或map 列中使用,因此您需要将转换properties struct为array,然后explode按如下所示应用函数
import org.apache.spark.sql.functions._
df_json.withColumn("event_properties", explode(array($"event.properties.*"))).show(false)
Run Code Online (Sandbox Code Playgroud)
您应该有所需的要求
| 归档时间: |
|
| 查看次数: |
7758 次 |
| 最近记录: |