简体   繁体   English

Elasticsearch-如何使用嵌套字段过滤数据

[英]Elasticsearch - How to filter data with nested fields

Below are few documents with tags as nested field. 以下是一些带有标签作为嵌套字段的文档。 Is it possible to filter the results to get the documents which has both tags.id = 21 and tags.id = 22 ? 是否可以过滤结果以获取同时具有tags.id = 21tags.id = 22的文档?

{
  "title": "Nokia",
  "tags": [
    {
      "id": 21
    },
    {
      "id": 22
    }
  ]  
}

{
  "title": "HTC",
  "tags": [
    {
      "id": 21
    },
    {
      "id": 23
    }
  ]  
}

{
  "title": "Samsung",
  "tags": [
    {
      "id": 21
    },
    {
      "id": 22
    }
  ]  
}

In this case the result should return the documents with title Nokia and Samsung 在这种情况下,结果应返回标题为诺基亚和三星的文档

You can use a boolean query: 您可以使用布尔查询:

GET my_index/_search
{
    "query": {
        "bool": {
            "filter": [
                {"match": {"tags.id": 21}},
                {"match": {"tags.id": 22}}
            ]
        }
    }
}

Below is the query for searching in the situation as mentioned in the question 以下是问题中提到的情况下的搜索查询

{
    "query": {
        "bool": {
            "filter": [
                {
                    "nested":{
                        "path":"tags",
                        "query":{
                            "bool":{
                                "filter":[
                                    {"term": {"tags.id": 21}}
                                ]
                            }
                        }
                    }
                },
                {
                    "nested":{
                        "path":"tags",
                        "query":{
                            "bool":{
                                "filter":[
                                    {"term": {"tags.id": 22}}
                                ]
                            }
                        }
                    }
                }

            ]
        }
    }
}

The mistake that i was doing was putting in the 2 match blocks under the same filter block. 我所做的错误是将2个匹配块放在同一过滤器块下。

"filter":[
    {"term": {"tags.id": 21}},
    {"term": {"tags.id": 22}}
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM