【问题标题】:Using schema contained in a json file for spark.read() in Python在 Python 中使用包含在 spark.read() 的 json 文件中的模式
【发布时间】:2021-10-13 14:13:59
【问题描述】:

问题:

  1. 我的模式转换为 json 是否正确?
  2. 如何传递 json 文件为 spark.read() 提供架构

我将以下架构硬编码到 python 脚本中,这非常适合我的代码:

schema1 = StructType([
            StructField("computer_name", StringType()),
            StructField("owner_id", StringType())])

我想将模式从 json 文件中的脚本中移出,所以我进行了以下转换:

{"StructType":[
    {"fields":[
    {"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
    {"metadata":{},"name":"owner_id","nullable":true,"type":"string"},
    "type":"struct"}
    ]
}

我想读取一个文件并使用 json 文件提供我自己的架构:

df=spark.read.option("header", "true").schema(schema_json_file).load(file_names)

这将引发以下错误:

ERROR: schema should be StructType or string

【问题讨论】:

    标签: python json pyspark schema


    【解决方案1】:

    这是我解决问题的方法:

    json 文件:

    {"fields":[
    {"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
    {"metadata":{},"name":"owner_id","nullable":true,"type":"string"}],
    "type":"struct"}
    

    Python 代码:

    schema_file = s3.Object("bucket_name",  "prefix")
    schema_file = json.loads(schema_file.get()['Body'].read().decode('utf-8'))
    custom_schema = StructType.fromJson(schema_file)
    df=spark.read.option("header", "true").schema(custom_schema).load(file_names)
    

    在我的例子中,带有架构的 json 文件位于 S3 位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多