Blog

Quering CouchDB for scalar values with Map/Reduce view and Ektorp library

I have encountered a problem today when I was trying to execute a simple Map/Reduce query within my pet project using Ektorp java 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.

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:

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:

 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 type as an argument but for some reason I couldn’t make it work, there is a class for constructing complex keys within the Extorp library called ComplexKey but this didn’t work either with this view (I have it working for other views without reduce step).
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

  1. what is web scraper December 19, 2012 at 12:08 pm

    I think the admin of this website is in fact working hard for his web site, because
    here every material is quality based data.

Leave a Reply