1
votes

I have a requirement of finding the total number of documents while performing a query without fetching them in cloudant.

I'm using the cloudant client https://github.com/cloudant/java-cloudant . Generally to fetch documents I use "findByIndex()" method.

Now my requirement is to get "only" the total count of documents that can fetched by the selector that is specified in first argument of findByIndex().

I don't want to fetch all the documents and count them on the client side as that will take up all the network bandwidth and the memory.

From the search I do see its possible via the reduce function given here: http://guide.couchdb.org/editions/1/en/cookbook.html#aggregate

But how do I use this reduce function on the java client for cloudant? Is there some other way to achieve this?

2

2 Answers

1
votes

The documentation for querying a view is https://github.com/cloudant/java-cloudant#query-on-a-view

I quickly ran an example using groovysh (which uses the java api) against the cloudant education account's animaldb.

You can see the raw results of the example query by hitting this url with your browser: https://education.cloudant.com/animaldb/_design/views101/_view/diet_count?reduce=true&group=true&key=%22omnivore%22

{"rows":[
   {"key":"omnivore","value":3}
]}

The groovy program (note the first two lines using Grape are just for pulling in the cloudant java library):

groovy:000> import groovy.grape.Grape
groovy:000> Grape.grab(group:'com.cloudant', module:'cloudant-client', version:'1.0.1')
groovy:000> import com.cloudant.client.api.CloudantClient
groovy:000> client = new CloudantClient('education', 'education')
groovy:000> db = client.database('animaldb', false)
groovy:000> omnivores = db.view("views101/diet_count").key('omnivore').queryForInt()
===> 3

Here is the equivalent java code:

CloudantClient client = new CloudantClient('education', 'education');
Database db = client.database('animaldb', false);
int omnivores = db.view("views101/diet_count").key('omnivore').queryForInt();
0
votes

The findByIndex function uses Cloudant Query indexes. This index type doesn't support returning the total count of results right now.

The link http://guide.couchdb.org/editions/1/en/cookbook.html#aggregate refers to Views, a different type of index on Cloudant. Reduces only work in Views and not Query indexes. You'll need to use a view, as Chris Snow suggests, to get the total count efficiently via a reduce.

Unfortunately you can't use a regex in a view (which you mention your Cloudant Query selector uses). However, perhaps you can create a key in the view's map function which allows the same query to be performed.