javacouchbasesql++

How to retrieve metrics from Couchbase query?


I am trying to delete documents that have expired via a query. I am not using Couchbase's feature of expiring documents as I need better control over this.

Now apart from running a delete query like this

Instant threshold = Instant.now().minus(retention);
String query = String.format("delete from %s.%s.%s where _lastmodified < \"%s\"", bucketName, scopeName, collectionName, threshold);
QueryResult result = cluster.query(query);

I'd like to see some metrics how many documents were impacted. For this I am challenging the returning clause but it only partly works for me. I can do something like

Instant threshold = Instant.now().minus(retention);
String query = String.format("delete from %s.%s.%s where _lastmodified < \"%s\" returning _id, _lastmodified", bucketName, scopeName, collectionName, threshold);
QueryResult result = cluster.query(query);

and the query result will deliver all the identifiers and timestamps of the documents that were deleted. But I am more or also interested to see the metrics listed here: https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/insert.html#result

How can I get hold of those?


Solution

  • If the JSON returned by the server has a non-empty value for errors, the SDK always propagates the error as an exception.

    Similarly, if the status field in the JSON does not indicate success, the SDK always propagates the failure as an exception.

    If you enable metrics when executing the query, the QueryResult's metadata includes a QueryMetrics object you can inspect:

    QueryResult result = clusterOrScope.query(
      statement,
      QueryOptions.queryOptions()
        .metrics(true)
    );
    
    QueryMetaData md = result.metaData();
    QueryMetrics metrics = md.metrics().orElseThrow();
    
    System.out.println("elapsedTime = " + metrics.elapsedTime());
    System.out.println("executionTime = " + metrics.executionTime());
    System.out.println("resultCount = " + metrics.resultCount());
    System.out.println("resultSize = " + metrics.resultSize());
    System.out.println("mutationCount: " + metrics.mutationCount());
    

    References:
    https://docs.couchbase.com/java-sdk/current/howtos/sqlpp-queries-with-sdk.html#the-query-result