这是保存模式并将其应用于新 csv 数据的工作示例:
# funcs
from pyspark.sql.functions import *
from pyspark.sql.types import *
# example old df schema w/ long datatype
df = spark.range(10)
df.printSchema()
df.write.mode("overwrite").csv("old_schema")
root
|-- id: long (nullable = false)
# example new df schema we will save w/ int datatype
df = df.select(col("id").cast("int"))
df.printSchema()
root
|-- id: integer (nullable = false)
# get schema as json object
schema = df.schema.json()
# write/read schema to s3 as .txt
import json
with open('s3:/path/to/schema.txt', 'w') as F:
json.dump(schema, F)
with open('s3:/path/to/schema.txt', 'r') as F:
saved_schema = json.load(F)
# saved schema
saved_schema
'{"fields":[{"metadata":{},"name":"id","nullable":false,"type":"integer"}],"type":"struct"}'
# construct saved schema object
new_schema = StructType.fromJson(json.loads(saved_schema))
new_schema
StructType(List(StructField(id,IntegerType,false)))
# use saved schema to read csv files ... new df has int datatype and not long
new_df = spark.read.csv("old_schema", schema=new_schema)
new_df.printSchema()
root
|-- id: integer (nullable = true)