es boolquery 的几种用法

Bool query 包含那些?

Bool query 对应lucene 的BooleanQuery,一般由一个或者多个查询子句组成,如下表格所示:

用法描述

must

查询一定包含匹配查询内容,并且提供得分

filter

查询一定包含匹配查询内容,但是不提供得分,会对查询结果进行缓存

should

子查询不一定包含查询内容

must_not

查询一定不包含查询内容,来自于filter 上下文,所以不会由评分,但是会缓存

 

 

bool 查询秉持匹配越多越接近的原则,每个子查询(must or should)评分会被加在一起作为最终评分。

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参数指定返回的文档必须匹配的子句的数量或百分比。

如果bool 查询包含至少一个should 子查询并且没有must 或者filter 查询,则默认数值是1.否则默认为0.

使用bool.filter评分

filter 对评分无影响返回值为0,评分只受到特殊查询影响,比如,如下三种情况的得分

 

使用filter,返回的文档得分都为0:
GET _search {
"query": { "bool": { "filter": { "term": { "status": "active" } } } } } 使用match_all查询,所有文档评分都为1.0 GET _search { "query": { "bool": { "must": { "match_all": {} }, "filter": { "term": { "status": "active" } } } } } constant_score 查询与match_all 完全一致,使用filter 返回所有文档都分配一个1.0 的评分 GET _search { "query": { "constant_score": { "filter": { "term": { "status": "active" } } } } }

 


 

Named queries

每个查询在顶部的定义里面都要接收一个_name  。可以使用这种查询追踪匹配返回的文档。比如,返回命中文档必须包含一个match 查询的属性:

GET /_search
{
  "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"
        }
      }
    }
  }
}
posted @ 2022-02-17 13:27  DB乐之者  阅读(1323)  评论(0编辑  收藏  举报