Elasticsearch---复合(bool)查询

3,605 阅读1分钟

本文对应的Elasticsearch版本为7.3

概念

bool 过滤器将多个小查询组合成一个大查询,查询语法有如下特点:

  1. 子查询可以任意顺序出现
  2. 可以嵌套多个查询,包括bool 查询也可以
  3. 如果bool查询中没有must条件,should中必须至少满足一条才会返回结果。

bool 过滤器包括四个操作符,mustmust_notshouldfilter,这四个都是数组,数组里面是对应的判断条件

  • must: 必须匹配。贡献算分
  • must_not:过滤子句,必须不能匹配,但不贡献算分
  • should: 选择性匹配,至少满足一条。贡献算分
  • filter: 过滤子句,必须匹配,但不贡献算分

官方例子

POST _search
{
  "query": {
    "bool" : {
      "must" : [
        "term" : { "user" : "kimchy" }
      ],
      "filter": [
        "term" : { "tag" : "tech" }
      ],
      "must_not" : [
        "range" : {
          "age" : { "gte" : 10, "lte" : 20 }
        }
      ],
      "should" : [
        { "term" : { "tag" : "wow" } },
        { "term" : { "tag" : "elasticsearch" } }
      ],
      "minimum_should_match" : 1,
      "boost" : 1.0
    }
  }
}

Bool嵌套查询

# 嵌套,实现了 should not 逻辑
POST /products/_search
{
  "query": {
    "bool": {
      "must": [
        "term": {
          "price": "30"
        }
      ],
      "should": [
        {
          "bool": {
            "must_not": [
              "term": {
                "avaliable": "false"
              }
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

SQL和dsl的对照

查询日期在16年10月份且文章标题或内容包含“ES“的文档,用SQL表示为

select * from article where date between  '2016-10-01' and  '2016-10-31' and (name like '%ES%' or contents like '%ES%')

bool过滤器组合filtershould,对应的SQL使用and来连接

{
  "query": {
    "bool":{
      "filter": [
        "range":{
          "date":{
            "gte":"2016-10-01",
            "lte":"2016-10-31"
          }
      ],
      "should": [
        {"match":{"name":"ES"}},
        {"match":{"contents":"ES"}}
      ]
    }
  } 
}