Elasticsearch中能否自定义父文档与嵌套文档的_score?
Elasticsearch父文档与嵌套文档自定义_score实现方案
这个需求完全可行,Elasticsearch的function_score查询结合nested类型特性,能精准控制父文档和嵌套文档的评分,完全匹配你的场景要求。
1. 准备测试数据结构
首先确保嵌套字段用nested类型定义mapping:
PUT /cars_index { "mappings": { "properties": { "title": {"type": "text"}, "colors": { "type": "nested", "properties": { "color": {"type": "text"} } } } } }
插入测试文档:
POST /cars_index/_doc { "title": "car", "colors": [{"color": "red"}, {"color": "blue"}] }
2. 场景一:搜索"red car"的评分控制
通过function_score为父文档固定评分0.5,同时对嵌套文档设置差异化评分:
GET /cars_index/_search { "query": { "function_score": { "query": {"match": {"title": "car"}}, "functions": [{"filter": {"match": {"title": "car"}}, "weight": 0.5}], "score_mode": "sum", "nested": { "path": "colors", "query": { "function_score": { "functions": [ {"filter": {"match": {"colors.color": "red"}}, "weight": 1}, {"filter": {"match": {"colors.color": "blue"}}, "weight": 0} ], "score_mode": "sum" } }, "inner_hits": {} } } } }
查询结果:
- 父文档
_score为0.5 - 嵌套文档"red"的
_score为1,"blue"的_score为0
3. 场景二:搜索"black car"的评分控制
调整嵌套文档的评分规则,统一设为0或0.5:
GET /cars_index/_search { "query": { "function_score": { "query": {"match": {"title": "car"}}, "functions": [{"filter": {"match": {"title": "car"}}, "weight": 0.5}], "score_mode": "sum", "nested": { "path": "colors", "query": { "function_score": { "functions": [ {"filter": {"match_all": {}}, "weight": 0} ], "score_mode": "sum" } }, "inner_hits": {} } } } }
查询结果:
- 父文档
_score为0.5 - 所有嵌套文档
_score为0(若需要0.5,修改weight值即可)
4. 评分结果的业务使用
查询返回结果中:
- 父文档评分在顶层
_score字段 - 每个嵌套文档的评分在
inner_hits.colors.hits.hits数组对应元素的_score字段
你可直接读取这些评分值,判断返回父文档页面链接,还是对应嵌套文档的链接(比如评分1返回red的链接,0返回blue的链接,父文档0.5返回car的链接)。
内容的提问来源于stack exchange,提问作者Виталий Монашенков
相关产品推荐
相关产品推荐

