配置文件以在PySpark中定义JSON Schema Struture

Pun*_*bar 4 python apache-spark apache-spark-sql pyspark

我创建了一个PySpark应用程序,它通过定义的Schema读取数据帧中的JSON文件.下面的代码示例

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

我需要一种方法来找到如何在一种配置或ini文件等中定义此模式.并在主要的PySpark应用程序中阅读.

如果将来有任何需要而不更改主PySpark代码,这将帮助我修改更改JSON的模式.

感谢任何帮助,谢谢.

zer*_*323 8

StructType提供jsonjsonValue方法,可以分别用于获取jsondict表示fromJson,并可用于将Python字典转换为StructType.

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

StructType.fromJson(schema.jsonValue())
Run Code Online (Sandbox Code Playgroud)

除此之外,您唯一需要的是内置json模块来解析dict可以使用的输入StructType.

对于Scala版本,请参阅如何从CSV文件创建架构并将该架构保存/保存到文件中?

  • 很好的答案,不知道为什么它不被接受.:) (2认同)