Working with N1QL Queries

Pronounced “nickel”, N1Ql is Couchbase’s next generation language for querying JSON documents. Similar in syntax to traditional SQL found in all relational databases, N1QL is an extended non-first normal form variation which allows you to query nested structures commonly found within the document domain. SDK support for N1QL can be found at two different levels: low level support for ad-hoc N1QL queries and at a higher level abstraction as a LINQ provider (currently in development).

At the time of writing, N1QL is available as Developer Preview 3 (DP3). To use the developer preview with the SDK, you will need to download and install the N1QL DP3 which can be found here. Once you have downloaded and extracted DP3, follow the directions to start the tutorial; the client currently only works with the tutorial running on localhost:8093

For running ad-hoc N1QL queries, the client has a single method which takes a string that must be a valid N1QL query. Here is an example of executing a simple query using the SDK:


 const string query = "SELECT c FROM tutorial as c";
 var result = bucket.Query<dynamic>(query);
 foreach (var row in result.Rows)
 {
     Console.WriteLine(row);
 }
   

Here we create a query which targets the tutorial bucket, aliases it as “c” and returns all of the “children” elements from the documents in that bucket. Then we execute the query using the IBucket.Query(...) method, typing it as a CLR dynamic type. The result of the query is then iterated over and displayed to stdout.

Note the return type of the IBucket.Query method is an object implementing the the IQueryResult<T> interface:

Name Description
Error The error message returned by the N1QL engine
Rows A List<T> of T, which is the result of the query
Success true if the query completed successfully