在ElasticSearch中查询要完全匹配的对象数组

tct7dpnv  于 2022-11-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(164)

考虑以下索引

PUT /orchards
{
  "mappings": {
    "properties": {
      "fruits": {
        "type": "nested",
        "properties": {
          "farms": {
            "type": "long"
          },
          "visits": {
            "type": "long"
          },
          "counts": {
            "type": "long"
          }
        }
      }
    }
  }
}

这些文件
第一次
现在,我想编写一个查询,只返回具有

"fruits" : [
    {
    "farms" : 1,
    "visits" : 1,
    "counts" : [1]
    }
  ]

我通过编写以下查询进行了尝试

GET /orchards/_search
{
  "query": {
    "nested": {
      "path": "fruits",
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "fruits.counts": [
                  1
                ]
              }
            },
            {
              "match": {
                "fruits.visits": 1
              }
            },
            {
              "match": {
                "fruits.farms": 1
              }
            }
          ]
        }
      }
    }
  }
}

但是,结果命中包含两个文档,即它不执行精确匹配
我希望避免使用脚本比较长度,因为这是一个开销很大的操作-如this post中所述
尝试了一些其他的变化,以及,但他们似乎都给予要么没有命中或两个文档的结果。
参考文献
Query on Nested Type
Query on Array Type

wnvonmuf

wnvonmuf1#

Tldr;

这是预期的行为。在嵌套文档中,您得到了一个匹配,因此返回整个文档。
如果您只对来自匹配的信息感兴趣,则可以使用类似inner_hits的内容

溶液

请注意_source: falseinner_hits:{}

GET /orchards/_search
{
  "_source": "false", 
  "query": {
    "nested": {
      "path": "fruits",
      "inner_hits": {},
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "fruits.counts": [
                  1
                ]
              }
            },
            {
              "match": {
                "fruits.visits": 1
              }
            },
            {
              "match": {
                "fruits.farms": 1
              }
            }
          ]
        }
      }
    }
  }
}

相关问题