按 Spark DataFrame 中的数组值过滤

Filter by array value in Spark DataFrame

我正在使用带有 elasticsearch 的 apache spark 1.5 数据框,我尝试从包含 id 列表(数组)的列中过滤 id。

例如 elasticsearch 列的映射是这样的:

    {
        "people":{
            "properties":{
                "artist":{
                   "properties":{
                      "id":{
                         "index":"not_analyzed",
                         "type":"string"
                       },
                       "name":{
                          "type":"string",
                          "index":"not_analyzed",
                       }
                   }
               }
          }
    }

示例数据格式如下

{
    "people": {
        "artist": {
            [
                  {
                       "id": "153",
                       "name": "Tom"
                  },
                  {
                       "id": "15389",
                       "name": "Cok"
                  }
            ]
        }
    }
},
{
    "people": {
        "artist": {
            [
                  {
                       "id": "369",
                       "name": "Carl"
                  },
                  {
                       "id": "15389",
                       "name": "Cok"
                  },
                 {
                       "id": "698",
                       "name": "Sol"
                  }
            ]
        }
    }
}

在 spark 中我试试这个:

val peopleId  = 152
val dataFrame = sqlContext.read
     .format("org.elasticsearch.spark.sql")
     .load("index/type")

dataFrame.filter(dataFrame("people.artist.id").contains(peopleId))
    .select("people_sequence.artist.id")

我得到了所有包含 152 的 id,例如 1523 、 152978 但不仅是 id == 152

然后我试了

dataFrame.filter(dataFrame("people.artist.id").equalTo(peopleId))
    .select("people.artist.id")

我变空了,我明白为什么,因为我有 people.artist.id

数组

谁能告诉我当我有 ID 列表时如何过滤?

在 Spark 1.5+ 中你可以使用 array_contains 函数:

df.where(array_contains($"people.artist.id", "153"))

如果您使用的是早期版本,您可以尝试这样的 UDF:

val containsId = udf(
  (rs: Seq[Row], v: String) => rs.map(_.getAs[String]("id")).exists(_ == v))
df.where(containsId($"people.artist", lit("153")))