[英]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.