这是 Elasticsearch 最容易被混淆的地方。
很多初学者会把下面两件事混成一件事:
- 搜“无线降噪耳机”
- 过滤“分类=audio、库存=true、价格<2000”
但这两类条件本质完全不同。
全文检索关心的是:
这份文档和用户线索有多像?精确过滤关心的是:
这份文档是否满足硬条件?把它画出来就很清楚:
全文检索
用户线索
│
▼
analyzer 拆词
│
▼
倒排索引找候选
│
▼
算相关性分数
│
▼
按 _score 排序
精确过滤
结构化条件
│
▼
term / range / exists / bool filter
│
▼
是 / 否
│
▼
保留或剔除对应的查询写法通常是这样:
全文检索:
GET /city_products/_search
{
"query": {
"match": {
"title": "noise cancelling headphones"
}
}
}精确过滤:
GET /city_products/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "brand": "AcmeAudio" } },
{ "range": { "price": { "lte": 1500 } } }
]
}
}
}真正的业务搜索通常是两者结合:
GET /city_products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "title": "headphones" } }
],
"filter": [
{ "term": { "in_stock": true } }
]
}
}
}记一句很关键的话:
must 更像“相关性召回”,filter 更像“硬门禁筛选”。