Elasticsearch 的`bool`查询是构建复杂查询条件的核心工具之一。它允许通过布尔逻辑组合多个查询子句,以实现精确的搜索需求。`bool`查询支持四种主要的子句类型:`must`、`should`、`filter`和`must_not`。每种子句类型都有其特定的作用和行为。
1.`bool`查询的基本结构
`bool`查询的基本结构如下:
```json
{
"query": {
"bool": {
"must": [/* 必须匹配的查询 */],
"should": [/* 应该匹配的查询 */],
"filter": [/* 过滤条件 */],
"must_not": [/* 必须不匹配的查询 */]
}
}
}
```
2.子句类型详解
2.1`must`子句
• 作用:`must`子句中的查询必须匹配。它相当于逻辑“与”(AND)操作。
• 评分:`must`子句中的查询会对文档的评分(`_score`)有贡献。
• 示例:
```json
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } },
{ "match": { "content": "search engine" } }
]
}
}
}
```
• 解释:返回`title`包含"Elasticsearch"并且`content`包含"search engine"的文档。
2.2`should`子句
• 作用:`should`子句中的查询应该匹配,但不是必须的。它相当于逻辑“或”(OR)操作。
• 评分:`should`子句中的查询会对文档的评分有贡献,但只有当`minimum_should_match`参数满足时,文档才会被返回。
• `minimum_should_match`参数:
• 用于指定必须匹配的`should`子句的最小数量。
• 如果没有指定,默认值为`0`,除非没有`must`或`filter`子句,此时默认值为`1`。
• 示例:
```json
{
"query": {
"bool": {
"should": [
{ "match": { "tags": "Elasticsearch" } },
{ "match": { "tags": "Kibana" } }
],
"minimum_should_match": 1
}
}
}
```
• 解释:返回`tags`包含"Elasticsearch"或者"Kibana"的文档。
2.3`filter`子句
• 作用:`filter`子句中的查询必须匹配,但不会对文档的评分有贡献。它主要用于过滤数据,而不影响评分。
• 评分:`filter`子句中的查询不会对文档的评分产生影响,所有匹配的文档的评分默认为`0`。
• 缓存:`filter`子句通常会被缓存,从而提高查询效率。
• 示例:
```json
{
"query": {
"bool": {
"filter": [
{ "term": { "status": "active" } }
]
}
}
}
```
• 解释:返回`status`字段值为"active"的文档,但不对评分产生影响。
2.4`must_not`子句
• 作用:`must_not`子句中的查询必须不匹配。它相当于逻辑“非”(NOT)操作。
• 评分:`must_not`子句中的查询不会对文档的评分有贡献,所有匹配的文档的评分默认为`0`。
• 示例:
```json
{
"query": {
"bool": {
"must_not": [
{ "range": { "age": { "gte": 10, "lte": 20 } } }
]
}
}
}
```
• 解释:返回`age`字段值不在 10 到 20 之间的文档。
3.综合示例
以下是一个综合使用`must`、`should`、`filter`和`must_not`的查询示例:
```json
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } }
],
"should": [
{ "match": { "tags": "Kibana" } },
{ "match": { "tags": "Logstash" } }
],
"minimum_should_match": 1,
"filter": [
{ "term": { "status": "active" } }
],
"must_not": [
{ "range": { "age": { "gte": 10, "lte": 20 } } }
]
}
}
}
```
• 解释:
• 必须匹配`title`包含"Elasticsearch"。
• 至少匹配一个`tags`包含"Kibana"或"Logstash"。
• 必须匹配`status`为"active",但不考虑评分。
• 必须不匹配`age`在 10 到 20 之间。
4.评分机制
• 评分计算:
• `must`和`should`子句中的查询会对文档的评分有贡献。
• `filter`和`must_not`子句中的查询不会对评分产生影响。
• Elasticsearch 会根据匹配的`must`和`should`子句计算文档的最终评分。
• 评分优化:
• 如果你不需要评分,可以使用`constant_score`查询包装`filter`子句,以进一步优化性能。
```json
{
"query": {
"constant_score": {
"filter": {
"term": { "status": "active" }
}
}
}
}
```
5.性能优化
• 缓存:
• `filter`和`must_not`子句通常会被缓存,从而提高查询效率。
• 如果查询中包含大量`filter`子句,可以考虑使用`filter`缓存来优化性能。
• 减少子句数量:
• 尽量减少`must`和`should`子句的数量,以提高查询性能。
• 如果不需要评分,尽量使用`filter`子句。
6.总结
`bool`查询是 Elasticsearch 中非常强大的工具,通过组合`must`、`should`、`filter`和`must_not`子句,可以实现复杂的查询逻辑。合理使用这些子句可以提高查询的灵活性和性能。