Callback to let observer know that newly inserted document was indexed

My use-case is to insert a new document and immediately after run a N1QL query which should include the newly inserted document. This is how I insert the document:

WebAppServletContextListener.collection.insert(docName, doc);
runN1qlQuery();

The newly inserted doc is not included in the result set. But it will if I run have this code:

WebAppServletContextListener.collection.insert(docName, doc);
try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
runN1qlQuery();

I think this is because the document takes time to get indexed. Is there a way to find out when this is the case, i.e. with a callback? Something like this:

WebAppServletContextListener.collection.insert(docName, doc, new IndexListener("specified-index-A", "specified-index-B") {
            @Override
            public void onIndexed() {
                runN1qlQuery();
            }
        });

I’m also open to other solutions to solve the use-case appropriately!

@benjamin_glatzeder your solution is to set the scan consistency on the n1ql query to REQUEST_PLUS which will tell the indexer to wait until the request has been indexed before returning it to the query engine.

1 Like

Here’s a snippet with the recommended approach:

cluster.query("SELECT ...", QueryOptions.queryOptions().scanConsistency(QueryScanConsistency.REQUEST_PLUS));

There is a small issue in the Java documentation. The code snippets are in C#: https://docs.couchbase.com/java-sdk/3.0/concept-docs/n1ql-query.html

@benjamin_glatzeder the section you linked is the general concept doc - here is the java one: https://docs.couchbase.com/java-sdk/3.0/howtos/n1ql-queries-with-sdk.html

1 Like