开发者

couchdb map-reduce and grouping

I am attempting to get a count of unique events for an object (lets say a video):

Here are my documents:

{
  "type":"View",
  "video_id": "12300",
  "user_id": 3
}

{
  "type":"View",
  "video_id": "12300",
  "user_id": 1
}
{
  "type":"View",
  "video_id": "45600",
  "user_id": 3
}

I'm trying to get a unique (by user_id) count of views for each video

I assume I want to map my data like so:

function(doc) {
        if (doc.type === 'View') {
           emit([doc.video_id, doc.user_id], 开发者_JS百科1);
        }
    },

But I don't understand how to reduce it down to unique users per video, or am I going about this wrong.


You should look at the group_level view parameter. It will allow you to change what field(s) the grouping occurs on.

By using group_level = 1, in this case it will group by video_id. Using group_level = 2, it will group on both video_id and user_id.


Add ?group=true after the request URL. That groups identical keys together as input for the reduce function:

function(keys, values, rereduce){
  return sum(values);
}

That should do it.

Note that keys and values are unzipped lists of keys and their values. With grouping on the keys are all identical for each call of the reduce.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜