Using views from an application

Using views from an application

When you develop a new application using views, you sometimes need to create a view dynamically from your code. For example you may need this when you install your application, when you write a test, or when you are building a framework and want to create views and query data from the framework. This sections describes you how to do it. When you do the initial server setup , make sure you install the beer sample data set .

For more information about using views from the Java SDK, see Tug’s Blog .

The first thing we do in our application is to connect to the cluster from our Couchbase client. As a best practice we typically provide a list of URIs to different nodes in the cluster in case the initial node we try to connect to is unavailable. By doing so we can attempt another initial connection to the cluster at another node:

import com.couchbase.client.CouchbaseClient;

    List<uri> uris = new LinkedList<uri>();

    uris.add(URI.create("http://127.0.0.1:8091/pools"));

    CouchbaseClient client = null;

    try {

        client = new CouchbaseClient(uris, "beer-sample", "");


        // put your code here
        client.shutdown();
    } catch (Exception e) {
        System.err.println("Error connecting to Couchbase: " + e.getMessage());
        System.exit(0);
    }


</uri></uri>

Here we create a list of URIs to different nodes of the cluster; for the sake of convenience we are working with a single node cluster. Then we connect to our bucket, which in this case is beer-sample .

Creating View Functions with an SDK

Couchbase SDKs provide all the methods you need to save, index, and query views. Imagine we want to get all the beer names out of our sample database. In this case, our map function would appear as follows:

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

At first, we import the Java SDK libraries that we need to work with views. Then we can create a design document based on the DesignDocument class and also create our view as an instance of the ViewDesign class:

import com.couchbase.client.protocol.views.DesignDocument;
import com.couchbase.client.protocol.views.ViewDesign;

    DesignDocument designDoc = new DesignDocument("dev_beer");

    String viewName = "by_name";
    String mapFunction =
            "function (doc, meta) {\n" +
            "  if(doc.type && doc.type == \"beer\") {\n" +
            "    emit(doc.name);\n" +
            "  }\n" +
            "}";

    ViewDesign viewDesign = new ViewDesign(viewName,mapFunction);
    designDoc.getViews().add(viewDesign);
    client.createDesignDoc( designDoc );

In this case we create a design document named dev_beer , name our actual view by_name , and store the map function in a String. We then create a new view provide the constructor the name and function. Finally we add this view to our design document and store it to Couchbase Server with createDesignDoc .

Querying View from SDKs

At this point you can index and query your view. Be aware that when you first create a view, whether this in Couchbase Web Console, or via an SDK, the view is in development mode. You need to put the into production mode in order to query it:

import import com.couchbase.client.protocol.views.*;

System.setProperty("viewmode", "development"); // before the connection to Couchbase

// Create connection if needed

View view = client.getView("beer", "by_name");
Query query = new Query();
query.setIncludeDocs(true).setLimit(20);
query.setStale( Stale.FALSE );
ViewResponse result = client.query(view, query);

for(ViewRow row : result) {
  row.getDocument(); // deal with the document/data
}

Before we create a Couchbase client instance and connect to the server, we set a system property viewmode to development to put the view into production mode. Then we query our view and limit the number of documents returned to 20 items. Finally when we query our view we set the stale parameter to FALSE to indicate we want to re-index and include any new or updated beers in Couchbase. For more information about the stale parameter and index updates, see Index updates and the stale parameter .

The last part of this code sample is a loop we use to iterate through each item in the result set. You can provide any code for handling or outputting individual results here.