有没有办法收集 pyspark 中嵌套模式中所有字段的名称

Kev*_*ger 2 apache-spark apache-spark-sql pyspark

我希望收集嵌套模式中所有字段的名称。数据是从 json 文件导入的。

该架构如下所示:

root
 |-- column_a: string (nullable = true)
 |-- column_b: string (nullable = true)
 |-- column_c: struct (nullable = true)
 |    |-- nested_a: struct (nullable = true)
 |    |    |-- double_nested_a: string (nullable = true)
 |    |    |-- double_nested_b: string (nullable = true)
 |    |    |-- double_nested_c: string (nullable = true)
 |    |-- nested_b: string (nullable = true)
 |-- column_d: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

如果我使用df.schema.fieldsordf.schema.names它只是打印列层的名称 - 没有嵌套列。

我想要的期望输出是一个 python 列表,其中包含所有列名称,例如:

['column_a', 'columb_b', 'column_c.nested_a.double_nested.a', 'column_c.nested_a.double_nested.b', etc...]
Run Code Online (Sandbox Code Playgroud)

如果我想编写自定义函数,该信息就存在 - 但我是否错过了一个节拍?是否存在一种方法可以实现我所需要的?

Shu*_*Shu 5

默认情况下,Spark 没有任何方法让我们扁平化模式名称。

使用这篇文章中的代码:

def flatten(schema, prefix=None):
    fields = []
    for field in schema.fields:
        name = prefix + '.' + field.name if prefix else field.name
        dtype = field.dataType
        if isinstance(dtype, ArrayType):
            dtype = dtype.elementType

        if isinstance(dtype, StructType):
            fields += flatten(dtype, prefix=name)
        else:
            fields.append(name)

    return fields


df.printSchema()
#root
# |-- column_a: string (nullable = true)
# |-- column_c: struct (nullable = true)
# |    |-- nested_a: struct (nullable = true)
# |    |    |-- double_nested_a: string (nullable = true)
# |    |-- nested_b: string (nullable = true)
# |-- column_d: string (nullable = true)

sch=df.schema

print(flatten(sch))
#['column_a', 'column_c.nested_a.double_nested_a', 'column_c.nested_b', 'column_d']
Run Code Online (Sandbox Code Playgroud)