如何基于自定义加权条件对Elasticsearch语义搜索结果重打分?
修改ELSER语义搜索查询以支持自定义重打分排序
我正在使用Elasticsearch的ELSER推理模型进行语义搜索,需要按照以下规则对搜索结果进行重打分排序:
- spotlight标记为true的文档置于首位
- 其次是verified标记为true的文档
- 最后按votes字段降序排序
原语义搜索查询
GET business-index/_search?filter_path=hits.hits._source.title,hits.hits._source.subtitle,hits.hits._source.categorySearch,hits.hits._source.spotlight,hits.hits._source.verified,hits.hits._source.votes,hits.hits._source.createdAt { "query": { "semantic": { "query": "broken pipes", "field": "elser" } } }
修改后的查询(带重打分逻辑)
GET business-index/_search?filter_path=hits.hits._source.title,hits.hits._source.subtitle,hits.hits._source.categorySearch,hits.hits._source.spotlight,hits.hits._source.verified,hits.hits._source.votes,hits.hits._source.createdAt { "query": { "function_score": { // 保留原有的ELSER语义查询作为基础查询 "query": { "semantic": { "query": "broken pipes", "field": "elser" } }, // 定义重打分函数,按优先级设置权重 "functions": [ { // spotlight文档加最高权重 "filter": { "term": { "spotlight": true } }, "weight": 20 }, { // verified文档加次高权重 "filter": { "term": { "verified": true } }, "weight": 10 }, { // 基于votes字段做对数加权,避免高votes文档完全盖过语义相关性 "field_value_factor": { "field": "votes", "factor": 1, "modifier": "log1p", "missing": 0 }, "weight": 5 } ], // 权重与基础语义得分相加,保证语义相关性依然起作用 "boost_mode": "sum", "score_mode": "sum" } }, // 最终排序:先按综合得分降序,得分相同则按votes降序 "sort": [ { "_score": "desc" }, { "votes": { "order": "desc" } } ] }
关键逻辑说明
- 基础查询保留:将原有的
semantic查询嵌套在function_score的query字段中,确保语义相关性是排序的基础。 - 优先级权重设置:
spotlight: true的文档额外加20权重,确保这类文档排在最前面verified: true的文档额外加10权重,优先级仅次于spotlight文档
- votes字段处理:使用
log1p修饰符避免高votes值的文档完全压制语义得分,同时给votes设置较低的权重(这里设为5),保证语义相关性为主、votes为辅的排序逻辑。 - 排序规则:先按综合得分(语义得分+权重)降序,得分相同时再按votes降序,完全符合需求中的排序优先级。
内容的提问来源于stack exchange,提问作者R4nc1d
相关产品推荐
相关产品推荐

