问题描述
我的Couchbase中有一些带有以下模板的文档:
I have some documents in my Couchbase with the following template:
{
"id": 102750,
"status": 5,
"updatedAt": "2014-09-10T10:50:39.297Z",
"points1": 1,
"points2": -3,
"user1": {
"id": 26522,
...
},
"user2": {
"id": 38383,
...
},
....
}
我想要做的是将用户上的文档分组,并对每个用户的得分求和,然后显示上周的前100名用户.我一直在转悠,但没有任何解决方案.
What I want to do is to group the documents on the user and sum the points for each user and then show the top 100 users in the last week. I have been circling around but I haven't come with any solution.
我已经开始使用以下地图功能:
I have started with the following map function:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(doc.user1.id, doc.points1);
emit(doc.user2.id, doc.points2);
}
}
然后尝试求和以减少结果,但显然我错了,因为我无法对这些点进行排序,而且我也无法包含date参数
and then tried the sum to reduce the results but clearly I was wrong because I wasn't able to sort on the points and I couldn't also include the date parameter
推荐答案
我已经通过服务器端脚本的帮助解决了此问题.我所做的是将地图功能更改为:
I have solved this issue by the help of a server side script.What I have done is I changed my map function to be like this:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(dateToArray(doc.createdAt), { 'userId': doc.user1.id, 'points': doc.points1});
emit(dateToArray(doc.createdAt), { 'userId': doc.user2.id, 'points': doc.points2});
}
}
在脚本中,我用所需的参数查询视图,然后对它们进行分组和排序,然后发送前100名用户.
And in the script I query the view with the desired parameters and then I group and sort them then send the top 100 users.
我正在使用Node JS,所以我的脚本是这样的:(结果是我从沙发床视图中读取的内容)
I am using Node JS so my script is like this: (the results are what I read from couchbase view)
function filterResults(results) {
debug('filtering ' + results.length + ' entries..');
// get the values
var values = _.pluck(results, 'value');
var groupedUsers = {};
// grouping users and sum their points in the games
// groupedUsers will be like the follwoing:
// {
// '443322': 33,
// '667788': 55,
// ...
// }
for (var val in values) {
var userId = values[val].userId;
var points = values[val].points;
if (_.has(groupedUsers, userId)) {
groupedUsers[userId] += points;
}
else
groupedUsers[userId] = points;
}
// changing the groupedUsers to array form so it can be sorted by points:
// [['443322', 33], ['667788', 55], ...]
var topUsers = _.pairs(groupedUsers);
// sort descending
topUsers.sort(function(a, b) {
return b[1] - a[1];
});
debug('Number of users: ' + topUsers.length + '. Returning top 100 users');
return _.first(topUsers, 100);
}
这篇关于Couchbase自定义归约功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!