【问题标题】:use pre-defined schema in pyspark json在 pyspark json 中使用预定义的模式
【发布时间】:2018-05-21 18:40:53
【问题描述】:

目前,如果我想使用 pyspark 读取 json,我要么使用受干扰的架构,要么必须手动定义我的架构 StructType

是否可以使用文件作为架构的参考?

【问题讨论】:

    标签: json pyspark schema


    【解决方案1】:

    您确实可以使用文件来定义您的架构。例如,对于以下架构:

    TICKET:string 
    TRANSFERRED:string 
    ACCOUNT:integer
    

    您可以使用此代码导入它:

    import csv
    from collections import OrderedDict 
    from pyspark.sql.types import StructType, StructField, StringType,IntegerType
    
    schema = OrderedDict()
    with open(r'schema.txt') as csvfile:
        schemareader = csv.reader(csvfile, delimiter=':')
        for row in schemareader:
            schema[row[0]]=row[1]
    

    然后您可以使用它即时创建您的StructType 架构:

    mapping = {"string": StringType, "integer": IntegerType}
    
    schema = StructType([
        StructField(k, mapping.get(v.lower())(), True) for (k, v) in schema.items()])
    

    您可能需要为 JSON 文件创建一个更复杂的架构文件,但是请注意,您不能使用 JSON 文件来定义您的架构,因为在解析 JSON 时无法保证列的顺序。

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2020-11-04
      • 2017-11-19
      • 2014-10-16
      相关资源
      最近更新 更多