搜索基础与请求体查询
从这篇开始进入查询 DSL。ES 有两种搜索形式:URL 查询字符串和请求体(request body)查询。前者是遗留用法,后者是主力。这篇把两种形式、分页、以及 ES 查询模型里最重要的分野——**查询(query context)与过滤(filter context)**讲清楚。
一、两种搜索形式
1.1 查询字符串(query string)
# 全部文档
curl "localhost:9200/products/_search?q=*"
# 带条件
curl "localhost:9200/products/_search?q=name:键盘"
# 多条件
curl "localhost:9200/products/_search?q=name:键盘+price:>=300"URL 形式的问题:复杂查询没法表达(没有 bool 嵌套、没有聚合)、特殊字符要转义、可读性为零。只适合调试时快速验证,生产代码一律用请求体。
1.2 请求体查询(request body search)
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
"query": {
"bool": {
"must": [ { "match": { "name": "机械键盘" } } ],
"filter": [ { "range": { "price": { "gte": 300, "lte": 500 } } } ]
}
}
}'请求体查询的能力是 URL 形式的超集:布尔组合、嵌套子句、过滤、排序、分页、聚合、高亮、source 过滤,全在这一个 JSON 里。 Kibana Dev Tools 的自动补全也是针对请求体查询的。
二、空搜索
不带 query 的搜索等价于 match_all:
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '{}'
# 等价于
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{ "query": { "match_all": {} } }'返回结构:
{
"took": 3,
"timed_out": false,
"_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 },
"hits": {
"total": { "value": 100, "relation": "eq" },
"max_score": null,
"hits": [ { "_index": "products", "_id": "1", "_score": 1.0, "_source": { ... } } ]
}
}took:查询耗时(毫秒),注意这是 ES 内部计时,不含网络传输;hits.total.value:命中总数,7.x 之后默认只精确统计到 10000,超过显示"relation": "gte";_score:相关性得分。match_all不过滤不打分,所有文档_score相同(1.0)。
hits.total.relation: "gte" 是个隐蔽的坑:分页翻页时如果总数显示 gte 10000,说明实际更多,ES 没有精确统计。要精确计数用 _count API 或设置 track_total_hits: true(有性能代价)。
三、多索引与多类型
一条搜索可以打多个索引:
# 搜两个索引
curl -X POST "localhost:9200/products,orders/_search" -H 'Content-Type: application/json' -d '{ "query": { "match_all": {} } }'
# 通配符
curl -X POST "localhost:9200/logs-*/_search" -H 'Content-Type: application/json' -d '{ "query": { "match_all": {} } }'
# _all(已废弃但 8.x 仍兼容,别用)
curl -X POST "localhost:9200/_search" -H 'Content-Type: application/json' -d '{ "query": { "match_all": {} } }'类型(type)的历史遗留要说清楚:6.x 起一个索引只允许一个 type(_doc),7.x 彻底移除 type 概念,8.x 的 API 里已经没有 type 参数。从 6.x 迁移的老代码如果还在 URL 里带 /index/type/_search,需要删掉。
多索引搜索的坑:不同索引的字段名冲突。products 和 orders 都有 name 字段但类型不同(一个 text 一个 keyword),跨索引 match 查询会直接 400——映射冲突。跨索引搜索前用 _resolve/index API 检查字段兼容性。
四、分页:from/size
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
"from": 20,
"size": 10,
"query": { "match_all": {} }
}'from 默认 0,size 默认 10。分页上限:
| 版本 | 限制 |
|---|---|
| 所有版本 | from + size 不能超过 index.max_result_window,默认 10000 |
超过报 Result window is too large。改上限是下策(每个分片都要缓存 from + size 个结果,内存爆炸),深分页用 search_after 或 PIT + search_after,见《分布式搜索与深分页》。
分页的性能特征:from 越大越慢。ES 要在每个分片上取 from + size 条,协调节点再归并排序后丢弃前 from 条。from=9900, size=10 时每个分片取 9910 条,纯浪费。产品上前十页用 from/size,再往深的场景 redesign(搜索词引导、时间过滤、滚动加载)。
五、查询字符串语法速查
如果维护的旧代码在用 q= 参数,这些语法要知道:
name:键盘 字段查询
name:键盘 AND price:>300 布尔组合(大写)
name:(键盘 OR 鼠标) 分组
name:"机械键盘" 短语
name:键* 通配(性能差,慎用)
name:键*盘 前后通配(最差,避免)
date:[2024-01-01 TO 2024-12-31] 范围
_exists_:field 字段存在坑一堆:
- 保留字符
+ - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ /都要转义; - 默认分词器是查询字段的分析器,中文场景下
q=name:机械键盘会被切成单字 OR 查询,结果和直觉不符; - 简单场景用
simple_query_string替代query_string,它用更安全的语法且不报错(无法解析的部分被忽略)。
六、查询与过滤的本质区别
这是 ES 查询模型的核心,搞不懂这个永远写不出高性能查询。
6.1 Query Context(查询上下文)
{ "query": { "match": { "name": "键盘" } } }回答的问题是:「这个文档和查询有多相关?」——计算 _score。所有 match、multi_match、query_string 这些全文查询都在 query context。计算 BM25 打分要读词频、文档长度、字段统计,开销比过滤大。
6.2 Filter Context(过滤上下文)
{ "query": { "bool": { "filter": [ { "term": { "on_sale": true } } ] } } }回答的问题是:「这个文档符合条件吗?是或否。」——不打分,只做布尔判断。所有 term、terms、range、exists、geo_* 这些结构化查询都可以放 filter。
过滤的三个优势:
- 不打分,省 CPU;
- 结果可缓存:ES 自动把 filter 结果缓存成 bitset(64 位一组的位图),后续相同 filter 直接位运算,纳秒级。bitset 缓存对高频过滤条件(品牌、类目、状态)收益巨大;
- 可组合加速:ES 会按「过滤成本从低到高」自动调整 filter 执行顺序,先执行便宜的 bitset 缓存项。
判断标准一句话:要不要按相关性排序?要 → query context;只是筛数据 → filter context。商品列表页的「品牌 + 价格区间 + 有货」全部走 filter,排序用 sort 字段(如销量、价格),_score 根本不看。
6.3 bool 查询的四种子句
{
"query": {
"bool": {
"must": [],
"should": [],
"must_not": [],
"filter": []
}
}
}| 子句 | 语义 | 打分 | 缓存 |
|---|---|---|---|
| must | 必须匹配(AND) | 参与 _score | 否 |
| filter | 必须匹配(AND) | 不贡献 _score | 是 |
| should | 至少匹配 should 数量(OR) | 贡献 _score | 否 |
| must_not | 必须不匹配(NOT) | 不贡献 _score | 是 |
行为细节:
bool里只有should时,默认至少匹配 1 条,可用minimum_should_match控制;must_not子句在 filter context,自动缓存;must里混结构化查询是常见浪费:{"must": [{"term": {"brand": "logitech"}}]}改成filter子句,白拿缓存。
七、重要的查询子句速览
按场景选查询类型,这张表日常够用:
| 需求 | 查询 |
|---|---|
| 精确匹配 keyword | term / terms |
| 数值/日期范围 | range |
| 字段存在性 | exists |
| 全文搜索(已分词) | match |
| 短语(词序+相邻) | match_phrase |
| 多字段搜索 | multi_match |
| 前缀匹配 | prefix(宁可用 completion suggester) |
| 通配符 | wildcard(性能差) |
| 模糊匹配 | fuzzy |
| 组合条件 | bool |
| 全部文档 | match_all |
| 打分可控 | function_score / boosting |
每个查询的详细语法和坑在《查询子句详解》和《多字段搜索》展开,这里先建立「什么场景用什么」的地图。
八、验证查询:_validate 与 profile
查询语法错误不想跑全量?用 _validate API:
curl -X GET "localhost:9200/products/_validate/query?explain" -H 'Content-Type: application/json' -d '
{ "query": { "match": { "name": "键盘" } } }'返回 valid: true/false,加 explain 会返回 ES 对查询的解析结果(比如分词结果、改写的 Lucene 查询)。调试 DSL 时的第一道关卡,比看 400 报错直观。
想知道慢在哪,用 profile:
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
"profile": true,
"query": { "bool": { "must": [ { "match": { "name": "键盘" } } ] } }
}'返回每个分片、每个查询子句的耗时分解(rewrite time、score time 等)。优化查询前先 profile,别凭感觉改。生产排查慢查询的标配动作。
九、常见坑汇总
- URL 查询中文乱码/分词不符预期:URL 形式会用字段的分析器分词,
q=name:机械键盘实际按单字 OR 匹配。改用请求体 +match。 from + size超 10000 报错:index.max_result_window默认 10000。深分页用search_after,别去改上限。match查询 keyword 字段:keyword 不分词,match: { "brand": "罗技键盘" }会按整串精确匹配,通常 0 结果。要么改 term,要么字段映射换成 text。- must 里放了纯过滤条件:白白损失 bitset 缓存。品牌、状态、开关类条件全部移到 filter。
hits.total显示 gte 10000 就以为数据齐了:需要精确总数时track_total_hits: true。- 多索引搜索 400 mapping conflict:跨索引同名字段类型不一致。要么统一 mapping,要么拆开查询。
_validate说 valid 但结果不对:语法合法 ≠ 语义正确。配合explain看分词和改写结果,再看 mapping。
下一篇《查询子句详解》逐个拆解结构化查询和全文查询的子句语法。
