Skip to content

Instantly share code, notes, and snippets.

@copenhas
Created June 6, 2011 14:03
Show Gist options
  • Save copenhas/1010318 to your computer and use it in GitHub Desktop.
Save copenhas/1010318 to your computer and use it in GitHub Desktop.
example couchdb map/reduce
/*
So with documents as such:
{
one_id : 1,
another_id : 22,
created_at : "2011-05-26 23:22:11",
a_name : "Lisa"
}
We want to get a count of the unique 'a_name' values possibly
filtering by the 'created_at' or the id fields.
*/
//Map:
function (doc) {
emit([doc.created_at, doc.one_id, doc.another_id], doc.a_name);
}
//Reduce:
function (key, values, rereduce) {
if (rereduce) {
//rereduce is true:
//key is null
//values is an array of the results we have returned from the reduce
//now aggregate the original reduce results
//which are in documents of { <name>: <count> ... }
//structure
var results = { };
for(var i = 0; i < values.length; i++) {
for(var name in values[i]) {
if (results[name]) results[name] += values[i][name];
else results[name] = values[i][name];
}
}
return results;
}
//rereduce is false:
//key will be an array of the map's emitted keys
//values will be an array of the map's emitted values in the same
//order as the keys
//group and count the docs by the name
//which is the value the map function emitted
var results = { };
for(var i = 0; i < values.length; i++) {
var name = values[i];
if (results[name]) results[name]++;
else results[name] = 1;
}
return results;
}
/*
example results:
{ John: 4, Jane: 6 }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment