我使用 Atlas Search 回傳檔案串列(使用 Mongoose):
const searchResults = await Resource.aggregate()
.search({
text: {
query: searchQuery,
path: ["title", "tags", "link", "creatorName"],
},
}
)
.match({ approved: true })
.addFields({
score: { $meta: "searchScore" }
})
.exec();
用戶可以對這些資源進行投票(例如 Stackoverflow 上的問題)。我想根據這些投票來提高搜索分數。
我可以為此使用boost運算子。
問題:投票不是Resource檔案的屬性。相反,它們存盤在一個單獨的集合中:
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
}
然后,我從客戶端的贊成票中減去反對票,并在 UI 中顯示最終數字。
如何將此投票點值合并到搜索結果的分數中?我必須在客戶端重新訂購它們嗎?
uj5u.com熱心網友回復:
它可以只用一個查詢來完成,看起來類似于:
Resource.aggregate([
{
$search: {
text: {
query: "searchQuery",
path: ["title", "tags", "link", "creatorName"]
}
}
},
{$match: {approved: true}},
{$addFields: {score: {$meta: "searchScore"}}},
{
$lookup: {
from: "ResourceVote",
localField: "_id",
foreignField: "resourceId",
as: "votes"
}
}
])
使用$lookup步驟從ResourceVote集合中獲取選票
如果您想使用投票來提高分數,可以將上述$lookup步驟替換為:
{
$lookup: {
from: "resourceVote",
let: {resourceId: "$_id"},
pipeline: [
{
$match: {$expr: {$eq: ["$resourceId", "$$resourceId"]}}
},
{
$group: {
_id: 0,
sum: {$sum: {$cond: [{$eq: ["$upDown", "up"]}, 1, -1]}}
}
}
],
as: "votes"
}
},
{$addFields: { votes: {$arrayElemAt: ["$votes", 0]}}},
{
$project: {
"wScore": {
$ifNull: [
{$multiply: ["$score", "$votes.sum"]},
"$score"
]
},
createdAt: 1,
score: 1
}
}
正如您在這個游樂場示例中看到的那樣
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465392.html
標籤:mongodb 猫鼬 Lucene mongodb-图集
