Elasticsearch
Elasticsearch 查询类型总结
查询类型对比
| 查询类型 | 是否分词 | 大小写敏感 | 适用场景 | 示例字段 |
|---|---|---|---|---|
| term | ❌ 否 | ✅ 是 | 精确值(如状态、ID) | status, id |
| match | ✅ 是 | ❌ 否* | 单个单词或分词文本 | title, log |
| match_phrase | ✅ 是 | ❌ 否* | 完整短语(如错误消息) | error_msg |
- match 和 match_phrase 的大小写敏感性由字段的分析器决定(如默认分析器会将文本转为小写)。
1. 为什么 term 查不到数据?
- 原因:目标字段是
text类型(会分词),无法精确匹配。 - 解决方法:改用字段的
.keyword子字段。
示例:
# 查看索引字段的映射,确认字段是 `text` 还是 `keyword`
curl -X GET "http://localhost:9200/your_index/_mapping"
2. match 和 match_phrase 的区别
- match:匹配分词后的任意单词。例如,搜索
quick fox可能匹配到the fox is quick。 - match_phrase:必须完整匹配短语且单词顺序一致。例如,搜索
quick fox不会匹配fox quick。
3. must_not 和 should 的区别
- must_not:排除符合条件的文档。例如,
"must_not": { "status": "failed" }。 - should:
- 满足任意条件即可加分(类似“或”逻辑)。
- 常与
minimum_should_match: 1配合,强制至少满足一个条件。
示例:
{
"query": {
"bool": {
"must": [
{ "term": { "status.keyword": "active" } },
{ "match_phrase": { "error": "NullPointerException" } }
],
"must_not": [
{ "term": { "priority": "low" } }
],
"should": [
{ "match": { "tags": "urgent" } },
{ "match": { "tags": "high" } }
],
"minimum_should_match": 1
}
}
}
4. Elasticsearch 聚合子结果排序
在 Elasticsearch 的聚合结果中,子聚合的输出顺序并不是按照查询中定义的顺序排列的,而是按照字母顺序(lexicographical order)自动排序的。这是 Elasticsearch 的默认行为。
浙公网安备 33010602011771号