【发布时间】:2017-04-18 20:41:31
【问题描述】:
有没有办法将数据帧模式序列化为 json 并在以后反序列化?
用例很简单: 我有一个 json 配置文件,其中包含我需要读取的数据帧的架构。 我希望能够从现有架构(在数据框中)创建默认配置,并且我希望能够通过从 json 字符串中读取它来生成相关架构以供以后使用。
【问题讨论】:
标签: apache-spark apache-spark-sql
有没有办法将数据帧模式序列化为 json 并在以后反序列化?
用例很简单: 我有一个 json 配置文件,其中包含我需要读取的数据帧的架构。 我希望能够从现有架构(在数据框中)创建默认配置,并且我希望能够通过从 json 字符串中读取它来生成相关架构以供以后使用。
【问题讨论】:
标签: apache-spark apache-spark-sql
这有两个步骤:从现有数据帧创建 json 并从之前保存的 json 字符串创建架构。
从现有数据框创建字符串
val schema = df.schema
val jsonString = schema.json
从 json 创建架构
import org.apache.spark.sql.types.{DataType, StructType}
val newSchema = DataType.fromJson(jsonString).asInstanceOf[StructType]
【讨论】:
我正在为 Assaf 回答的问题发布 pyspark 版本:
from pyspark.sql.types import StructType
# Save schema from the original DataFrame into json:
schema_json = df.schema.json()
# Restore schema from json:
import json
new_schema = StructType.fromJson(json.loads(schema_json))
【讨论】: