【问题标题】:Reading multiple JSON files using Spark 2.4 vs Spark 3使用 Spark 2.4 与 Spark 3 读取多个 JSON 文件
【发布时间】:2021-05-13 20:50:21
【问题描述】:

我必须从 Azure 数据湖中读取一堆 JSON 文件。我正在使用 Databricks,当我使用使用 Spark 2.4.5 的集群时,我能够读取所有文件,但是当我使用 Spark 3.0.1 时,返回的数据帧为空。 我正在使用以下命令,

dfa = spark.read.json("dbfs:/mnt/abc/bronze/xyz/history/*.json", multiLine=True)
dfb = dfa.select(explode("result").alias("result"))
dfc.show(truncate = False)
#this returns 0 records with Spark 3 but returns the data when the notebook is attached to Spark 2.4

我尝试了多种选项,例如在读取文件时更改编码,但没有奏效。

文件内容很直接,文件内容类似这样,

{
    "result": [
        {
            "number": "abc123",
            "active": "false",
            "cat_item.category": ""
        }
    ]
}

【问题讨论】:

    标签: apache-spark pyspark azure-databricks


    【解决方案1】:

    想法是从第一条记录中获取架构,然后将其应用于其余数据

    schema1 = T.StructType([
        T.StructField('result', T.StringType()),
    ])
                                           
    
    df = spark.read.json("a.json", multiLine=True, schema=schema1)
    df.show()
    +--------------------+
    |              result|
    +--------------------+
    |[{"number":"abc1..."| <<< string
    +--------------------+
    
    schema2 = F.schema_of_json(df.first()['result'])
    df = df.withColumn('json', F.from_json('result', schema2))
    df.show(10, False)
    df.printSchema()
    +-------------------------------------------------------------+-------------------+
    |result                                                       |json               |
    +-------------------------------------------------------------+-------------------+
    |[{"number":"abc123","active":"false","cat_item.category":""}]|[{false, , abc123}]|
    +-------------------------------------------------------------+-------------------+
    
    root
     |-- result: string (nullable = true)
     |-- json: array (nullable = true)
     |    |-- element: struct (containsNull = true)
     |    |    |-- active: string (nullable = true)
     |    |    |-- cat_item.category: string (nullable = true)
     |    |    |-- number: string (nullable = true)
    
    

    【讨论】:

    • 谢谢@pltc,但我必须读取多个文件,有时列是结构类型,有时是字符串,定义模式是一个问题。在我的情况下,有些文件的类别列是字符串或结构类型。假设该列是结构类型,并且我将架构中的列定义为结构并读取它不显示/显示任何记录的文件,但是当我使用字符串时它确实显示数据但不是作为键值数据格式而不是字符串。
    • 我明白了,不过您的原始问题并不清楚,请查看我的更新答案
    猜你喜欢
    • 2020-10-18
    • 2016-08-18
    • 1970-01-01
    • 2021-12-07
    • 2017-03-05
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多