从另一个集合中的数据提高搜索分数
我使用地图集搜索返回文档列表(使用猫鼬):
const searchResults = await Resource.aggregate()
.search({
text: {
query: searchQuery,
path: ["title", "tags", "link", "creatorName"],
},
}
)
.match({ approved: true })
.addFields({
score: { $meta: "searchScore" }
})
.exec();
这些资源可以由用户向上和倾斜(例如Stackoverflow上的问题)。我想根据这些投票提高搜索分数。
我可以使用 boost> boost 操作员。
问题:投票不是资源
文档的属性。取而代之的是,它们存储在一个单独的集合中:
const resourceVoteSchema = mongoose.Schema({
_id: { type: String },
userId: { type: mongoose.Types.ObjectId, required: true },
resourceId: { type: mongoose.Types.ObjectId, required: true },
upDown: { type: String, required: true },
在上面获得搜索结果后,我会分别获取投票并将其添加到每个搜索结果中:
for (const resource of searchResults) {
const resourceVotes = await ResourceVote.find({ resourceId: resource._id }).exec();
resource.votes = resourceVotes
}
我然后从客户端上的upvotes中减去下降票在UI中显示最终数字。
如何将此投票点价值纳入搜索结果的分数?我是否必须在客户端重新排序?
编辑:
这是我的更新代码。唯一缺少的部分是让资源投票提高搜索分数,同时将所有资源访问量
文档保留在 fotes
field 以便我以后可以访问它们。我正在使用Mongoose语法,但是与普通MongoDB语法的答案对我有用:
const searchResults = await Resource.aggregate()
.search({
compound: {
should: [
{
wildcard: {
query: queryStringSegmented,
path: ["title", "link", "creatorName"],
allowAnalyzedField: true,
}
},
{
wildcard: {
query: queryStringSegmented,
path: ["topics"],
allowAnalyzedField: true,
score: { boost: { value: 2 } },
}
}
,
{
wildcard: {
query: queryStringSegmented,
path: ["description"],
allowAnalyzedField: true,
score: { boost: { value: .2 } },
}
}
]
}
}
)
.lookup({
from: "resourcevotes",
localField: "_id",
foreignField: "resourceId",
as: "votes",
})
.addFields({
searchScore: { $meta: "searchScore" },
})
.facet({
approved: [
{ $match: matchFilter },
{ $skip: (page - 1) * pageSize },
{ $limit: pageSize },
],
resultCount: [
{ $match: matchFilter },
{ $group: { _id: null, count: { $sum: 1 } } }
],
uniqueLanguages: [{ $group: { _id: null, all: { $addToSet: "$language" } } }],
})
.exec();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它只能使用一个查询来完成,看起来与以下查询相似:
使用
$ lookup
步骤,如果您想使用票数来提高得分,您可以用以下内容替换上述
$ lookup
步骤:您可以在
编辑:如果您想对结果进行选票,则可以做类似的事情:
可以看到在这里
It could be done with one query only, looking similar to:
Using the
$lookup
step to get the votes from theResourceVote
collectionIf you want to use the votes to boost the score, you can replace the above
$lookup
step with something like:As you can see on this playground example
EDIT: If you want to keep the votes on the results, you can do something like:
As can be seen here