簡體   English   中英

在 PySpark 中定義 JSON 模式結構的配置文件

[英]Config file to define JSON Schema Structure in PySpark

我創建了一個 PySpark 應用程序,它通過定義的架構讀取數據幀中的 JSON 文件。 下面的代碼示例

schema = StructType([
    StructField("domain", StringType(), True),
     StructField("timestamp", LongType(), True),                            
])
df= sqlContext.read.json(file, schema)

我需要一種方法來找到如何在一種配置或 ini 文件等中定義此模式。並在 PySpark 應用程序的主應用程序中讀取該模式。

如果將來有任何需要,這將幫助我修改不斷變化的 JSON 的架構,而無需更改主要的 PySpark 代碼。

StructType提供了jsonjsonValue方法,可分別用於獲取jsondict表示, fromJson可用於將 Python 字典轉換為StructType

schema = StructType([
    StructField("domain", StringType(), True),
    StructField("timestamp", LongType(), True),                            
])

StructType.fromJson(schema.jsonValue())

除此之外,您唯一需要的是內置json模塊來解析StructType可以使用的dict輸入。

對於 Scala 版本,請參閱如何從 CSV 文件創建架構並將該架構持久化/保存到文件?

您可以使用以下格式創建一個名為 schema.json 的 JSON 文件

{
  "fields": [
    {
      "metadata": {},
      "name": "first_fields",
      "nullable": true,
      "type": "string"
    },
    {
      "metadata": {},
      "name": "double_field",
      "nullable": true,
      "type": "double"
    }
  ],
  "type": "struct"
}

通過讀取此文件創建結構架構

rdd = spark.sparkContext.wholeTextFiles("s3://<bucket>/schema.json")
text = rdd.collect()[0][1]
dict = json.loads(str(text))
custom_schema = StructType.fromJson(dict)

之后,您可以使用 struct 作為架構來讀取 JSON 文件

val df=spark.read.json("path", custom_schema)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM