【问题标题】:Paginating a mongoose mapReduce, for a ranking algorithm为 mongoose mapReduce 分页,用于排名算法
【发布时间】:2016-04-17 07:09:15
【问题描述】:

我正在使用 MongoDB mapReduce 来编写排名提要算法,它几乎可以工作,但最新实现的是分页。 map reduce 支持结果限制,但我如何实现基于偏移(跳过),例如在最新查看的_id 上,知道我在使用猫鼬吗?

这是我写的程序:

o = {};

o.map = function() {
    //log10(likes+comments) / elapsed hours from the post creation
    emit(Math.log(this.likes + this.comments + 1) / Math.LN10 / Math.abs((now - this.createdAt) / 6e7 + 1), this);
};

o.reduce = function(key, values) {
    //sort the values, when they have the same score
    values.sort(function(a, b) {
        a.createdAt - b.createdAt;
    });

    //serialize the values, because mongoose does not support multiple returned values
    return JSON.stringify(values);
};

o.scope = {now: new Date()};
o.limit = 15;

Posts.mapReduce(o, function(err, results) {
    if (err) return console.log(err);
    console.log(results);
});

另外,如果 mapReduce 这不是要走的路,你是否建议其他关于如何实现这样的东西?

【问题讨论】:

    标签: node.js mongodb mongoose pagination mapreduce


    【解决方案1】:

    您需要的是一个页面分隔符,它不是您所说的最新查看的 id,而是您的排序属性。在这种情况下,它似乎是公式Math.log(this.likes + this.comments + 1) / Math.LN10 / Math.abs((now - this.createdAt) / 6e7 + 1)

    因此,在您的 mapReduce 中,query 需要保留上述公式的 where 值。或者具体来说,'formula >= . And also it needs to hold the value of createdAt at the last page, since you don't sort by that. (Assuming createdAt is unique). So yourqueryof mapReduce would saywhere: theFormulaExpression, createdAt: { $lt: lastCreatedAt }`

    如果您确实允许多个相同的 createdAt 值,则必须在数据库本身之外进行一些操作。

    所以你只需按公式搜索。

    理想情况下,这会为您提供一个具有该值的元素,并在此之后排序下一个元素。因此,作为对模块调用者的回复,从数组中删除第一个元素(并确保您实际要求的结果比您需要的更多)。

    现在,由于您允许多个相似的值,您需要另一个标识属性,例如对象 id 或 created_at。您的消费者(此模块的调用者)必须同时提供(last value of the scorecreatedAt of the last object)。假设您有一个页面正好在中间拆分 - 一个或多个对象在前一页上,另一个在下一个页面上 .您不必简单地删除最高值(因为相同的分数已在前一页上提供),但可能有几个从顶部开始。

    然后它变得真的疯狂,因为可能你的整个页面已经被提供 - 比较_id,在你的模块调用者提供给你的那个之后寻找第一个。或者查看数据并确定有多少这样的匹配值,尝试从 mapReduce 中获取至少与实际页面大小一样多的值。

    除此之外,我会改为使用聚合来执行此操作,它应该更加高效。

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 2015-04-15
      • 2017-05-23
      相关资源
      最近更新 更多