弹性搜索查询以返回与数组中所有元素匹配的文档

时间:2019-11-19 03:13:01

标签: elasticsearch

我的结构与此类似:

文档1:

nestedobject: {
uniqueid: "12345",
field: [ {id: 1,
          color: blue,
         fruit:banana},
{id: 2,
          color: red,
fruit:apple},
]
}

文档2 :(在同一索引中)

nestedobject: {
uniqueid:23456,
field: [ {id: 3,
          color: blue, 
fruit:banana},
{id: 4,
          color: blue,
fruit:banana},
]
}

字段映射可以看成是:

{"mappings":
 "nestedobject":{
"properties":{
"uniqueid":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
"field":{
"type":"nested",
"id":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
},
"color":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
},
"fruit":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":256
}
}
}
}
}
}
}

现在,我尝试用2个文档查询该索引,而我只想要具有字段数组中所有元素的颜色为香蕉和蓝色的水果的文档-并非ATLEAST1。

现在,通过查询,我得到了与第一个文档的第一个元素匹配的两个文档,并返回了它们。

如何做到这一点?

{
    "query": {
        "nested" : {
            "path" : "nestedobject.field",
            "query" : {
                "bool" : {
                    "must" : [
                    { "match" : {"nestedobject.field.color" : "blue"} },
                    { "match" : {"nestedobject.field.fruit" : "banana"}}
                    ]
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

将查询更改为以下内容:

POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "field",
            "query": {
              "match":{
                "field.color": "blue"
              }
            }
          }
        },
        {
          "nested": {
            "path": "field",
            "query": {
              "match":{
                "field.fruit": "banana"
              }
            }
          }
        }
      ]
    }
  }
}

请注意,must子句中有两个Nested Queries

还请注意,为了利用完全匹配,您应该在Term Queries字段上使用keyword,如下所示:

POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "field",
            "query": {
              "term": {
                "field.color.keyword": "yellow"
              }
            }
          }
        },
        {
          "nested": {
            "path": "field",
            "query": {
              "term": {
                "field.fruit.keyword": "banana"
              }
            }
          }
        }
      ]
    }
  }
}

希望有帮助,如果您认为可以解决所需的内容,请随时 和/或 接受答案 ,只需点击此答案左侧的灰色大选中按钮即可。

相关问题