Skip to content

Instantly share code, notes, and snippets.

@TheNicholasNick
Created April 2, 2009 23:56
Show Gist options
  • Save TheNicholasNick/89572 to your computer and use it in GitHub Desktop.
Save TheNicholasNick/89572 to your computer and use it in GitHub Desktop.
CouchDB Map/Reduce Example
// Data
[
{"_id":"pvg:IHC09A","_rev":"1-3881006720","nvic":"IHC09A","family":"159","couchrest-type":"GRD::Pvg","make":"ALFA ROMEO"},
{"_id":"pvg:IJU09A","_rev":"1-243536901","nvic":"IJU09A","family":"147","couchrest-type":"GRD::Pvg","make":"ALFA ROMEO"},
{"_id":"pvg:IJV09A","_rev":"1-3794903136","nvic":"IJV09A","family":"147","couchrest-type":"GRD::Pvg","make":"ALFA ROMEO"},
{"_id":"pvg:IJY09A","_rev":"1-1301614913","nvic":"IJY09A","family":"147","couchrest-type":"GRD::Pvg","make":"ALFA ROMEO"},
{"_id":"pvg:J3X09A","_rev":"1-1398113861","nvic":"J3X09A","family":"V8","couchrest-type":"GRD::Pvg","make":"ASTON MARTIN"}
]
// Map
function(doc) {
if (doc['couchrest-type'] == 'GRD::Pvg' && doc.make && doc.family) {
emit(doc.make, doc.family);
}
}
// Reduce
function(keys, values, rereduce) {
var totals = {}
for (i in values) {
if (totals[values[i]] == undefined) {
totals[values[i]] = 1
} else {
totals[values[i]]++
}
}
return totals
}
// reults in w/ group=true
{"rows":[
{"key":"ALFA ROMEO","value":{"147":3,"159":1}},
{"key":"ASTON MARTIN","value":{"V8":1}}
]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment