【问题标题】:Create spark dataframe schema from json schema representation从 json 模式表示创建 spark 数据框模式
【发布时间】:2017-04-18 20:41:31
【问题描述】:

有没有办法将数据帧模式序列化为 json 并在以后反序列化?

用例很简单: 我有一个 json 配置文件,其中包含我需要读取的数据帧的架构。 我希望能够从现有架构(在数据框中)创建默认配置,并且我希望能够通过从 json 字符串中读取它来生成相关架构以供以后使用。

【问题讨论】:

    标签: apache-spark apache-spark-sql


    【解决方案1】:

    这有两个步骤:从现有数据帧创建 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]
    

    【讨论】:

      【解决方案2】:

      我正在为 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))
      

      【讨论】:

      • 谢谢!这将我的数据加载速度从几分钟缩短到几秒钟:D
      猜你喜欢
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多