ES-布尔查询

一个匹配文档的查询,该文档与其他查询的布尔组合相匹配。bool 查询映射到 Lucene BooleanQuery。它是用一个或多个布尔子句构建的,每个子句都有一个类型出现。出现类型有:

Occur Description
must 该子句 (查询) 必须出现在匹配的文件中,并将影响评分。
filter 该子句 (查询) 必须出现在匹配的文档中。然而,与 must 不同的是,查询的分数将被忽略。过滤器子句在过滤器上下文中执行,这意味着评分将被忽略,子句将被考虑用于缓存。
should 该子句 (查询) 应该出现在匹配的文档中。
must_not 子句 (查询) 不能出现在匹配的文档中。子句在过滤器上下文中执行,这意味着忽略评分,子句被考虑用于缓存。因为忽略评分,所以返回所有文档的评分为 0。

bool 查询采用 “匹配越多越好” 的方法,因此每个匹配 must 或 should 子句的分数将被加在一起,为每个文档提供最终的_score。

POST _search
{
  "query": {
    "bool" : {
      "must" : {
        "term" : { "user.id" : "kimchy" }
      },
      "filter": {
        "term" : { "tags" : "production" }
      },
      "must_not" : {
        "range" : {
          "age" : { "gte" : 10, "lte" : 20 }
        }
      },
      "should" : [
        { "term" : { "tags" : "env1" } },
        { "term" : { "tags" : "deployed" } }
      ],
      "minimum_should_match" : 1,
      "boost" : 1.0
    }
  }
}

使用 minimum_should_match#

可以使用 minimum_should_match 参数指定返回的文档必须匹配的 should 子句的数量或百分比。

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

For other valid values, see the minimum_should_match parameter.

Scoring with bool.filter#

在筛选器元素下指定的查询对评分没有影响 —— 得分返回为 0。分数只受指定的查询的影响。例如,以下三个查询都返回 status 字段包含术语 active 的所有文档。

第一个查询为所有文档分配 0 分,因为没有指定评分查询:

GET _search
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}

这个 bool 查询有一个 match_all 查询,它为所有文档赋值 1.0

GET _search
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}

constant_score 查询的行为与上面的第二个示例完全相同。constant_score 查询为筛选器匹配的所有文档赋值 1.0。

GET _search
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}

Name queries#

每个查询在其顶级定义中接受一个_name。您可以使用命名查询来跟踪哪些查询与返回的文档匹配。如果使用命名查询,则响应为每次命中都包含一个 matched_queries 属性。

本作品采用《CC 协议》,转载必须注明作者和本文链接