【问题标题】:Couchbase custom reduce functionCouchbase 自定义 reduce 功能
【发布时间】:2014-11-06 12:19:31
【问题描述】:

我的 Couchbase 中有一些文档,模板如下:

{
  "id": 102750,
  "status": 5,
  "updatedAt": "2014-09-10T10:50:39.297Z",
  "points1": 1,
  "points2": -3,
  "user1": {
      "id": 26522,
      ...
  },
  "user2": {
      "id": 38383,
      ...
  },
  ....
}

我要做的是对用户上的文档进行分组并对每个用户的分数求和,然后显示上周排名前 100 的用户。我一直在转,但我没有找到任何解决方案。

我已经开始使用以下地图功能:

function (doc, meta) {
  if (doc.user1 && doc.user2) {
    emit(doc.user1.id, doc.points1);
    emit(doc.user2.id, doc.points2);
  }
}

然后尝试求和以减少结果,但显然我错了,因为我无法对点进行排序,也无法包含日期参数

【问题讨论】:

  • 看看blog.couchbase.com/using-map-and-reduce-view-ranking - 这应该与您想要实现的目标非常相似。
  • 感谢@DaveRigby 的回复,但您提供的链接描述了如何查找指定用户的排名。我需要的是知道指定时间段内排名前 100 的用户

标签: mapreduce couchbase


【解决方案1】:

您需要查看我的示例,我能够按日期分组并使用 reduce 显示值。但计算我在我的程序中所做的总和。

查看回复How can I groupBy and change content of the value in couchbase?

【讨论】:

    【解决方案2】:

    我在服务器端脚本的帮助下解决了这个问题。 我所做的是将我的地图功能更改为这样:

    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 个用户。

    我使用的是 Node JS,所以我的脚本是这样的:(结果是我从 couchbase 视图中读取的)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2019-09-02
      • 2021-01-11
      • 2012-09-11
      相关资源
      最近更新 更多