json - 使用 Spark 访问嵌套在结构中的 json 数组

标签 json scala apache-spark

我希望从具有数组的嵌套相当深的结构中访问不同的字段/子字段,以便对它们进行算术运算。一些数据实际上是在字段名称本身中(我必须访问的结构是以这种方式创建的,对此我无能为力)。特别是,我有一个数字列表作为我必须使用的字段名称,这些会从一个 json 文件更改为下一个,因此我必须动态推断这些字段名称是什么,然后将它们与子字段值一起使用。

我看过这个:Access names of fields in struct Spark SQL 不幸的是,我不知道我的结构的字段名称是什么,所以我不能使用它。

我也尝试过这个,看起来很有希望:how to extract the column name and data type from nested struct type in spark 不幸的是,无论“flatten”函数的魔力如何,我都无法将其调整为字段名而不是字段本身。

这是一个示例 json 数据集。它代表消费篮子:

  • “comp A”和“comp B”这两个篮子中的每一个都有多个价格作为子字段:compA.'55.80' 是一个价格,compA.'132.88' 是另一个价格,等等。
  • 我希望将这些单价与其各自子字段中的可用数量相关联:compA.'55.80'.comment[0].qty (500) 以及 compA.'55.80'.comment[0].qty (600),两者都应与 55.80 相关联。 compA.'132.88'.comment[0].qty (700) 应该关联到 132.88。等
{"type":"test","name":"john doe","products":{
    "baskets":{
        "comp A":{
            "55.80":[{"type":"fun","comment":{"qty":500,"text":"hello"}},{"type":"work","comment":{"qty":600,"text":"hello"}}]
            ,"132.88":[{"type":"fun","comment":{"qty":700,"text":"hello"}}]
            ,"0.03":[{"type":"fun","comment":{"qty":500,"text":"hello"}},{"type":"work","comment":{"qty":600,"text":"hello"}}]
        }
        ,"comp B":{
            "55.70":[{"type":"fun","comment":{"qty":500,"text":"hello"}},{"type":"work","comment":{"qty":600,"text":"hello"}}]
            ,"132.98":[{"type":"fun","comment":{"qty":300,"text":"hello"}},{"type":"work","comment":{"qty":900,"text":"hello"}}]
            ,"0.01":[{"type":"fun","comment":{"qty":400,"text":"hello"}}]
        }
    }
}}

我想在数据框中获取所有这些数字,以便对它们进行一些操作:

+ -------+---------+----------+
+ basket | price   | quantity +
+ -------+---------+----------+
+ comp A | 55.80   | 500      +
+ comp A | 55.80   | 600      +
+ comp A | 132.88  | 700      +
+ comp A | 0.03    | 500      +
+ comp A | 0.03    | 600      +
+ comp B | 55.70   | 500      +
+ comp B | 55.70   | 600      +
+ comp B | 132.98  | 300      +
+ comp B | 132.98  | 900      +
+ comp B | 0.01    | 400      +
+ -------+---------+----------+

原始数据集是这样访问的:

scala> myDs
res135: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [products: struct<baskets: struct<compA: struct<55.80: array<struct .....

最佳答案

这种处理以列名形式出现的数据的方法不是可遵循的方法。它根本行不通。

关于json - 使用 Spark 访问嵌套在结构中的 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918109/

相关文章:

ios - 解析YouTube JSON以获取UITableView

scala - onComplete 和 foreach 在 Scala 中的 future 有什么区别?

java - 序列化对象时包含外部变量

java - 如何根据 JavaRDD<ObjectHandler> 对象中的特定列查找不同元素?

apache-spark - 获取Spark作业的应用运行ID

c# - 无法从 json 结果 MVC 4 中检索值

json - 使用 Rest Api 的 Xamarin 中的 ListView

objective-c - Xcode : How to add Protocol to a socket Connection and send JSON data

scala - 在 Scala 中实现 Java 接口(interface)方法

pandas - 对 UserWarning : pyarrow. open_stream 的任何修复均已弃用,请使用 pyarrow.ipc.open_stream?