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 examples query 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?" Here's the JavaScript code for the view function:

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

Querying a view through the PHP client is performed through the CouchbaseViewQuery class that is available as a top-level object.

$query = CouchbaseViewQuery::from('beer', 'by_name');

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

$myBucket = $myCluster->openBucket();
$res = $myBucket->query($query);

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

$query = CouchbaseViewQuery::from('beer', 'by_name')->skip(6)->limit(3);
$myBucket->query($query);