Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

javascript - Sorting mongodb by reddit ranking algorithm

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

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

(Reddit's ranking algorithm)

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );

};

And the run the mapReduce (without a reducer):

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...