如何在 ElasticSearch 中按字段值过滤?

fko*_*sal 5 filter elasticsearch

鉴于以下 ElasticSearch 文档:

{
    "_id": "3330481",
    "_type": "user",
    "_source": {
        "id": "3330481",
        "following": ["1", "2", "3", ... , "15000"]
    }
}
Run Code Online (Sandbox Code Playgroud)

对于给定的用户列表 ["50", "51", "52"] 我想检查 ID 为 3330481 的用户关注哪些用户。由于她关注了 15000 个用户,我不想获取整个列表然后在本地检查。

有没有办法只检索相关用户?

Rah*_*hul 4

我不确定您是否可以从文档中获取子数组。

但是,实现此目的的一种方法是使用嵌套字段。您可以将 following字段的架构更改为nested如下所示。

 {
        "id": "3330481",
        "following": [
              {"userId":"1"}, {"userId":"2"},{"userId": "3"}, ... ]
 }
Run Code Online (Sandbox Code Playgroud)

然后您可以使用inner_hits检索数组中的匹配元素,如下所示。

{
    "query" : {
        "nested" : {
            "path" : "following",
            "query" : {
                "terms" : {"following.userId" : ["50","51","53"]}
            },
            "inner_hits" : {
                "size":0 // fetches all 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)