es bool解释

概念

Boolean query 可以基于多个条件的组合对文档进行查询。使用的是Lucene BooleanQuery的映射。它是基于一个或多个布尔子句构建的,每个子句对应一个类型。类型有以下几种:

关键词描述
must查询的结果必须匹配查询条件,并且计算score。
filter查询的结果必须匹配查询条件,和must不太一样的是,不会计算score
should查询结果必须符合查询条件should中的一个或者多个,minimum_should_match参数定义了至少满足几个子句。会计算score。
must查询的结果必须不符合查询条件。

注意

bool查询采用的策略是“越多的匹配越好”,所以每个命中的must和should语句都会计算score,最终会为每个文档计算一个总分。

如下官方文档示意:

需要数据的user.id为kimchy
tags包含production
并且age要小于10且大于20
tags至少要包含env1或者deployed

curl -X POST "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "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查询中,使用了至少一个1个should语句,并且没有用过must和filter语句,默认的值是1,否则默认值是0。

bool.filter的得分

在filter中的命中的元素对score没有影响-score会return 0.分数仅受特别指定的查询的影响。举例,下面三个会返回所有status包含分词active的文档。

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

虽然有match_all,但是为每个文档都分配了1.0的score。

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": {
        "match_all": {}
      },
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}
'

constant_score和上面的那个例子一样,constant_score为命中filter的每个文档都分配了1.0的score。

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "status": "active"
        }
      }
    }
  }
}
'

name声明

每个查询支持一个_name在最顶层的定义。可以使用命名查询来跟踪哪些查询与返回的文档匹配。如果使用命名查询,则响应会为每个命中的文档包含一个matched_queries 属性。

curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "should": [
        { "match": { "name.first": { "query": "shay", "_name": "first" } } },
        { "match": { "name.last": { "query": "banon", "_name": "last" } } }
      ],
      "filter": {
        "terms": {
          "name.last": [ "banon", "kimchy" ],
          "_name": "test"
        }
      }
    }
  }
}
'

官方原文

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值