Elasticsearch——Boolean query

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

must

子句(query)必须出现在匹配的文档中,并将对分数起作用。

filter子句(query)必须出现在匹配的文档中。但是,查询的分数将被忽略。filter子句在fiter上下文中执行,这意味着忽略评分,并考虑缓存子句。
should

子句(query)应出现在匹配文档中。

must_not

子句(query)不得出现在匹配的文档中。子句在filter上下文中执行,这意味着评分被忽略,子句被考虑用于缓存。因为评分被忽略,所以返回所有文档的0分。

bool query采用了“匹配越多越好”的方法,因此来自每个匹配的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
    }
  }
}

Using minimum_should_match

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

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

Scoring with bool.filter

在filter元素下指定的查询对评分没有影响 — 分数返回为0。分数仅受已指定查询的影响。例如,以下三个查询都返回status字段包含term “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查询为filter匹配的所有文档分配1.0的分数。

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

Named queries

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

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"
        }
      }
    }
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值