python - 在 Python 中使用包含在 spark.read() 的 json 文件中的模式
问题描述
问题:
- 我的模式转换为 json 是否正确?
- 如何传递 json 文件为 spark.read() 提供模式
我将以下架构硬编码到 python 脚本中,这非常适合我的代码:
schema1 = StructType([
StructField("computer_name", StringType()),
StructField("owner_id", StringType())])
我想将模式从 json 文件中的脚本中移出,所以我进行了以下转换:
{"StructType":[
{"fields":[
{"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
{"metadata":{},"name":"owner_id","nullable":true,"type":"string"},
"type":"struct"}
]
}
我想读取一个文件并使用 json 文件提供我自己的架构:
df=spark.read.option("header", "true").schema(schema_json_file).load(file_names)
这将引发以下错误:
ERROR: schema should be StructType or string
解决方案
以下是我解决问题的方法:
.json 文件:
{"fields":[
{"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
{"metadata":{},"name":"owner_id","nullable":true,"type":"string"}],
"type":"struct"}
Python代码:
schema_file = s3.Object("bucket_name", "prefix")
schema_file = json.loads(schema_file.get()['Body'].read().decode('utf-8'))
custom_schema = StructType.fromJson(schema_file)
df=spark.read.option("header", "true").schema(custom_schema).load(file_names)
就我而言,带有架构的 json 文件位于 S3 位置。
推荐阅读
- javascript - Dhtmlx Gantt 在 XAMPP 工作但不是 VPS 服务器
- postgresql - 在 docker-entrypoint-initdb.d 中运行脚本后,docker-compose postgres 重新启动
- javascript - useRef 挂钩中的“当前”键是什么?
- python - Python C API - PyDict - 是否需要对值和键进行引用计数?
- python - 使用 asyncpg 时如何修复异步代码锁定
- ios - 协议类型“名称”的值不能符合具有通用功能的协议“名称”
- firebase - Vuejs 路由器和 Firebase
- python - 一象限python的具体值
- java - 尝试在 Java 中运行 Selenium 时出错
- r - Ggplot2 改变条的颜色。错误 n 太大,调色板允许的最大值