Join / Summarize with CouchDB

Using CouchDB , I have a document presenting an idea, you can evaluate this idea. Each idea is one document, and each rating is a different document. I do this in order to avoid concurrent access problems when people evaluate an idea.

My documents look like this (I simplified them):

Idea:

{ "_id": "idea1", "title": "A great idea" } 

Rating:

 { "_id": "rating1", "rating": 1, "author": "author1" } { "_id": "rating2", "rating": 1, "author": "author2" } 

I am currently using the reduction function to return me the idea ID and its rating (simple sum of ratings):

Map

 function(doc) { if (doc.type == "rating") emit(doc.idea_id, doc.rating); } 

Decrease:

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

My question is: how could I "join" the document "idea" with the result of the reduction, which represents the rating for this idea?

+4
source share
2 answers

Map

 function(doc) { switch (doc.type) { case "idea": emit(doc._id, ["idea", doc]); break; case "rating": emit(doc.idea_id, ["rating", doc.rating]); break; } } 

Decrease:

 function(keys, values, rereduce) { var i, l, ret = {idea:null, rating:0}; for (i = 0, l = values.length; i < l; ++i) { switch (values[i][0]) { case "idea": ret.idea = values[i][1]; break; case "rating": ret.rating += values[i][1]; break; } } return ret; } 

Another option would be to use view matching to do the trick.

+7
source

First of all, do not create your own _id, let CouchDB create uuid for you. This is much better, I promise you :)

Short answer: you cannot receive an idea document with anything other than an additional request. Although the request is pretty fast, since you have _id in your voting document.

If you want to return full documents for all votes to get comments or something else, you can do it. Just run a view request with: include_docs = true

+1
source

All Articles