【问题标题】:How to create DataFrame Schema from Json schem file如何从 Json schem 文件创建 DataFrame Schema
【发布时间】:2019-08-08 16:59:08
【问题描述】:

我的用例是读取一个现有的 json-schema 文件,解析这个 json-schema 文件并从中构建一个 Spark DataFrame 模式。首先,我按照here 中提到的步骤操作。

遵循的步骤
1.从Maven导入库
2.重启集群
3.创建了一个示例 JSON 模式文件
4.使用此代码读取示例模式文件
val schema = SchemaConverter.convert("/FileStore/tables/schemaFile.json")

当我运行上面的命令时,我得到error: not found: value SchemaConverter

为了确保调用库,我在重新启动集群后将笔记本重新附加到集群。

除了尝试上述方法之外,我还尝试了以下方法。我用实际的 JSON 模式替换了 jsonString。

import org.apache.spark.sql.types.{DataType, StructType} val newSchema = DataType.fromJson(jsonString).asInstanceOf[StructType]

我一直在使用的示例模式有 300 多个 feild,为简单起见,我使用了来自 here 的示例模式。

【问题讨论】:

    标签: scala apache-spark databricks


    【解决方案1】:

    SchemaConverter 为我工作。我使用spark-shell 测试并安装所需的包为spark-shell --packages "org.zalando:spark-json-schema_2.11:0.6.1"

    scala> val schema = SchemaConverter.convertContent("""
     | {
     |   "$schema": "http://json-schema.org/draft-04/schema#",
     |   "title": "Product",
     |   "description": "A product from Acme's catalog",
     |   "type": "object",
     |   "properties": {
     |     "id": {
     |       "description": "The unique identifier for a product",
     |       "type": "integer"
     |     },
     |     "name": {
     |       "description": "Name of the product",
     |       "type": "string"
     |     },
     |     "price": {
     |       "type": "number",
     |       "minimum": 0,
     |       "exclusiveMinimum": true
     |     }
     |   },
     |   "required": [
     |     "id",
     |     "name",
     |     "price"
     |   ]
     | }
     | """)
    
    schema: org.apache.spark.sql.types.StructType = StructType(StructField(id,LongType,false), StructField(name,StringType,false), StructField(price,DoubleType,false))
    
    scala> schema.toString
    res1: String = StructType(StructField(id,LongType,false), StructField(name,StringType,false), StructField(price,DoubleType,false))
    

    你想在读取 json 数据时显式指定 schema 吗?因为如果你使用 spark 读取 json 数据,它会自动从 json 数据推断 schema。例如。

    val df = spark.read.json("json-file")
    df.printSchema() // Gives schema of json data
    

    【讨论】:

    • 之所以要特别提及架构,是因为我有一个字段,当仅存在 1 个值时,有时会以字符串形式出现,而当存在多个值时,会以数组形式出现。作为一种解决方法,我希望提供模式可以帮助一致地阅读该领域。我在 Databricks 中试过这个,不确定它的 Databricks 设置是否阻止了库被调用。将在 spark-shell 中尝试它,看看这是否有效。干杯。
    猜你喜欢
    • 2021-12-08
    • 2020-05-07
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多