zt1*_*811 2 scala dataframe elasticsearch apache-spark apache-spark-sql
我正在使用带有elasticsearch的apache spark 1.5数据帧,我尝试从包含id列表(数组)的列中过滤id.
例如,elasticsearch列的映射如下所示:
{
"people":{
"properties":{
"artist":{
"properties":{
"id":{
"index":"not_analyzed",
"type":"string"
},
"name":{
"type":"string",
"index":"not_analyzed",
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
示例数据格式如下所示
{
"people": {
"artist": {
[
{
"id": "153",
"name": "Tom"
},
{
"id": "15389",
"name": "Cok"
}
]
}
}
},
{
"people": {
"artist": {
[
{
"id": "369",
"name": "Carl"
},
{
"id": "15389",
"name": "Cok"
},
{
"id": "698",
"name": "Sol"
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
在火花中我试试这个:
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")
Run Code Online (Sandbox Code Playgroud)
我得到了包含152的所有id,例如1523,152978,但不仅是id == 152
然后我试了一下
dataFrame.filter(dataFrame("people.artist.id").equalTo(peopleId))
.select("people.artist.id")
Run Code Online (Sandbox Code Playgroud)
我变空了,我理解为什么,这是因为我有一系列的people.artist.id
当有我的ID列表时,有谁能告诉我如何过滤?
在Spark 1.5+中,您可以使用以下array_contains
功能:
df.where(array_contains($"people.artist.id", "153"))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是早期版本,可以尝试这样的UDF:
val containsId = udf(
(rs: Seq[Row], v: String) => rs.map(_.getAs[String]("id")).exists(_ == v))
df.where(containsId($"people.artist", lit("153")))
Run Code Online (Sandbox Code Playgroud)