按相关性sorting问题

有没有函数/方法mongoose(和或mongodb)可用于sorting查询结果基于相关性(最高匹配的查询参数)?

下面的例子是我目前使用的(查询使用$in:[] ,否则相同) – 我的集合是相当小的,所以性能很好,但在较大的集合,它显着减缓了事情。

另外,如果有一个更好的执行方法(mongoose/ mongodb之外),我会很高兴知道这件事。

例:

 var docs = [ { fruits: ['apple', 'orange', 'tomato'], colors: ['blue', 'green'], // relevance: 3 }, { fruits: ['apple', 'carrot'], colors: ['red', 'green'], // relevance: 2 } ] var query = {fruits: ['apple', 'orange'], colors: ['green']} docs.forEach(function(doc){ var relevance = 0 Object.keys(query).forEach(function(_query){ var arrays = [doc[_query], query[_query]] var result = arrays.shift().filter(function(v) { return arrays.every(function(a) { return a.indexOf(v) !== -1; }); }); relevance += result.length }) doc.relevance = relevance }) 

结果:

 var docs = [ { fruits: ['apple', 'orange', 'tomato'], colors: ['blue', 'green'], relevance: 3 }, { fruits: ['apple', 'carrot'], colors: ['red', 'green'], relevance: 2 } ] 

你可以用聚合来完成:

 db.getCollection('docs').aggregate([ {$match: {fruits: {$in: ['apple', 'orange']}, colors: {$in: ['green']}}}, {$project: { relevance: { $sum: [ {$cond: {if: { "$setIsSubset": [['orange'], "$fruits" ]}, then: 1, else: 0}}, {$cond: {if: { "$setIsSubset": [['apple'], "$fruits" ]}, then: 1, else: 0}}, {$cond: {if: { "$setIsSubset": [['green'], "$colors" ]}, then: 1, else: 0}}] }, doc: '$$ROOT'}} ]) 
Interesting Posts