排序与自定义评分
本章定位:搜索结果按相关度排序是默认行为,但产品经理可能要求"按价格排序"或"综合销量+评分排序"。本章覆盖排序规则和 function_score 自定义评分。
定义与作用
排序(Sort):按指定字段升序或降序排列。function_score:在原始 _score 基础上叠加多个函数(weight、field_value_factor、random、decay 等),实现"相关性 + 业务规则"的综合排序。
完整示例:杨英的综合排序需求
按报名人数排序
POST /courses/_search
{
"sort": [{ "enrollment_count": "desc" }]
}
function_score 综合排序
POST /courses/_search
{
"query": {
"function_score": {
"query": { "multi_match": { "query": "Python", "fields": ["title^3","description"] } },
"functions": [
{ "field_value_factor": { "field": "enrollment_count", "factor": 0.1, "modifier": "log1p", "missing": 0 }, "weight": 1.5 },
{ "field_value_factor": { "field": "rating", "factor": 1, "modifier": "none", "missing": 1 }, "weight": 2 }
],
"score_mode": "sum",
"boost_mode": "multiply"
}
}
}
小结
基础排序用 sort 参数,业务综合排序用 function_score。score_mode 决定多函数如何结合(sum/avg/max),boost_mode 决定函数得分与原 _score 如何结合(multiply/sum)。