MongoDB Search 或MongoDB Vector Search查询返回的每个文档都会根据相关性分配一个分数,并且结果设立包含的文档会按从最高分到最低分的顺序返回。
使用
要在搜索结果中包含每个文档的得分,请在聚合管道中使用$project阶段。
For the
$searchstage, thescorefield takes the$metaexpression, which requires thesearchScorevalue. You can also specify thesearchScoreDetailsvalue for thescoreDetailsfield$metaexpression for a detailed breakdown of the score.For the
$vectorSearchstage, thescorefield takes the$metaexpression, which requires thevectorSearchScorevalue to return the score of each document in your vector search results.
注意
您可以使用:
searchScore仅在$search查询中vectorSearchScore仅在$vectorSearch查询中
如果您在任何其他查询中使用 searchScore 和 vectorSearchScore,MongoDB 会从 MongoDB v8.2 开始记录警告日志。
例子
下面的查询使用 $project 阶段在返回的文档中添加名为 score 的字段:
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "text": { 5 <operator-specification> 6 } 7 } 8 }, 9 { 10 "$project": { 11 "<field-to-include>": 1, 12 "<field-to-exclude>": 0, 13 "score": { "$meta": "searchScore" } 14 } 15 } 16 ])
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "text": { 5 <operator-specification> 6 }, 7 "scoreDetails": true 8 } 9 }, 10 { 11 "$project": { 12 "<field-to-include>": 1, 13 "<field-to-exclude>": 0, 14 "scoreDetails": { "$meta": "searchScoreDetails" } 15 } 16 } 17 ])
要了解更多信息,请参阅返回搜索分数详情。
1 db.movies.aggregate([ 2 { 3 "$vectorSearch": { 4 <query-syntax> 5 } 6 }, 7 { 8 "$project": { 9 "<field-to-include>": 1, 10 "<field-to-exclude>": 0, 11 "score": { "$meta": "vectorSearchScore" } 12 } 13 } 14 ])
要学习更多信息,请参阅MongoDB 向量搜索评分。
行为
分配给返回文档的分数是文档元数据的一部分。您可以在聚合管道中使用 $project 阶段,将每个返回文档的得分与结果集一起包含在内。文档按从最高分到最低分的顺序返回。很多因素都会影响文档的分数,包括以下因素:
搜索词在文档中的位置。
搜索术语在文档中出现的频率。
MongoDB搜索查询使用的操作符或分析器的类型。
要学习;了解有关Lucene评分算法的更多信息,请参阅Lucene文档。
其他选项
除了默认的评分行为外, MongoDB Search 还支持以下选项:
修改分配给某些文档的分数。
通过使用 score details 选项返回分数的详细分解。
规范化搜索分数。
Considerations
如果结果中的多个文档具有相同的分数,则结果中文档的顺序是不确定的。如果希望MongoDB Search 结果有确定的顺序,请在 阶段包含 排序 $search选项,以按唯一字段对结果进行排序。您还可以使用排序选项按分数返回对结果进行升序排序。要学习;了解更多信息,请参阅对MongoDB搜索结果进行排序和按分数排序示例。
On separate Search Nodes, each node assigns documents different internal Lucene IDs used for sorting when scores are identical. When sorting and paginating results, the mongot process on the node that is processing the query might include documents from other nodes if their internal IDs have greater pagination order than the token. To prevent this, use $match after $search to exclude documents by their _id.
查询大量值时,如果大量中的更多值与查询匹配, MongoDB Search 会分配更高的分数。