【问题标题】:How to format json string as MongoDB document style using spark/scala?如何使用 spark/scala 将 json 字符串格式化为 MongoDB 文档样式?
【发布时间】:2021-07-10 02:35:42
【问题描述】:

我有一个包含两列 id、json_string 的表,需要将 json_string 转换为 MongoDB 文档格式。我正在将数据从 Spark/Scala 发送到 MongoDB。

我尝试使用 withColumn,但仍然没有得到所需的格式。这是我到目前为止所拥有的,因此非常感谢任何帮助。

原始json字符串样本(df)

val df=spark.sql("select id, json_string from mytable")

{"id":"0001","json_string":"{\"header\": {\"column1\":\"value1\",\"column2\":\"value2\"},\"tail\": [{\"column3\":\"value3\",\"column4\":\"value4\",\"column5\":\"value5\"}]}"}

使用 withColumn (df2) 我得到这个:

val df2=df.withColumn("json_string",from_json(col("json_string"),MapType(StringType,StringType)))

{"id":"0001","json_string":{"header":"{\"column1\":\"value1\",\"column2\":\"value2\"}","tail":"[{\"column3\":\"value3\",\"column4\":\"value4\",\"column5\":\"value5\"}]"}}

所需格式:

{"id":{"$id":"0001"},"header":{"column1":"value1","column2":"value2"},"tail":[{"column3":"value3","column4":"value4","column5":"value5"}]}

Desired format picture sample

【问题讨论】:

    标签: json mongodb scala apache-spark struct


    【解决方案1】:

    您可以动态获取它并将其与from_json 一起使用,而不是手动定义架构

    val json_schema = spark.read.json(df.select("json_string").as[String]).schema
    val df2 = df.withColumn("json_string", from_json(col("json_string"), json_schema))
      .select("id", "json_string.*")
    

    结果:

    +----+----------------+--------------------------+
    |id  |header          |tail                      |
    +----+----------------+--------------------------+
    |0001|{value1, value2}|[{value3, value4, value5}]|
    +----+----------------+--------------------------+
    

    架构:

    root
     |-- id: string (nullable = true)
     |-- header: struct (nullable = true)
     |    |-- column1: string (nullable = true)
     |    |-- column2: string (nullable = true)
     |-- tail: array (nullable = true)
     |    |-- element: struct (containsNull = true)
     |    |    |-- column3: string (nullable = true)
     |    |    |-- column4: string (nullable = true)
     |    |    |-- column5: string (nullable = true)
    

    【讨论】:

    • 太棒了!有效!我为此苦苦挣扎,尝试了许多方法而没有成功。谢谢,非常感谢。
    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多