[英]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
提供了json
和jsonValue
方法,可分別用於獲取json
和dict
表示, 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.