問題描述
這是一個根據(jù) Reddit 的排名算法對項(xiàng)目進(jìn)行排名的 js 代碼.
Here is a js code to rank items according to Reddit's ranking algorithm.
我的問題是:如何使用此代碼對我的 mongodb 文檔進(jìn)行排名?
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 );
};
然后運(yùn)行 ??mapReduce(不使用 reducer):
And the run the mapReduce (without a reducer):
db.collection.mapReduce(
mapper,
function(){},
{
"out": { "inline": 1 }
}
)
當(dāng)然,假設(shè)您的收藏"包含 ups
、downs
和 date
字段.當(dāng)然,排名"需要以獨(dú)特"的方式發(fā)出,否則您需要一個reducer"來整理結(jié)果.
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.
但一般來說應(yīng)該可以完成這項(xiàng)工作.
But generally speaking that should do the job.
這篇關(guān)于通過reddit排名算法對mongodb進(jìn)行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!