代码之家  ›  专栏  ›  技术社区  ›  Will

如何在pyspark中访问模式的元数据?

  •  0
  • Will  · 技术社区  · 6 年前

    from pyspark.sql.types import StructField, StructType, IntegerType, StringType
    
    schema = StructType([
        StructField(name='a_field', dataType=IntegerType(), nullable=False, metadata={'a': 'b'}),
        StructField(name='b_field', dataType=StringType(), nullable=True, metadata={'c': 'd'})
    ])
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   Will    6 年前

    您可以通过以下方式查看架构结构:

    >>>schema.json()
    '{"fields":[{"metadata":{"a":"b"},"name":"a_field","nullable":false,"type":"integer"},
                {"metadata":{"c":"d"},"name":"b_field","nullable":true,"type":"string"}],
      "type":"struct"}'
    

    要访问元数据,只需遍历字段并访问元数据(dict)

    >>>schema.fields[0].metadata['a']
    'b'
    
    >>> schema.fields[1].metadata['c']
    'd'