constant_score 与 boosting 是什么
constant_score 把一个过滤条件包成固定分值的查询:子查询不参与打分,命中文档统一得到 boost 指定的分值,省掉无意义的评分计算。boosting 查询由 positive 与 negative 两部分组成:命中 positive 的部分正常计分,同时命中 negative 的会被乘以 negative_boost 降权,结果仍保留在返回集里,只是排名靠后。想让某类文档彻底不出现,应该用 must_not 或 filter,而不是降权。
基本信息
| constant_score 结构 | { constant_score: { filter: {...}, boost: 1.2 } } |
|---|---|
| boosting 结构 | { boosting: { positive, negative, negative_boost } } |
| negative_boost | 取值通常在 0 到 1 之间,越小降得越狠 |
| 打分影响 | constant_score 内不计算评分 |
| 适用 | 排序需要固定权重,或想让某类文档沉底但不排除 |
典型使用场景
- 固定权重排序:某些过滤条件本身不该影响相关性,包成 constant_score
- 降权不排除:归档或测试数据排到后面但保留在结果里
- 省掉评分开销:纯过滤场景避免逐文档计算评分
- 多来源合并:把不同来源的候选结果按固定权重混合排序
- 调试排序:用统一分值观察脚本排序等其它因素的影响
两种查询写法
两种查询写法
GET /my-index/_search
{
"query": {
"constant_score": {
"filter": { "term": { "user.id": "kimchy" } },
"boost": 1.2
}
}
}
# 让归档数据降权但不排除
GET /my-index/_search
{
"query": {
"boosting": {
"positive": { "match": { "title": "elastic" } },
"negative": { "term": { "tier": "archived" } },
"negative_boost": 0.2
}
}
}参数读法
| 参数 | 含义 | 注意 |
|---|---|---|
| constant_score.filter | 判定条件 | 不参与评分计算 |
| constant_score.boost | 统一分值 | 只影响排序不影响命中集合 |
| boosting.positive | 加分条件 | 通常写相关性查询 |
| boosting.negative | 降权条件 | 命中后按降幅压低 |
| negative_boost | 降幅 | 写 0 会让这类文档分值归零 |
纯过滤场景优先用 bool 的 filter,它不评分而且匹配结果可以被缓存;constant_score 更适合需要固定 boost 参与排序的场合。
boosting 只是降权不淘汰,被降权的文档依旧占返回条数。真正要排除的条件应当放进 must_not 或 filter。
constant_score 里的 boost 是固定分值,不会与其它子句的相关性得分线性叠加;多个子句组合时先看 explain 的最终分值再决定调参方向。
需要按数值字段加权、脚本打分或做随机扰动时,function_score 比 boosting 更直接,boosting 只解决「命中某条件就整体降权」这一类需求。