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 that allows you to query nested structures commonly found within the document domain. SDK support for N1QL can be found at these levels: low-level support for ad hoc N1QL queries and at a higher-level abstraction as a Language-Integrated Query (LINQ) provider (currently in development).
At the time of writing, N1QL is available as part of Couchbase Server 4.0 developer preview. The client currently only supports N1QL when all nodes in the cluster are running it.
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);
}
The example creates a query that targets the tutorial bucket, aliases it as c
and returns all of the child elements from the documents in that bucket.
Then it executes the query using the IBucket.Query(...)
method, typing it as a common language runtime (CLR) dynamic type.
The result of the query is then iterated over and displayed to stdout
.
The return type of the IBucket.Query
method is an object implementing the IQueryResult<T>
interface and contains the following properties:
Name | Description |
---|---|
|
The error message returned by the N1QL engine |
|
A |
|
true if the query completed successfully |
You can also construct a query via the IQueryRequest
interface, which allows more parameters to be set for the N1QL service.
Reading your own writes (RYOW)
To read your own writes, you need to use the IQueryRequest
API.
There’s an ScanConsistency
method that can be used for that, with the REQUEST_PLUS
value:
var request = QueryRequest.Create("SELECT * FROM default");
request.ScanConsistency(ScanConsistency.REQUEST_PLUS);
bucket.Query(request);