Working with view queries

Working with view queries

You can use MapReduce views to create queryable secondary indexes in Couchbase Server.

The primary index for documents is the key you use when performing the standard CRUD methods.

The following example queries a by_name view in a beer design document. This view checks whether a document is a beer and has a name. If it does, it emits the beer's name into the index. This view allows beers to be queried for by name. For example, it's now possible to ask the question "What beers start with A?"

function (doc, meta) {
  if (doc.type && doc.type == "beer" && doc.name) {    
     emit(doc.name, null);
  }
}

Querying a view through the Node.js client is performed through the ViewQuery class that is available as a top-level object.

var couchbase = require('couchbase');
var ViewQuery = couchbase.ViewQuery;

var query = ViewQuery.from('beer', 'by_name');

A ViewQuery object enables you to query the view and specify various available options for the query. Once you have the query ready for execution, pass it to the query method of the your Bucket instance:

var myBucket = myCluster.openBucket();
myBucket.query(query, function(err, results) {
  for(i in results)
    console.log(results[i]);
});

You can modify your view results by specifying various options before executing the query method. Here is an example that skips the first six items and limits the results to three items:

var query = ViewQuery.from('beer', 'by_name').skip(6).limit(3);
myBucket.query(query, function(err, results) {
  for(i in results)
    console.log(results[i]);
});

If you are interested in performing a geospatial view, simply use SpatialQuery as your root rather than ViewQuery.

Note: Geospatial queries are supported only against Couchbase Server 3.0.1 or later and are currently experimental. If going as planned, the next major release will provide stable support. It is not expected that the client API will change, because it is very similar to what is provided against regular views.
var SpatialQuery = couchbase.SpatialQuery;

var query = SpatialQuery.from('designdoc', 'spatialview').limit(10);
myBucket.query(query, function(err, results) {
  for(i in results)
    console.log(results[i]);
});