Python PySpark,通过JSON文件导入模式
Python PySpark,通过JSON文件导入模式,python,json,apache-spark,pyspark,apache-spark-sql,Python,Json,Apache Spark,Pyspark,Apache Spark Sql,tbschema.json如下所示: [{"TICKET":"integer","TRANFERRED":"string","ACCOUNT":"STRING"}] 我使用以下代码加载它 >>> df2 = sqlContext.jsonFile("tbschema.json") >>> f2.schema StructType(List(StructField(ACCOUNT,StringType,true), StructField(TICKET
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)
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)
派生json后,数据类型integer已转换为StringType,如何保留该数据类型
JSON字段TICKET
的数据类型是string,因此JSON读取器返回string。它是JSON读取器,而不是某种模式读取器
一般来说,你应该考虑一些有格式支持的适当格式,例如,或。但如果你真的想玩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的问题在于,对于字段的排序并没有任何保证,更不用说处理缺少的字段、不一致的类型等等了。所以,使用上述解决方案实际上取决于您对数据的信任程度
或者,您可以使用。有趣的解决方案,是否有任何特殊原因导致
IntergerType()
之后的()
被移动到结构的创建中,而不是在映射中?这将允许您执行一个DecimalType(x,y)
。。谢谢,真的很有帮助!