Anu*_*p K 4 struct dataframe apache-spark apache-spark-sql pyspark
我正在尝试对嵌套列进行匿名/哈希处理,但没有成功。该架构看起来像这样:
-- abc: struct (nullable = true)
| |-- xyz: struct (nullable = true)
| | |-- abc123: string (nullable = true)
| | |-- services: struct (nullable = true)
| | | |-- service: array (nullable = true)
| | | | |-- element: struct (containsNull = true)
| | | | | |-- type: string (nullable = true)
| | | | | |-- subtype: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)
我需要更改(匿名/哈希)type列的值。
对于 Spark 3.1+,有一个列方法withField可用于更新结构体字段。
假设这是您的输入数据框(对应于您提供的架构):
from pyspark.sql import Row
df = spark.createDataFrame([
Row(abc=Row(xyz=Row(abc123="value123", services=[Row(type="type1", subtype="subtype1")])))
])
df.show(truncate=False)
#+---------------------------------+
#|abc |
#+---------------------------------+
#|{{value123, [{type1, subtype1}]}}|
#+---------------------------------+
Run Code Online (Sandbox Code Playgroud)
您可以使用transform数组来散列每个结构元素的services字段(这里我使用函数来说明),如下所示:typexxhash64
import pyspark.sql.functions as F
df2 = df.withColumn(
"abc",
F.col("abc").withField(
"xyz",
F.col("abc.xyz").withField(
"services",
F.expr("transform(abc.xyz.services, x -> struct(xxhash64(x.type) as type, x.subtype))")
)
)
)
df2.show(truncate=False)
#+-----------------------------------------------+
#|abc |
#+-----------------------------------------------+
#|{{value123, [{2134479862461603894, subtype1}]}}|
#+-----------------------------------------------+
Run Code Online (Sandbox Code Playgroud)
对于较旧的 Spark 版本,您需要重新创建整个结构才能更新字段,这在存在许多嵌套字段时变得很乏味。在你的情况下,它会是这样的:
df2 = df.withColumn(
"abc",
F.struct(
F.struct(
F.col("abc.xyz.abc123"),
F.expr(
"transform(abc.xyz.services, x -> struct(xxhash64(x.type) as type, x.subtype))"
).alias("services")
).alias("xyz")
)
)
Run Code Online (Sandbox Code Playgroud)