After running this program (please change the URL or bucket name as appropriate) you should now have 10 users in your bucket.

The next step is to a User design document with a Rank view.

The first step is create a simple Map for the Rank view which will emit the experience attribute:

function (doc, meta) {

if (doc.experience)

emit(doc.experience, null);

}

Doing so will create an index based on experience attribute but will not allow to determine the ranking.

This is where adding a Reduce fits in. We will add simple built-in _count reduce.

The full view should look like this:

The Reduce function allows to aggregate the number of User documents with a known experience value (if doc.experience).

By not specifying any query parameter, it will output 10 which is the number of documents that we have created.

In order to look up the ranking of a specific User what we need to do is first look up the ranking of a given user (User5 in this example):

// Look up a specific user

String jsonString = (String) client.get("User5");

user = json.fromJson(jsonString, UserDoc.class);

From there, we can create a query which will filter this count with a range query with a descending order which will start by max value to capture all the users which have a greater experiencethe experience and end with value for the user:

View view = client.getView("User", "Rank");

Query query = new Query();

query.setIncludeDocs(true).setLimit(10000);

query.setRangeStart(Long.toString(Long.MAX_VALUE));

query.setRangeEnd(Long.toString(user.experience));

query.setDescending(true);

query.setReduce(true);

As such the reduce will output the number of users which have a greater experience than the experience for that user. The ranking is simply that number + 1.

ViewResponse response = client.query(view, query);

Iterator<ViewRow> itr = response.iterator();

while (itr.hasNext()) {

ViewRow row = itr.next();

System.out.println("Rank: " + Long.parseLong(row.getValue()) + 1 );

}

This will output the Rank based on the experience for that user such as: