A newer version of this documentation is available.

View Latest

Install and Start Using the Java SDK with Couchbase Server

The Couchbase Java SDK allows Java applications to access a Couchbase cluster. It offers traditional synchronous APIs as well as scalable asynchronous APIs to maximize performance.

Installing the SDK

At least Java 7 is required — with Java 8 (or above) recommended, since it brings performance enhancements and lambda expressions, which are very convenient when used in an asynchronous context. All newer Java versions are supported (and encouraged), up to and including Java 11.

All stable releases of the Java SDK are primarily distributed through Maven. As a result the dependency can be included easily using your favorite package manager. For Maven itself, it typically looks like this:

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

The java-client dependency will pull in two more transitive dependencies. One is called com.couchbase.client.core-io and is a internal dependency which performs all the underlying tasks like IO and cluster management. The other dependency is RxJava which is both used internally and exposed as a first-class API to the user in order to perform scalable and performant asynchronous, reactive operations.

Information on new features, fixes, known issues as well as information on how to install older release versions is in the release notes. You will also find other install options there, including a zip file which includes all transitive dependencies and Javadocs.

Using the SDK

The code snippet below shows how the Java SDK may be used for some common operations:

import com.couchbase.client.java.*;
import com.couchbase.client.java.document.*;
import com.couchbase.client.java.document.json.*;
import com.couchbase.client.java.query.*;

public class Example {

    public static void main(String... args) throws Exception {

        // Initialize the Connection
        Cluster cluster = CouchbaseCluster.create("localhost");
        cluster.authenticate("username", "password");
        Bucket bucket = cluster.openBucket("bucketname");

        // Create a JSON Document
        JsonObject arthur = JsonObject.create()
            .put("name", "Arthur")
            .put("email", "[email protected]")
            .put("interests", JsonArray.from("Holy Grail", "African Swallows"));

        // Store the Document
        bucket.upsert(JsonDocument.create("u:king_arthur", arthur));

        // Load the Document and print it
        // Prints Content and Metadata of the stored Document
        System.out.println(bucket.get("u:king_arthur"));

        // Create a N1QL Primary Index (but ignore if it exists)
        bucket.bucketManager().createN1qlPrimaryIndex(true, false);

        // Perform a N1QL Query
        N1qlQueryResult result = bucket.query(
            N1qlQuery.parameterized("SELECT name FROM `bucketname` WHERE $1 IN interests",
            JsonArray.from("African Swallows"))
        );

        // Print each found Row
        for (N1qlQueryRow row : result) {
            // Prints {"name":"Arthur"}
            System.out.println(row);
        }
    }
}

Connecting & Disconnecting

Most of the operations performed against Couchbase are done against a Bucket instance. A Bucket reference can be obtained through a Cluster reference which allows you to manage more buckets at the same time and reuse the underlying IO and computation resources efficiently.

To obtain a Cluster the CouchbaseCluster#create method needs to be called. If no arguments are provided it will connect to a cluster listening on localhost. Note that not all nodes of the cluster need to be passed to the method, just a few to allow it to bootstrap itself are enough. We recommend more than one though since if one of the nodes happens to be not available during application startup it still has a chance to try another one and bootstrap properly.

Any Cluster nodes addresses passed in to establish (bootstrap) the connection should be for data (KV) nodes.

To connect to a Couchbase bucket, you must use Couchbase Role-Based Access Control (RBAC). This is fully described in the section Authorization. A username and password for the current user must be specified. Following successful authentication, the bucket can be opened.

Once the SDK has successfully reached one node it will throw your bootstrap list away and replace it with a complete up-to-date list of nodes in the cluster.

Here is how you can create a Cluster reference in a few different ways:

// Connects to localhost
Cluster cluster = CouchbaseCluster.create();

// Connects to a cluster on 10.0.0.1 and tries 10.0.0.2
// if the other one does not respond during bootstrap.
Cluster cluster = CouchbaseCluster.create("10.0.0.1", "10.0.0.2");

If you have an environment with port mapping, such as Couchbase Server and the SDK in separate containers under Kubernetes, see the multi-network configuration note under Managing Connections

Once a Cluster reference is available, you can open Bucket instances and then perform operations on them:

// Connects to localhost
Cluster cluster = CouchbaseCluster.create();

// Authenticates
cluster.authenticate("username", "password");

// Opens the "myTestBucket" bucket
Bucket myTestBucket = cluster.openBucket("myTestBucket");
It is very important that cluster and bucket instances are created during startup and are then reused until the application shuts down. Connection setup is expensive and the SDK is designed to be thread safe and can be efficiently used across all your application threads.

Finally you need to close the buckets and/or disconnect from the Cluster. If a cluster disconnect is issued, all buckets will be automatically closed.

// Just close a single bucket
bucket.close();

// Disconnect and close all buckets
cluster.disconnect();

More information on managing connections including error handling can be found here.

API Reference

Each stable Java SDK version has the Javadocs API reference published. The reference for the latest version can be found here.

Additional Resources

The Couchbase JVM Core module is the common library responsible for all the Couchbase Server interaction — used by both the Java SDK, and the new Scala SDK. It is designed to be quite low level and only exposes a message-oriented API — the API reference is here.

Links to older versions of the API docs can be found on the Release Notes page, and links to the new 3.0 SDK API docs can be found on the 3.0 Release Notes page.

Contributing

Couchbase welcomes community contributions to the Java SDK. The Java SDK source code is available on GitHub. Please see the CONTRIBUTING file for further information.