首页 > 解决方案 > 这个 Elasticsearch OR Query 有什么不正确的地方?

问题描述

我正在尝试在一个查询中对两个子句进行 OR 运算,但我看到一些奇怪的行为并正在寻找指导

给定一个包含两个文档的索引“index1” -

{"column1": "A"} with _id=1
{"column1": "B"} with _id=2

当使用以下正文运行 POST index1/_search -

{"query": {
    "bool": {
        "minimum_should_match": 1,
        "should": [
            {
                "bool": {
                    "must": [
                        {"term": {"_id": "1"}},
                        {"term": {"column1": "A"}}
                    ]
                }
            },
            {
                "bool": {
                    "must": [
                        {"term": {"_id": "2"}},
                        {"term": {"column1": "B"}}
                    ]
                }
            }
        ]
    }
}}

我没有得到任何结果。我所期待的是两份文件都会被退回。如果我删除其中一个 column1 术语匹配项,我将获得另一个文档。如果我删除两个 column1 术语匹配,我得到两个文档?

我究竟做错了什么?

标签: elasticsearch

解决方案


column1.keword正如@Val 已经建议的那样,如果您采用默认映射,您应该使用column1

搜索查询:

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_id": "1"
                }
              },
              {
                "term": {
                  "column1.keyword": "A"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_id": "2"
                }
              },
              {
                "term": {
                  "column1.keyword": "B"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "fd_cb",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.6931472,
        "_source": {
          "column1": "A"
        }
      },
      {
        "_index": "fd_cb",
        "_type": "_doc",
        "_id": "2",
        "_score": 1.6931472,
        "_source": {
          "column1": "B"
        }
      }
    ]

如果您已经为 定义了显式映射column1,如下所示:

{
  "mappings": {
    "properties": {
      "column1": {
        "type": "keyword"
      }
    }
  }
}

然后,您的问题中提到的搜索查询可以正常工作。


推荐阅读