通过reddit排名算法对mongodb进行排序

Sorting mongodb by reddit ranking algorithm(通过reddit排名算法对mongodb进行排序)
本文介绍了通过reddit排名算法对mongodb进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是一个根据 Reddit 的排名算法对项目进行排名的 js 代码.

Here is a js code to rank items according to Reddit's ranking algorithm.

我的问题是:如何使用此代码对我的 mongodb 文档进行排名?

My question is: how do I use this code to rank my mongodb documents ?

(Reddit的排名算法)

function hot(ups,downs,date){
    var score = ups - downs;
    var order = log10(Math.max(Math.abs(score), 1));
    var sign = score>0 ? 1 : score<0 ? -1 : 0;
    var seconds = epochSeconds(date) - 1134028003;
    var product = order + sign * seconds / 45000;
    return Math.round(product*10000000)/10000000;
}
function log10(val){
  return Math.log(val) / Math.LN10;
}
function epochSeconds(d){
    return (d.getTime() - new Date(1970,1,1).getTime())/1000;
}

推荐答案

你可以使用mapReduce:

Well you can use mapReduce:

var mapper = function() {

    function hot(ups,downs,date){
        var score = ups - downs;
        var order = log10(Math.max(Math.abs(score), 1));
        var sign = score>0 ? 1 : score<0 ? -1 : 0;
        var seconds = epochSeconds(date) - 1134028003;
        var product = order + sign * seconds / 45000;
        return Math.round(product*10000000)/10000000;
    }

   function log10(val){
      return Math.log(val) / Math.LN10;
   }

   function epochSeconds(d){
       return (d.getTime() - new Date(1970,1,1).getTime())/1000;
   }

   emit( hot(this.ups, this.downs, this.date), this );

};

然后运行 mapReduce(不使用 reducer):

And the run the mapReduce (without a reducer):

db.collection.mapReduce(
    mapper,
    function(){},
    {
        "out": { "inline": 1 }
    }
)

当然,假设您的收藏"包含 upsdownsdate 字段.当然,排名"需要以独特"的方式发出,否则您需要一个reducer"来整理结果.

And of course presuming that your "collection" has the fields for ups, downs and date. Of course the "rankings" need to be emitted in a way that is "unique" otherwise you need a "reducer" to sort out the results.

但一般来说应该可以完成这项工作.

But generally speaking that should do the job.

这篇关于通过reddit排名算法对mongodb进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)