Working with N1QL

Working with N1QL

Explains how to Query a bucket using the N1QL query language.

Note: N1QL is currently experimental and may change in subsequent versions.

You need to make sure to have the query engine downloaded, started and pointed to your cluster. For more information, visit http://query.couchbase.com.

Next, you need to enable it either through a system property or through the environment builder. This step will go away once N1QL is fully integrated into the server:

// Through a system property
System.setProperty("com.couchbase.queryEnabled", "true");

Cluster cluster = CouchbaseCluster.create();
Bucket bucket = cluster.openBucket("beer-sample").toBlocking().single();
// Through the builder
Cluster cluster = CouchbaseCluster.create(DefaultCouchbaseEnvironment
    .builder()
    .queryEnabled(true)
    .build());

Bucket bucket = cluster.openBucket("beer-sample").toBlocking().single();

Finally, you can run a query using either raw N1QL strings or a DSL API:

// raw string query
Observable<QueryResult> query = bucket.query("SELECT * FROM beer-sample LIMIT 10");

// using the DSL
Observable<QueryResult> query = bucket.query(select("*").from("beer-sample").limit(10));

The select() method is a static import which kicks off a BNF (syntax) aware DSL for N1QL. It provides a typesafe and intuitive way to perform queries.

The query always returns a QueryResult, which aside from the actual QueryRows also contains debug or error information if supplied.

  • rows : Contains all rows returned by the query, can be an empty Observable.
  • info : Contains info-level JSON output from the server to debug the query (if success).
  • success : shorthand identifier to see if the query was a success.
  • error : If the query was not successful, contains a JsonObject identifying the error.

The following code prints the found documents and an error if it failed:

bucket
    .query(select("*").from("beer-sample").limit(10))
    .doOnNext(result -> {
        if (!result.success()) {
            System.err.println(result.error());
        }
    })
    .flatMap(QueryResult::rows)
    .toBlocking()
    .forEach(row -> System.out.println(row.value()));