Elasticsearch复合查询

问题描述

我正在使用如下所示的复合查询查询具有300条记录的弹性索引:

GET my_index/_search
{
  "size": 10,"query": {
    "bool": {
      "should": [
        {
          "bool": {
            "should": [
              {
                "multi_match": {
                  "query": "card","fields": [
                    "title^1.0"
                  ]
                }
              }
            ],"must": {
              "term": {
                  "_index": {
                    "value": "my_index"
                  }
                }
            }
          }
        }
      ]
    }
  }
}

必须启用索引是因为根据某些业务逻辑这可能是一个多索引查询(最有可能应该是一个过滤器,我可以更改它,但这不是我的问题。我得到的结果相同以及过滤器)。

虽然我希望它返回与should子句匹配的文档,但我要检索索引(300)中的所有文档

为什么会这样?

解决方法

此问题的解决方案是向查询中添加minimumShouldMatch字段。结果查询变为:

GET my_index/_search
{
  "size": 10,"query": {
    "bool": {
      "should": [
        {
          "bool": {
            "minimum_should_match": 1,"should": [
              {
                "multi_match": {
                  "query": "card","fields": [
                    "title^1.0"
                  ]
                }
              }
            ],"must": {
              "term": {
                  "_index": {
                    "value": "my_index"
                  }
                }
            }
          }
        }
      ]
    }
  }
}

我相信其背后的原因是调整布尔查询以提供最大数量的匹配结果(more-matches-is-更好)。因此,如果must / filter子句匹配,则甚至不会执行。通过添加“ minimum_should_match”:1,我们指示elasticsearch在返回文档之前至少匹配1个应该子句。

弹性文档摘录:

bool查询采用的是“更匹配是更好”的方法,因此每个匹配的must或应当子句的得分将加在一起,以提供每个文档的最终_score。

您可以使用minimum_should_match 参数,用于指定应子句的数量或百分比 返回的文件必须匹配。

如果布尔查询至少包含一个should子句,并且没有must或 filter子句,默认值为1。否则,默认值为 是0。

有关其他有效值,请参见minimum_should_match参数。

参考链接-https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html#bool-min-should-match

,

添加带有索引数据和搜索查询的有效示例

索引数据:

{
    "title":"card","cost":"55"
}
{
    "title":"Card making","cost":"55"
}
{
    "title":"elasticsearch","cost":"55"
}

搜索查询:

GET /_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "_index": {
                    "value": "index-name"
                  }
                }
              }
            ],"must": [
              {
                "multi_match": {
                  "fields": [
                    "title^1.0"
                  ],"query": "card"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "my_index","_type": "_doc","_id": "1","_score": 0.7549127,"_source": {
          "title": "card","cost": "55"
        }
      },{
        "_index": "my_index","_id": "2","_score": 0.55654144,"_source": {
          "title": "Card making","cost": "55"
        }
      }
    ]