Working With View Queries

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

The Couchbase .NET SDK offers access to all features of the Couchbase View API. Note that before working with the API, a design document and View must exist on the Couchbase Server you are targeting.

For these examples, we will use the design documents and views that come with the Beer-Sample sample bucket that can be installed directly from the Couchbase Management Console. To do so, navigate to the console, log in and select the “Settings” tab. Once you have done this, select the “Sample Buckets” menu item and finally check the “beer-sample” checkbox under “Available” Samples:

Once you have the “beer-sample” sample data and bucket installed, we can run some queries. The beer-sample comes with a design document called “beer” and two views: “brewery_beers”, “by_country” and “by_location” defined. We will use these in the next several examples.

First a very simple query which fetches the results of the “brewery_beers” view. The view definition looks like this:

brewery_beers View

 function(doc, meta) {
   switch(doc.type) {
    case "brewery":
     emit([meta.id]);
     break;
   case "beer":
    if (doc.brewery_id) {
     emit([doc.brewery_id, meta.id]);
    }
    break;
  }
 }
   

What this does is create secondary indexes for every document with a type of “brewery” and a composite index for every document of type “beer”. When this map function is run, it will return a list of all of these keys. Here is an example of querying this View using the Couchbase .NET SDK:


 var query = bucket.CreateQuery(false).
     DesignDoc("beer").
     View("brewery_beers").
     Limit(5);

 var result = bucket.Query<dynamic>(query);
 foreach (var row in result.Rows)
 {
    Console.WriteLine(row);
 }
   

First, a IViewQuery object is created by calling the Factory method, CreateQuery, and passing in false to indicate that we want to target a production View. Then we are specifying the design document to use and the View on that design document that we want to query and specifying that we only want to return five (5) rows. We then use the Cluster.Query(...) method to execute the query and then iterate through the results.

Notice that the IViewQuery is fluent-interface which allows a series of methods to be chained together. Internally, it’s creating the HTTP request URL that will be sent the server and executed. Besides the methods defined in the query above, which are the minimal set of methods you must call to make a query, there are several others, below is a table with select methods*:

Name Description
From Specify the bucket and the design_doc to query.
Bucket Specify the bucket to query
DesignDoc Specify the design doc to query
View Specify the view to query
Skip The number of records to skip
Stale Whether or not to return stale data or force an index: StaleMode.False | Ok | UpdateAfter
Asc Sort in asc order by key
Desc Sort in desc order by key
Group Groups the results from the reduce function into a single row
GroupLevel Specify the level of grouping to use
Limit The max number of rows to return
Reduce True to use the reduce method
ConnectionTimeout The number of seconds to wait before timing out a request
RawUri Returns the internally created HTTP request URL
*A full list of methods, parameters they take and their return types can be found in the API documentation.

The IBucket.Query(..) method returns an object implementing the IViewResul<T> interface. This interface has the following members:

Name Description
Error The error message returned by the View engine
Message If the query failed as the result of a server error, a message indicating the reason why
Rows A List<T> of T, which is the result of the query
Success true if the query completed successfully
StatusCode The HTTP status code returned by the server
TotalRows The total rows available; may not match the exact rows returned if Limit is called.

You can iterate over the Rows property if the query was successful or check the Message and Error properties if Success returns false to determine the reason why the query failed.