Couchbase Java Client Library 1.4

The Java client library provides fast and reliable access to documents stored inside your Couchbase Server cluster. It learns about your cluster topology automatically, so you never need to take your application down for configuration changes when your cluster expands.

With JSON documents and Couchbase Server 2.0+ you have new ways to index and query data stored in the cluster. Just load our sample beer dataset and query them depending on your taste! Curious? Follow the instructions underneath or jump into our tutorial.

Step 0: Get a Server

Get & Install Couchbase Server. Come back here when you're done.

Step 1: Get a Client Library

The current stable version is 1.4.0. You can download the library either as a zipfile bundled with all dependencies or use the official Maven central repository:

<dependencies>
  <dependency>
    <groupId>com.couchbase.client</groupId>
    <artifactId>couchbase-client</artifactId>
    <version>1.4.0</version>
  </dependency>
</dependencies>

 

Step 2: Try it out!

If you need to set up the server, you can do with the Couchbase Administrative Console, or Couchbase Command-Line Interface (CLI), or the Couchbase REST-API. For information and instructions, see:

Now that you have installed Couchbase and have probably created a cluster of Couchbase servers, it is time to include the dependencies in your IDE project and write a "Hello World" example. Once Couchbase greets you nicely, we will write a slightly more complex example with Views.

Hello Couchbase

You might be curious what the simplest Java program to talk to Couchbase might look like.

We will create a connection and we will look at some of the operations that the library supports.

import com.couchbase.client.CouchbaseClient;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
 
public class HelloWorld {
 
  public static void main(String[] args) throws Exception {
 
    // (Subset) of nodes in the cluster to establish a connection
    List<URI> hosts = Arrays.asList(
      new URI("http://127.0.0.1:8091/pools")
    );
 
    // Name of the Bucket to connect to
    String bucket = "default";
 
    // Password of the bucket (empty) string if none
    String password = "";
 
    // Connect to the Cluster
    CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);
 
    // Store a Document
    client.set("my-first-document", "Hello Couchbase!").get();
 
    // Retreive the Document and print it
    System.out.println(client.get("my-first-document"));
 
    // Shutting down properly
    client.shutdown();
  }
}

Of course, in the "hosts" list, substitute your own Couchbase server IP address if it runs on a different machine. Either run that file from your IDE or use the command line to compile and run it:

shell> javac -cp couchbase-client-1.4.0.jar:spymemcached-2.11.1.jar \
  HelloWorld.java
 
shell> java -cp .:couchbase-client-1.4.0.jar:spymemcached-2.11.1.jar:\
jettison-1.1.jar:netty-3.5.5.Final.jar:commons-codec-1.5.jar:\
httpcore-4.3.jar:httpcore-nio-4.3.jar HelloWorld

If you are on Linux or Mac OS X replace the semi-colon in the second command-line with a colon.

The program first connects to the cluster, then stores a document with the key "my-first-document" and the value of "Hello Couchbase!". The value can be anything (JSON, serialized Java objects, binary,...), but in this case we just stored a plain string. The "get()" that you see on the "set()" method blocks the future that gets returned. Most operations on the CouchbaseClient object return futures which allow for a very performant and flexible programming model. For some commands (like the get() command underneath) we also provide synchronous methods for convenience.

If everything behaves as expected, you will see "Hello Couchbase!" printed out on the console (amongst some helpful INFO level log output from Couchbase).

Now that we have the basics in place, let's move on and create and query JSON documents through Views.

Storing JSON Documents

The CouchbaseClient does not enforce any JSON encoding/decoding library on you, so you are free to choose your own (like Google GSON or Jackson). If your application is really simple, you could even create the JSON string on your own. Most of the time though, you want to take an entity (maybe just a POJO) and store its JSON representation into Couchbase. When you load the document later, you can create a POJO out of it.

In this quick example, we will use Google GSON, which makes it really easy to marshal documents from and to JSON. You can download Google GSON from the official web page, or fetch it from Maven Central (groupId: "com.google.code.gson", artifactId: "gson", version i.e. "2.2.4").

First, we create a POJO that represents a user (which has a firstname and a lastname).

public class User {
  private final String firstname;
  private final String lastname;
 
  public User(String firstname, String lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  }
 
  public String getFirstname() {
    return firstname;
  }
 
  public String getLastname() {
    return lastname;
  }
}

Now, we can create instances and use Google GSON to generate JSON string representations. This string gets passed as the document value to the "set()" method, which will store it inside our cluster.

// CouchbaseClient client = new CouchbaseClient(...);
Gson gson = new Gson();
 
User user1 = new User("John", "Doe");
User user2 = new User("Matt", "Ingenthron");
User user3 = new User("Michael", "Nitschinger");
 
client.set("user1", gson.toJson(user1)).get();
client.set("user2", gson.toJson(user2)).get();
client.set("user3", gson.toJson(user3)).get();

Jump into the Couchbase UI, select your bucket and find the stored documents. Since we stored valid JSON, you can inspect and modify them directly from the browser.

Querying Views

Querying for a document by its unique key is easy and fast, but if you want to ask questions like "give me all users who have firstnames starting with M" you need to use a different technique. Couchbase Server 2.0+ comes with a rich indexing technique called Views (based on the Map/Reduce concept).

You create an index by defining which documents should go there and Couchbase does the rest for you. Let's try to answer the exact question from above. Go to the UI, click on "Views" and then "Create Development View". Make sure you've selected the right bucket, otherwise you won't see much data afterwards.

You'll learn about the details later, so give it a descriptive design document name like "users" and name the view "by_firstname". Replace the default "map" JavaScript code with the following:

function (doc, meta) {
  if(doc.firstname) {
    emit(doc.firstname, null);
  }
}

Click "save", then go back to the "Views" list and click "Publish" on your design document that you just created. This will publish the view in production, as we say. You can poke around in the UI and query the View there before we go back to the Java code.

Now that our View is saved, we can query it from our SDK. Querying is done in three simple steps as the code shows below:

// 1: Load the View infos
String designDoc = "users";
String viewName = "by_firstname";
View view = client.getView(designDoc, viewName);
 
// 2: Create a Query object to customize the Query
Query query = new Query();
query.setIncludeDocs(true); // Include the full document body
 
// 3: Actually Query the View and return the results
ViewResponse response = client.query(view, query);
 
// 4: Iterate over the Data and print out the full document
for (ViewRow row : response) {
  System.out.println(row.getDocument());
}

Now if you run that code, the console will show the content of all the documents we just stored. That's expected, because we didn't specify a query that narrows down the results. We can work with the "Query" object and tell it to just give us all firstnames that start with "M":

// 2: Create a Query object to customize the Query
Query query = new Query();
query.setIncludeDocs(true); // Include the full document body
query.setRangeStart("M"); // Start with M
query.setRangeEnd("M\\uefff"); // Stop before N starts

If the "\\uefff" character sounds weird, don't worry. Couchbase uses unicode collation for sorting and since this is one of the last characters, not much can come afterwards. This makes sure we end sorting right after "M". You'll pick up all concepts once you start digging deeper into indexing and querying.

Now, if you run the code again you'll see that "John Doe" is not part of the result set. Congratulations, you made the first steps to use Couchbase as a full-fledged document database.

Step 3: Learn More!

The full getting started guide starts from the basics and gets you up and running quickly. From there, move on to the tutorial, which will show how to build a full application on Couchbase Server with a JSON dataset, sample views, and modifying data.