PySpark中如何将array(struct(array))展平为array(struct)
Spark 3.5.0 嵌套数组结构体扁平化优化
需求背景
现有DataFrame包含嵌套数组结构体,原始Schema如下:
原始Schema:
root |-- a: integer (nullable = true) |-- list: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- b: integer (nullable = true) | | |-- sub_list: array (nullable = true) | | | |-- element: struct (containsNull = true) | | | | |-- c: integer (nullable = true) | | | | |-- foo: string (nullable = true)
需要将其简化为单层结构体数组的Schema:
目标Schema:
root |-- a: integer (nullable = true) |-- list: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- b: integer (nullable = true) | | |-- c: integer (nullable = true) | | |-- foo: string (nullable = true)
使用Spark 3.5.0版本,尝试过flatten、inline、explode、transform等函数,均未实现需求。
当前可行但繁琐的解决方案
针对简化示例,已实现以下代码,但在复杂场景中需要自顶向下展开所有层级到行级别,操作繁琐:
from pyspark.sql import functions as F df.select("a", F.inline("list")) \ .select(F.expr("*"), F.inline("sub_list")) \ .drop("sub_list") \ .groupBy("a") \ .agg(F.collect_list(F.struct("b", "c", "foo")).alias("list"))
期望的自底向上实现方式
希望通过自底向上的方式将内部数组展开到外部数组,避免全量展开到行级别。尝试过以下代码但报错:
from pyspark.sql import functions as F df.withColumn("list", F.transform(F.col("list"), lambda x: x.withField("sub_list", F.explode(x.getField("sub_list")))))
内容的提问来源于stack exchange,提问作者E. T.
相关产品推荐
相关产品推荐

