如何读取嵌套的JSON以进行聚合?

我是Spark的新手。 我想要做的就是读取嵌套的jsons并根据特定条件对它们进行分组。 例如:如果json包含像他的城市和邮政编码这样的人的详细信息。 我想对属于同一城市和邮政编码的人进行分组。

我已经取得了进展,直到将jsons读入DataSet。 但我不知道如何将它们分组。

我的嵌套JSON格式是

{ "entity": { "name": "SJ", "id": 31 }, "hierarchy": { "state": "TN", "city": "CBE" }, "data": {}} 

这是我编写的用于从文件中读取嵌套json的代码。

 public void groupJsonString(SparkSession spark) { Dataset studentRecordDS = spark.read() .option("timestampFormat", "yyyy/MM/dd HH:mm:ss ZZ") .json("/home/shiney/Documents/NGA/sparkJsonFiles/*.json"); StructType st = studentRecordDS.schema(); List nestedList = new ArrayList(); for(StructField field : st.fields()) { nestedList.add((StructType)field.dataType()); } } 

TL; DR使用spark.read.json (正如你所做的那样),然后select “flatten”运算符。

(我使用Scala并将转换为Java作为你的家庭练习:))

让我们使用你的样本。

 $ cat ../datasets/sample.json { "entity": { "name": "SJ", "id": 31 }, "hierarchy": { "state": "TN", "city": "CBE" }, "data": {} } 

代码可能如下(再次是Scala)。

 val entities = spark .read .option("multiLine", true) .json("../datasets/sample.json") scala> entities.printSchema root |-- entity: struct (nullable = true) | |-- id: long (nullable = true) | |-- name: string (nullable = true) |-- hierarchy: struct (nullable = true) | |-- city: string (nullable = true) | |-- state: string (nullable = true) 

让我们展平entityhierarchy顶级列。

 scala> entities.select("entity.*", "hierarchy.*").show +---+----+----+-----+ | id|name|city|state| +---+----+----+-----+ | 31| SJ| CBE| TN| +---+----+----+-----+ 

现在聚合应该是明智的。