javascript - 按相关性能问题排序

标签 javascript node.js mongodb mongoose relevance

mongoose(和/或 mongodb)中是否有函数/方法可用于根据相关性(匹配查询参数的最大数量)对查询结果进行排序?

下面的示例是我目前正在使用的示例(查询使用 $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'}}
])

结果:

/* 1 */
{
    "_id" : ObjectId("57be8a9b65d2835e960df543"),
    "relevance" : 3,
    "doc" : {
        "_id" : ObjectId("57be8a9b65d2835e960df543"),
        "fruits" : [ 
            "apple", 
            "orange", 
            "tomato"
        ],
        "colors" : [ 
            "blue", 
            "green"
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("57be8aa865d2835e960df544"),
    "relevance" : 2,
    "doc" : {
        "_id" : ObjectId("57be8aa865d2835e960df544"),
        "fruits" : [ 
            "apple", 
            "carrot"
        ],
        "colors" : [ 
            "red", 
            "green"
        ]
    }
}

关于javascript - 按相关性能问题排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137675/

相关文章:

javascript - 基于 jquery 的图像拼接墙布局

node.js - 任务超时表达AWS lambda

javascript - 发送ajax请求到远程node.js服务器

java - MongoDB:错误代码 - 10068,无效运算符:$oid

c# - 使用 C# 检索 MongoDB 文档并选择一个字段

javascript - 延迟更改的文本区域

javascript - meteor 集合不会在刷新时加载

php - 通过 Ajax 将 Javascript 对象发送到 PHP

c++ - node.js 的 v8 扩展 - 无法将 FunctionTemplate 设置为目标

python - 如何使用 python 在现有的 mongoDB 文档中添加具有特定数据类型(列表、对象)的字段