AWS GLUE:使用 Pyspark 重命名结构中的字段名称



这里提到的架构是我在 AWS Glue 中使用 Unnest 转换后原始架构的一部分。

profile.details.indices.index: array
|    |-- element: struct
|    |    |-- profile.details.indices.index.val.indexname: string
|    |    |-- profile.details.indices.index.val.indexsymbol: string

我的要求是使用pyspark将结构内两个字段的名称("profile.details.indices.index.val.indexname"和"profile.details.index.index.val.indexname"(分别更改为indexnameindexsymbol

Glue 中的重命名字段转换不适用于结构内的字段,它产生相同的架构。经过一些研究,我发现我必须创建一个 UDF 来重命名结构中的字段,因为我是 Pyspark 的新手,任何人都可以告诉我如何实现我的要求。

经过一些研究,我能够在这个博客的帮助下找到我的问题的解决方案:https://medium.com/@lvhuyen/working-with-spark-dataframe-having-a-complex-schema-a3bce8c3f44。在此处发布答案,以防有人有相同的查询。

我通过更改字段名称为特定列创建了一个新架构,并在数据框中强制转换了该列的架构

from pyspark.sql.functions import col
from pyspark.sql.types import (
ArrayType, LongType, StringType, StructField, StructType)
struct_schema = ArrayType(StructType([
StructField("indexname", StringType()),
StructField("indexsymbol", StringType()),
]))
df_renamed = df.withColumn("profile.details.indices.index", col("`profile.details.indices.index`").cast(struct_schema))

现在数据帧架构如下所示

|-- profile.details.indices.index: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- indexname: string (nullable = true)
|    |    |-- indexsymbol: string (nullable = true)

还有其他解决方案,但由于我的原始架构有 100 多个其他字段,我发现此解决方案有助于更改特定的嵌套列并保留旧架构

最新更新