QnaList > Groups > Couchdb-User > Nov 2009
faq

Sorting Items By Number Of Votes

Hi.  I'm new to CouchDB (and this list) and I am looking for some  
help.  I am trying to do something very similar to http://wiki.apache.org/couchdb/View_Snippets#aggregate_sum
.
I have a database with 2 types of documents, resources and votes.  The  
documents in the database look something like this:
resource 1 {_id: 1, type:"resource", name:"resource 1", ...}
resource 2 {_id: 2, type:"resource", name:"resource 2", ...}
resource 3 {_id: 3, type:"resource", name:"resource 3", ...}
vote for resource 3 {type:"vote", resource_id: 3, user_id: foo}
vote for resource 2 {type:"vote", resource_id: 2, user_id: foo}
vote for resource 3 {type:"vote", resource_id: 3, user_id: bar}
I want to create a view that will give me the resources in order of  
the most votes along with the number of votes.  In other words, I want  
to write a view that gives me something like the following results:
{id:3, key:3, value:{doc:(document for resource 3), score: 2}},
{id:2, key:2, value:{doc:(document for resource 2), score: 1}},
{id:1, key:1, value:{doc:(document for resource 1), score: 0}},
Here is my map function:
function(doc) {
	if (doc.type == 'vote' && doc.resource_id) {
		emit(doc.resource_id, doc);
	} else if (doc.type == 'resource' && doc.name) {
		emit(doc._id, doc);
	}
}
Here is my reduce function:
function(keys, values, rereduce) {
	var score = 0;
	var output_doc = {};
	for (var i=0; i < values.length; i++) {
		if (values[i].type == 'vote') {
			++score;
		} else if (values[i].type == 'resource') {
			output_doc = values[i];
		}
	}
	return {doc:output_doc, score:score};
}
When I query this view in Futon I get the following error:
"Reduce output must shrink more rapidly"
Am I trying to do something that can't be done with CouchDB?  Or am I  
just missing something?
Thanks so much for any help.
- Devon

asked Nov 5 2009 at 13:46

Devon Weller's gravatar image



1 Replies for : Sorting Items By Number Of Votes
That is true.  My app would need to detect the conflict, reload the  
document, add the vote to the array again and re-try the update.  I  
don't imagine enough collisions will occur in my app that this will be  
a problem.  And I believe it will make my views a lot easier to deal  
with.
- Devon

answered Nov 5 2009 at 20:05

Devon Weller's gravatar image


Related discussions

Tagged

Group Couchdb-user

asked Nov 5 2009 at 13:46

active Nov 5 2009 at 20:05

posts:2

users:1

©2013 QnaList.com