Quering CouchDB for scalar values with Map/Reduce view and Ektorp library
Besides not too bad documentation for the library itself, for some reason I couldn’t execute the query to retrieve scalar value from the database using an array of keys.
The problem:
Get the count of all documents created by specific user and belonging to a single group. Each document in my database of type ‘CONTRACTOR’ belongs to one or more ‘CONTRACTOR_GROUP’s.
First of all we need to create our mapping function to get the specific documents. This mapping function must use a key we are going to match against while executing our query from java application.
1 2 3 4 5 6 7 | function(doc) { if(doc.type == 'CONTRACTOR' && doc.userID){ for(var g in doc.groupList){ emit([doc.userID, doc.groupList[g].name],1); } } } |
For each group find we return a single number ’1′ (used later on within reduce stage).
Reducing map results:
1 2 3 | function (key, values, rereduce) { return sum(values); } |
In other words for each document of type CONTRACTOR, iterate over all the groups it belongs to emit value 1
In the reduce stage we just count all the results together.
The java part:
1 2 3 4 5 6 7 8 9 | public int getNumberOfContractors(String userID, String groupName) { ViewQuery query = createQuery("list_by_userID") .group(true) .dbPath(db.path()) .designDocId(stdDesignDocumentId) .key(new String[]{userID,groupName}); ViewResult r = db.queryView(query); return r.getRows().get(0).getValueAsInt(); } |
The biggest problem I got before figuring out this query was how to construct the ViewQuery object to get the scalar value from our reduce function and to pass it an array of 2 keys needed to execute it right, and get a single result.
ViewQuery object contains the method ‘.keys(..)’ which takes a Collection
Using a trial and error approach I have constructed my query with a key of simple String array and this happened to work so I’m sharing this with anyone having the same problems.
All of you who knows a better approach to this problem are more than welcome to comment below.
2 responses on “Quering CouchDB for scalar values with Map/Reduce view and Ektorp library”
Leave a Reply
Related Posts
No Releated Posts
I think the admin of this website is in fact working hard for his web site, because
here every material is quality based data.