Scala 通过传入要匹配的值列表,过滤出数据帧(JSON)中的嵌套数组项

Scala 通过传入要匹配的值列表,过滤出数据帧(JSON)中的嵌套数组项,scala,apache-spark,apache-spark-sql,rdd,Scala,Apache Spark,Apache Spark Sql,Rdd,我在一个数据框中读取了一个巨大的文件,其中每行包含一个JSON对象,如下所示: { "userId": "12345", "vars": { "test_group": "group1", "brand": "xband" }, "modules": [ { "id": "New" }, { "id": "Default" }, { "id": "BestValue" },

我在一个数据框中读取了一个巨大的文件,其中每行包含一个JSON对象,如下所示:

{
  "userId": "12345",
  "vars": {
    "test_group": "group1",
    "brand": "xband"
  },
  "modules": [
    {
      "id": "New"
    },
    {
      "id": "Default"
    },
    {
      "id": "BestValue"
    },
    {
      "id": "Rating"
    },
    {
      "id": "DeliveryMin"
    },
    {
      "id": "Distance"
    }
  ]
}
我想向一个方法传递一个模块id-s列表,并清除所有不属于该模块id-s列表的项。它应该删除所有其他模块,这些模块的id不等于传入列表中的任何值

您有解决方案吗?

正如您从读取
json
文件和操作
modules
列(其中包含
schema
所知道的那样

root
 |-- modules: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
这表示
模块
struct[String]
的集合。对于当前需求,您必须将
数组[struct[String]]
转换为
数组[String]

val finaldf = df.withColumn("modules", explode($"modules.id"))
                  .groupBy("userId", "vars").agg(collect_list("modules").as("modules"))
下一步是将
udf
函数定义为

def contains = udf((list: mutable.WrappedArray[String]) => {
  val validModules = ??? //your array definition here for example : Array("Default", "BestValue")
  list.filter(validModules.contains(_))
})
finaldf.withColumn("modules", contains($"modules")).show(false)
只需将
udf
函数调用为

def contains = udf((list: mutable.WrappedArray[String]) => {
  val validModules = ??? //your array definition here for example : Array("Default", "BestValue")
  list.filter(validModules.contains(_))
})
finaldf.withColumn("modules", contains($"modules")).show(false)

应该是这样。我希望答案是有帮助的。

谢谢@Ramesh!差不多了,但是我不想让模块作为字符串数组,而是作为JSON对象的列表,例如{“id”:“Default”}。其次,为什么我必须定义我想保留在groupBy()方法中的所有列?还有其他方法吗?第三件事:validModules必须作为方法传入parameters@esbej,您在问题
**“我想向一个方法传递一个模块id-s列表”**
,其次我使用了
“userId”,“vars”
在groupBy中,以便在使用collect_list时保留数组中的字符串,以便仅收集分解的字符串。对于第三个注释,是否希望将各种ValidModule作为参数传递?如果是,你能提供一些例子吗。