在 PySpark 中定义 JSON 模式结构的配置文件 [英] Config file to define JSON Schema Structure in PySpark

查看:42
本文介绍了在 PySpark 中定义 JSON 模式结构的配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a PySpark application that reads the JSON file in a dataframe through a defined Schema. code sample below

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

我需要一种方法来找到如何在一种配置或 ini 文件等中定义此架构.并在 PySpark 应用程序的主要内容中读取该内容.

I need a way to find how can I define this schema in a kind of config or ini file etc. And read that in the main the PySpark application.

如果将来有任何需要,这将帮助我修改不断变化的 JSON 的架构,而无需更改主要的 PySpark 代码.

This will help me to modify schema for the changing JSON if there is any need in future without changing the main PySpark code.

推荐答案

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

StructType provides json and jsonValue methods which can be used to obtain json and dict representation respectively and fromJson which can be used to convert Python dictionary to StructType.

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

StructType.fromJson(schema.jsonValue())

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

The only thing you need beyond that is built-in json module to parse input to the dict that can be consumed by StructType.

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

For Scala version see How to create a schema from CSV file and persist/save that schema to a file?

这篇关于在 PySpark 中定义 JSON 模式结构的配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆