首页/数据/NoSQL 速查/bool 布尔组合查询
Elasticsearch89 条

bool 布尔组合查询

bool 用 must、should、must_not、filter 组合子查询:filter 不参与评分且可被缓存,适合状态、时间范围这类纯筛选条件。

NoSQL 速查数据更新于 2026-10-12
must必须匹配,参与评分
filter必须匹配,不评分,可缓存
should应匹配:无 must/filter 时至少命中一个,可用 minimum_should_match 调整
must_not必须不匹配,不评分

示例

示例
GET /my-index/_search
{
  "query": {
    "bool": {
      "must": [ { "match": { "title": "search" } } ],
      "filter": [
        { "term": { "status": "published" } },
        { "range": { "publish_date": { "gte": "2024-01-01" } } }
      ],
      "must_not": [ { "term": { "flag": "spam" } } ],
      "should": [ { "term": { "tags": "featured" } } ],
      "minimum_should_match": 0
    }
  }
}
bool 子句顺序不影响执行计划,但把过滤条件放 filter 能显著减少评分计算量。

易错点

  • should 在有 must 或 filter 时默认不强制,需显式写 minimum_should_match: 1
  • 单独使用 must_not 时会先匹配全部文档再排除,先加 filter 或 term 限定范围可避免无谓扫描

数据来源与参考

  • Elasticsearch Guide: Boolean query
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌