【发布时间】:2021-01-27 04:14:22
【问题描述】:
我有一个使用 MongoDB(使用 Mongoose 驱动程序)的 Node/NestJS 后端应用程序。对于“获取”功能,我设置了一个聚合管道,首先可以应用一些“硬”过滤器,完全过滤掉内容 - 现在我想要一些软过滤器,对搜索结果进行排名并过滤掉它们无关的。该算法应该使用文档上的三个字段:标题、描述和标签。标题和标签应该是其中最重要的。如果总相关性得分低于某个阈值,则将排除结果。现在,我已经检查了其他几个 StackOverflow 帖子,例如this one,但它们似乎都与“标签”字段有关。我找到了suggested to use indexes for this 的一个文档,但如果我大致知道该怎么做,我最好希望通过聚合框架来做。
下面是另一个应用程序的代码,用于演示该功能;
do {
let reg
if (Array.isArray(searchString)) {
reg = new RegExp(searchString[i], 'gi')
} else {
reg = new RegExp(searchString, 'gi')
}
for (const note of this.notes) {
const countTitle = (note.title.match(reg) || []).length
note.searchScore += countTitle
let countTags = 0
for (const tag of note.tags) {
const tagLength = (tag.match(reg) || []).length
countTags += tagLength
}
note.searchScore += countTags * 0.5
const countContent = (note.content.match(reg) || []).length
note.searchScore += countContent * 0.3
}
i++
} while (!Array.isArray(searchString) && i < searchString.length)
this.toDisplay = this.notes.filter(
f => f.searchScore > 0 + searchString.length / 4
)
this.showNew = false
this.sortUp = false
this.sortItems('relevance')
} else {
this.updateUI()
}
}
上面的算法接受一个字符串或字符串数组。标题、标签和描述/内容的权重分别为 1、0.5 和 0.3。设置了一个阈值,当分数低于或等于 0 + 搜索词的数量除以 4 时,项目被完全过滤掉。可以调整值,但本质上,这是我想在聚合框架内实现的算法.它会是什么样子?提前致谢。
【问题讨论】:
标签: mongodb mongoose aggregation-framework