MattoTodd
MattoTodd

Reputation: 15199

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], 1);
        }
    },

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

Upvotes: 3

Views: 4611

Answers (2)

Dominic Barnes
Dominic Barnes

Reputation: 28429

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.

Upvotes: 6

Lodewijk
Lodewijk

Reputation: 3971

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.

Upvotes: 4

Related Questions