【发布时间】:2018-05-21 18:40:53
【问题描述】:
目前,如果我想使用 pyspark 读取 json,我要么使用受干扰的架构,要么必须手动定义我的架构 StructType
是否可以使用文件作为架构的参考?
【问题讨论】:
目前,如果我想使用 pyspark 读取 json,我要么使用受干扰的架构,要么必须手动定义我的架构 StructType
是否可以使用文件作为架构的参考?
【问题讨论】:
您确实可以使用文件来定义您的架构。例如,对于以下架构:
TICKET:string
TRANSFERRED:string
ACCOUNT:integer
您可以使用此代码导入它:
import csv
from collections import OrderedDict
from pyspark.sql.types import StructType, StructField, StringType,IntegerType
schema = OrderedDict()
with open(r'schema.txt') as csvfile:
schemareader = csv.reader(csvfile, delimiter=':')
for row in schemareader:
schema[row[0]]=row[1]
然后您可以使用它即时创建您的StructType 架构:
mapping = {"string": StringType, "integer": IntegerType}
schema = StructType([
StructField(k, mapping.get(v.lower())(), True) for (k, v) in schema.items()])
您可能需要为 JSON 文件创建一个更复杂的架构文件,但是请注意,您不能使用 JSON 文件来定义您的架构,因为在解析 JSON 时无法保证列的顺序。
【讨论】: