8192K
8192K

Reputation: 5280

Creating Couchbase views in code: First query returns 0 rows, index builds in background

I am creating a view in code using the Couchbase Java API 2.1.2 like this:

DefaultView view = DefaultView.create(viewName, jsMapFunctionAsString);
List<View> views = new ArrayList<>();
views.add(view);
DesignDocument doc = DesignDocument.create(name, views);
bucket.bucketManager().insertDesignDocument(doc);

Calling ViewResult result = bucket.query(ViewQuery.from(name, viewName)) directly after inserting the document, viewResult.success() always returns true, but both iterators rows() and iterator return 0 rows (there are definitely results present. When I execute the view in the web interface, it returns correct values).

The workaround I found after several hours is to call query twice with enough waiting time in between like

ViewResult result = bucket.query(ViewQuery.from(name, viewName));
Thread.sleep(10000);
result = bucket.query(ViewQuery.from(name, viewName));

The second call will then return the correct result.

It seems as if Couchbase has to build the index for the query first but returns directly, even before the index has been built.
Waiting 10 seconds is of course not optimal, maybe creating the index will take more time in the future.

So my question is, how can I make sure, that I only wait until the index has been built?
Is this a bug in the API?

Upvotes: 1

Views: 588

Answers (1)

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28301

You can use the stale method and set it to false in the ViewQuery, this will force to wait for the indexation to finish before returning results.

Upvotes: 4

Related Questions