N1QL from the SDK
Edit this article in GitHub
Version 2.3

N1QL from the SDK

To issue N1QL queries you must pass an couchbase.N1qlQuery object to the Bucket.query() function which will then send the query to the cluster and invoke the passed callback.

You can create a query object by using the couchbase.N1qlQuery.fromString() constructor. Once the query has been created you can then modify some query options such as its consistency and adhoc properties using the N1qlQuery.consistency() and N1qlQuery.adhoc() setters.
var N1qlQuery = couchbase.N1qlQuery;
// ...
query = N1qlQuery.fromString('SELECT name, email FROM default LIMIT 10');
bucket.query(query, function(err, rows, meta) {
  for (row in rows) {
    console.log('Name: %s. Email: %s', row.name, row.email);
  }
});

The callback is invoked with an error, an array of rows, and additional metadata about the result and execution. Generally, you should check the error before iterating over the rows.

Placeholders

Queries can be parameterized, allowing you to specify placeholders within the query string and then specify them as discreet parameters when executing the query.
query = N1qlQuery.fromString('SELECT name, email FROM users WHERE name=$1');
bucket.query(query, ['Monty Python'], function(err, rows) {
  // ...
});
In the above, the second argument passed is the parameter list for the placeholders. Placeholders can either be specified as $1, $2, $3, etc for positional parameters which must be passed in an array or they can be specified as $name, $email, etc for named parameters which must be passed as an object. A named or poditional parameter is a placeholder for a value in the WHERE, LIMIT or OFFSET clause of a query.

Streaming rows

If you are expecting a large result set from the server you can omit passing the callback to the query() function and instead register to the returned object's row, end, and error events. The row handler is invoked whenever new rows arrive from the cluster, so you don't need to buffer all rows in memory to process them. The error handler is invoked in the case of an error and the end handler is invoked when the response has fully been received.
var q = N1qlQuery.fromString('SELECT * FROM `travel-sample` LIMIT 10');
var req = bucket.query(q);
req.on('row', function(row) {
  console.log('Got a row');
});
req.on('error', function(err) {
  console.error('Got error %j', err);
});
req.on('end', function(meta) {
  console.log('All rows received. Metadata is %j:', meta);
});
Got a row
Got a row
Got a row
Got a row
Got a row
Got a row
Got a row
Got a row
Got a row
Got a row
All rows received. Metadata is {"requestID":"79914eb3-6204-4dc7-b9e6-b4680b6509a0","signature":{"*":"*"},"status":"success","metrics":{"elapsedTime":"8.631682ms","executionTime":"8.593926ms","resultCount":10,"resultSize":3002}}: