【问题标题】:Is there a way to collect the names of all fields in a nested schema in pyspark有没有办法在pyspark的嵌套模式中收集所有字段的名称
【发布时间】:2020-05-06 04:34:26
【问题描述】:

我希望收集嵌套模式中所有字段的名称。数据是从 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)

如果我使用df.schema.fieldsdf.schema.names,它只会打印列层的名称——没有嵌套列。

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

['column_a', 'columb_b', 'column_c.nested_a.double_nested.a', 'column_c.nested_a.double_nested.b', etc...]

如果我想编写自定义函数,信息就在那里 - 但我错过了一个节拍吗?有没有一种方法可以满足我的需要?

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql


    【解决方案1】:

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

    使用this帖子中的代码:

    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']
    

    【讨论】:

    • 如果架构包含数组则不起作用:|-- automatons: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- agentGroup: string (nullable = true) | | |-- automatonAttribute: struct (nullable = true) | | | |-- acif_version: string (nullable = true)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多