PySpark,通过JSON文件导入模式

sac*_*hin 6 python json apache-spark apache-spark-sql pyspark

tbschema.json 看起来像这样:

[{"TICKET":"integer","TRANFERRED":"string","ACCOUNT":"STRING"}]
Run Code Online (Sandbox Code Playgroud)

我使用以下代码加载它

>>> 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)
Run Code Online (Sandbox Code Playgroud)
  1. 当我希望元素的顺序与它们在JSON中出现的顺序相同时,为什么模式元素会被排序.

  2. 在派生JSON之后,数据类型整数已转换为StringType,如何保留数据类型.

zer*_*323 7

当我希望元素与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)
Run Code Online (Sandbox Code Playgroud)

派生json后,数据类型整数已转换为StringType,我该如何保留数据类型。

JSON字段的数据类型TICKET为字符串,因此JSON阅读器返回字符串。它是JSON阅读器,而不是某种形式的阅读器。

通常来说,您应该考虑现成的架构支持随附的某种适当格式,例如ParquetAvroProtocol 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])
Run Code Online (Sandbox Code Playgroud)

JSON的问题在于,对于字段的排序确实没有任何保证,更不用说处理丢失的字段,类型不一致等了。因此,使用上述解决方案实际上取决于您对数据的信任程度。

或者,您可以使用内置的架构导入/导出实用程序