python – PySpark,通过JSON文件导入模式
作者:互联网
tbschema.json看起来像这样:
[{"TICKET":"integer","TRANFERRED":"string","ACCOUNT":"STRING"}]
我使用以下代码加载它
>>> df2 = sqlContext.jsonFile("tbschema.json")
>>> f2.schema
StructType(List(StructField(ACCOUNT,StringType,true),
StructField(TICKET,StringType,true),StructField(TRANFERRED,StringType,true)))
>>> df2.printSchema()
root
|-- ACCOUNT: string (nullable = true)
|-- TICKET: string (nullable = true)
|-- TRANFERRED: string (nullable = true)
>当我希望元素的顺序与它们在JSON中出现的顺序相同时,为什么模式元素会被排序.
>在派生JSON之后,数据类型整数已转换为StringType,如何保留数据类型.
解决方法:
Why does the schema elements gets sorted, when i want the elemets in the same order as they appear in the json.
因为不保证领域的顺序.虽然没有明确说明,但是当您查看JSON阅读器doctstring中提供的示例时,这一点很明显.如果您需要特定的订购,您可以手动提供架构:
from pyspark.sql.types import StructType, StructField, StringType
schema = StructType([
StructField("TICKET", StringType(), True),
StructField("TRANFERRED", StringType(), True),
StructField("ACCOUNT", StringType(), True),
])
df2 = sqlContext.read.json("tbschema.json", schema)
df2.printSchema()
root
|-- TICKET: string (nullable = true)
|-- TRANFERRED: string (nullable = true)
|-- ACCOUNT: string (nullable = true)
The data type integer has been converted into StringType after the json has been derived, how do i retain the datatype.
JSON字段TICKET的数据类型是字符串,因此JSON读取器返回字符串.它是JSON读者而不是某种类型的架构读者.
一般来说,您应该考虑一些开箱即用的模式支持的正确格式,例如Parquet,Avro或Protocol Buffers.但是如果您真的想要使用JSON,您可以定义穷人的“模式”解析器,如下所示:
from collections import OrderedDict
import json
with open("./tbschema.json") as fr:
ds = fr.read()
items = (json
.JSONDecoder(object_pairs_hook=OrderedDict)
.decode(ds)[0].items())
mapping = {"string": StringType, "integer": IntegerType, ...}
schema = StructType([
StructField(k, mapping.get(v.lower())(), True) for (k, v) in items])
JSON的问题在于无法保证字段排序,更不用说处理缺少的字段,不一致的类型等等.因此,使用上述解决方案实际上取决于您对数据的信任程度.
标签:python,apache-spark,pyspark,apache-spark-sql,json 来源: https://codeday.me/bug/20191006/1858424.html