ElasticSearch组合多查询(must, should, must_not, bool, filter)
封面图
•
2025-10-25
•
Linux
178
0
0
0
在 Elasticsearch 中,`bool` 查询是一个非常强大的组合查询工具,它允许你使用多个子查询条件(如 `must`、`should`、`must_not` 和 `filter`)来构建复杂的查询逻辑。这些子句可以组合在一起,形成一个布尔逻辑表达式。 --- ## 🧩 1. 基本结构 ```json { "query": { "bool": { "must": [ ... ], "should": [ ... ], "must_not": [ ... ], "filter": [ ... ] } } } ``` --- ## 🔍 2. 各个子句的作用 | 子句 | 作用 | 是否影响相关性得分 | |------------|----------------------------------------------------------------------|------------------| | `must` | 必须匹配的条件,结果必须包含所有 `must` 条件 | ✅ 是 | | `should` | 可选匹配的条件,至少满足其中一个即可(默认 `minimum_should_match=1`) | ✅ 是 | | `must_not` | 必须不匹配的条件,相当于“排除” | ❌ 否 | | `filter` | 用于过滤文档,不计算相关性得分,性能更好 | ❌ 否 | --- ## 💡 3. 示例说明 ### 示例 1:`must` + `should` + `must_not` ```json { "query": { "bool": { "must": [ { "match": { "title": "ElasticSearch" } } ], "should": [ { "match": { "content": "search" } }, { "match": { "tags": "tutorial" } } ], "must_not": [ { "match": { "status": "draft" } } ] } } } ``` **含义:** - 文档标题必须包含 "ElasticSearch" - 内容包含 "search" 或 标签是 "tutorial" - 状态不能是 "draft" --- ### 示例 2:`filter` 用于高性能过滤 ```json { "query": { "bool": { "must": [ { "match": { "title": "ElasticSearch" } } ], "filter": [ { "term": { "category": "guide" } } ] } } } ``` **含义:** - 文档标题必须包含 "ElasticSearch" - 类别必须是 "guide"(不计算相关性得分) --- ### 示例 3:`should` + `minimum_should_match` ```json { "query": { "bool": { "should": [ { "match": { "title": "ElasticSearch" } }, { "match": { "content": "search" } }, { "match": { "tags": "tutorial" } } ], "minimum_should_match": 2 } } } ``` **含义:** - 至少满足 `should` 中的两个条件 --- ### 示例 4:`must_not` 排除某些文档 ```json { "query": { "bool": { "must_not": [ { "term": { "user": "spammer" } } ] } } } ``` **含义:** - 不包含用户为 "spammer" 的文档 --- ## 📌 4. 总结 | 子句 | 是否必须存在 | 是否影响得分 | 用途 | |------------|--------------|--------------|--------------------------| | `must` | 是 | ✅ 是 | 强制要求 | | `should` | 否 | ✅ 是 | 可选匹配 | | `must_not` | 否 | ❌ 否 | 排除不符合条件的文档 | | `filter` | 否 | ❌ 否 | 过滤,不计算相关性得分 | --- 如果你有具体的查询场景或想了解某个子句的更详细用法,欢迎继续提问!
上一篇:
CentOS查询端口占用和清除端口占用的程序
下一篇:
linux屏蔽主机的ping命令,使别人无法ping你的机器
标题录入,一次不能超过6条
返回顶部
留言
留言
评论