【问题标题】:Sorting mongodb by reddit ranking algorithm通过reddit排名算法对mongodb进行排序
【发布时间】:2014-05-08 20:23:35
【问题描述】:

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

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

(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;
}

【问题讨论】:

  • 好的,感谢您发布该代码!

标签: javascript mongodb mapreduce


【解决方案1】:

你可以使用 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):

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

当然,假设您的“收藏”具有upsdownsdate 的字段。当然,“排名”需要以“独特”的方式发出,否则您需要一个“reducer”来整理结果。

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

【讨论】:

  • 什么是“内联”?能不能加入reducer函数?
【解决方案2】:

你的函数有问题:

new Date(1970, 1, 1) // Sun Feb 01 1970 00:00:00 GMT-0300 (BRT)

是的,第 1 个月是 2 月,它也使用系统 timezone。 JavaScript 中的 Epoch 是

var epoch = new Date(Date.UTC(1970, 0, 1))

自从

epoch.getTime() // 0

功能

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

应该只是

function epochSeconds(d){
    return d.getTime()/1000;
}

稍微压缩一下,返回的结果和http://amix.dk/blog/post/19588中的python函数一模一样

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

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 2015-04-15
    • 2014-10-17
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多