Start Using the SDK
Edit this article in GitHub
Version 2.2

Start Using the SDK

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 Couchbase Server

To install Couchbase Server, pick up the platform download the software and run the installer.

If you are installing Couchbase Server for development, test, or production purposes, set up Couchbase Server by following the detailed [setup instructions] that cover pre-installation, installation on supported platforms, post-installation, upgrading, cloud deployment, and migration.

The SDK-specific installation is explained for each SDK.

Installing the SDK

Important: At least Java 6 is required, all newer Java versions are supported (and encouraged). Especially Java 8 is recommended since it brings performance enhancements and lambda expressions which are very convenient when used in an asynchronous context.

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.3.6</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");
        Bucket bucket = cluster.openBucket("default");

        // Create a JSON Document
        JsonObject arthur = JsonObject.create()
            .put("name", "Arthur")
            .put("email", "kingarthur@couchbase.com")
            .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 default 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 it, 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.

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");

Now that the Cluster reference is available, you can open Bucket instances and then perform operations on them:

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

// Opens the "default" bucket
Bucket defaultBucket = cluster.openBucket();

// Opens the "travel-sample" bucket without password
Bucket tsBucket = cluster.openBucket("travel-sample");

// Opens a bucket with password
Bucket secureBucket = cluster.openBucket("mybucket", "mypassword");
Important: 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.

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.