如果文档在Elasticsearch中包含多个嵌套文档,则匹配该文档

Joh*_*n K 1 elasticsearch

我有一个包含嵌套文档数组的文档。如果文档包含所有指定的嵌套文档,我需要返回匹配项。

这是映射的相关部分:

"element": {
  "dynamic": "false",
  "properties": {
    "tenantId": {
      "type": "string",
      "index": "not_analyzed"
    },
    "fqn": {
      "type": "string",
      "index": "not_analyzed"
    },
    "id": {
      "type": "string",
      "index": "not_analyzed"
    },
    "name": {
      "type": "string",
      "index": "not_analyzed"
    },
    "type": {
      "type": "string",
      "index": "not_analyzed"
    },
    "location": {
      "type": "string",
      "index": "not_analyzed"
    },
    "tags": {
      "type": "nested",
      "properties": {
        "id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "dataSourceId": {
          "type": "long",
          "index": "not_analyzed"
        },
        "name": {
          "type": "string",
          "index": "not_analyzed"
        },
        "value": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

目的是能够返回包含所有标签列表的元素(尽管允许该元素包含超出搜索要求的其他标签)。

这是我到目前为止的内容:

{
   "query": {
     "bool": {
       "filter": {
          "nested": {
             "path": "tags",
             "query": {
                "bool": {
                   "must": [
                      {
                        "bool": {
                          "must":{
                             "term": { "tags.name": "name1" },
                             "term": { "tags.value": "value1" }
                          }
                        }
                      },
                      {
                        "bool": {
                          "must":{
                             "term": { "tags.name": "name2" },
                             "term": { "tags.value": "value2" }
                          }
                        }
                      }
                   ]
                }
             }
          }
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的问题在于,它会返回具有多个标记值的0个匹配项(对于单个值来说效果很好)。我相信这是因为查询要求标记必须具有多个名称和值才能匹配,这显然是不会发生的。有谁知道如何查询包含所有标签列表的元素?

编辑:这是使用elasticsearch 5.0

Joh*_*n K 5

我们知道了。答案是创建两个嵌套查询,而不是对同一嵌套查询有两个子句。

{
 "query":{
   "bool":{
     "must":[{
        "nested":{
           "path":"tags",
           "query":{
              "bool":{
                 "must":[
                    {"term":{"tags.name":"name1"}},
                    {"term":{"tags.value":"value1"}}
                 ]
              }
           }
        }
     },
     {
        "nested":{
           "path":"tags",
           "query":{
              "bool":{
                 "must":[
                    {"term":{"tags.name":"name2"}},
                    {"term":{"tags.value":"value2"}}
                 ]
              }
           }
        }
     }]
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

  • 遇到了这个问题,您的回答让我头疼不已,谢谢! (2认同)