【问题标题】:Spark Scala nested JSON stored as structure tableSpark Scala 嵌套 JSON 存储为结构表
【发布时间】:2018-09-12 11:07:24
【问题描述】:

我有大量的嵌套 JSON,有超过 200 个键要转换并存储在结构表中。

  |-- ip_address: string (nullable = true)
  |-- xs_latitude: double (nullable = true)
  |-- Applications: array (nullable = true)
  |    |-- element: struct (containsNull = true)
  |    |    |-- b_als_o_isehp: string (nullable = true)
  |    |    |-- b_als_p_isehp: string (nullable = true)
  |    |    |-- b_als_s_isehp: string (nullable = true)
  |    |    |-- l_als_o_eventid: string (nullable = true)
                 ....

读取 JSON 并获取每个 ip_address 具有一个应用程序数组数据

 {"ip_address": 1512199720,"Applications": [{"s_pd": -1,"s_path": "NA", "p_pd": "temp0"}, {"s_pd": -1,"s_path": "root/hdfs", "p_pd": "temp1"},{"s_pd": -1,"s_path": "root/hdfs", "p_pd": "temp2"}],}

val data = spark.read.json("file:///root/users/data/s_json.json")
 var appDf = data.withColumn("data",explode($"Applications")).select($"Applications.s_pd", $"Applications.s_path", $"Applications.p_pd", $"ip_address")
 appDf.printSchema
/// gives 
root
  |-- s_pd: array (nullable = true)
  |    |-- element: string (containsNull = true)
  |-- s_path: array (nullable = true)
  |    |-- element: string (containsNull = true)
  |-- p_pd: array (nullable = true)
  |    |-- element: string (containsNull = true)
  |-- ip_address: string (nullable = true)

在每个数据帧记录中包含一个包含重复记录的数组。如何获取表格格式的记录。

【问题讨论】:

  • 在我的头顶上,您可以尝试appDf.select("ip_addres", "xs_latitude", "Applications.*") 来平整这样的结构。还是任意深度嵌套?

标签: json scala apache-spark dataframe


【解决方案1】:

错误

您的错误是您正在使用原始 (Application) 结构列来选择单独列中的嵌套结构

解决方案

您必须从展开的列中选择data

var appDf = data.withColumn("data",explode($"Applications"))
  .select($"ip_address", $"data.s_pd", $"data.s_path", $"data.p_pd")

你应该得到

+----------+----+---------+-----+
|ip_address|s_pd|s_path   |p_pd |
+----------+----+---------+-----+
|1512199720|-1  |NA       |temp0|
|1512199720|-1  |root/hdfs|temp1|
|1512199720|-1  |root/hdfs|temp2|
+----------+----+---------+-----+

希望回答对你有帮助

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2018-03-15
    • 2020-12-02
    • 2016-07-19
    • 2014-06-19
    • 2022-10-16
    • 2019-09-26
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多