Apache spark 如何使用Spark查询json文件的嵌套数组类型?
如何使用Spark数据集使用联接查询嵌套数组类型 目前,我正在分解数组类型,并在数据集上执行join操作,其中需要删除匹配的数据。但是有没有一种方法可以让我直接查询它而不会爆炸呢Apache spark 如何使用Spark查询json文件的嵌套数组类型?,apache-spark,apache-spark-sql,Apache Spark,Apache Spark Sql,如何使用Spark数据集使用联接查询嵌套数组类型 目前,我正在分解数组类型,并在数据集上执行join操作,其中需要删除匹配的数据。但是有没有一种方法可以让我直接查询它而不会爆炸呢 { "id": 525, "arrayRecords": [ { "field1": 525, "field2": 0 }, { "field1": 537, "field2": 1 } ] } 代码 val df = sql
{
"id": 525,
"arrayRecords": [
{
"field1": 525,
"field2": 0
},
{
"field1": 537,
"field2": 1
}
]
}
代码
val df = sqlContext.read.json("jsonfile")
val someDF = Seq(("1"),("525"),("3")).toDF("FIELDIDS")
val withSRCRec =df.select($"*",explode($"arrayRecords")as("exploded_arrayRecords"))
val fieldIdMatchedDF= withSRCRec.as("table1").join(someDF.as("table2"),$"table1.exploded_arrayRecords.field1"===$"table2.FIELDIDS").select($"table1.exploded_arrayRecords.field1")
val finalDf = df.as("table1").join(fieldIdMatchedDF.as("table2"),$"table1.id"===$"table2.id","leftanti")
需要删除具有FieldID的Id记录您可以基于数据集注册一个临时表,并使用SQL查询它。应该是这样的:
someDs.registerTempTable("sometable");
sql("SELECT array['field'] FROM sometable");
您可以使用
array\u,但
除外:
array\u except(col1:Column,col2:Column):Column返回第一个数组中的元素数组,但不返回第二个数组中的元素数组,且不存在重复项。结果中元素的顺序不确定
解决办法如下:
val input = spark.read.option("multiLine", true).json("input.json")
scala> input.show(false)
+--------------------+---+
|arrayRecords |id |
+--------------------+---+
|[[525, 0], [537, 1]]|525|
+--------------------+---+
// Since field1 is of type int, let's convert the ids to ints
// You could do this in Scala directly or in Spark SQL's select
val fieldIds = Seq("1", "525", "3").toDF("FIELDIDS").select($"FIELDIDS" cast "int")
// Collect the ids for array_except
val ids = fieldIds.select(collect_set("FIELDIDS") as "ids")
// The trick is to crossJoin (it is cheap given 1-row ids dataset)
val solution = input
.crossJoin(ids)
.select(array_except($"arrayRecords.field1", $"ids") as "unmatched")
scala> solution.show
+---------+
|unmatched|
+---------+
| [537]|
+---------+
是否只想筛选出
字段1
中的ID?具有字段ID的数据框中可以有多少个元素?