Start Using the Java SDK

  • tutorial
    +
    A quick start guide to get you up and running with Couchbase and the Java SDK.

    The Couchbase Java client allows applications to access a Couchbase database. It offers synchronous APIs as well as reactive and asynchronous equivalents to maximize flexibility and performance.

    In this guide, you will learn:

    Hello Couchbase

    We will go through the code sample step by step, but for those in a hurry to see it, here it is:

    • Couchbase Capella Sample

    • Local Couchbase Server

    If you are connecting to Couchbase Capella, be sure to get the correct endpoint as well as user, password.

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.kv.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.query.*;
    
    import java.time.Duration;
    
    
    public class StartUsingCloud {
      // Update these variables to point to your Couchbase Capella instance and credentials.
      static String connectionString = "cb.<your-endpoint-here>.cloud.couchbase.com";
      static String username = "username";
      static String password = "Password!123";
      static String bucketName = "travel-sample";
    
      public static void main(String... args) {
        // Simple connection.
        Cluster cluster = Cluster.connect("couchbases://" + connectionString, username, password);
        cluster.disconnect();
    
        // Custom environment connection.
        cluster = Cluster.connect(
                "couchbases://" + connectionString,
                ClusterOptions.clusterOptions(username, password).environment(env -> {
                  // Sets a pre-configured profile called "wan-development" to help avoid latency issues
                  // when accessing Capella from a different Wide Area Network
                  // or Availability Zone (e.g. your laptop).
                  env.applyProfile("wan-development");
                })
        );
    
        // Get a bucket reference
        Bucket bucket = cluster.bucket(bucketName);
        bucket.waitUntilReady(Duration.ofSeconds(10));
    
        // Get a user defined collection reference
        Scope scope = bucket.scope("tenant_agent_00");
        Collection collection = scope.collection("users");
    
        // Upsert Document
        MutationResult upsertResult = collection.upsert(
                "my-document",
                JsonObject.create().put("name", "mike")
        );
    
        // Get Document
        GetResult getResult = collection.get("my-document");
        String name = getResult.contentAsObject().getString("name");
        System.out.println(name); // name == "mike"
    
        // Call the query() method on the scope object and store the result.
        Scope inventoryScope = bucket.scope("inventory");
        QueryResult result = inventoryScope.query("SELECT * FROM airline WHERE id = 10;");
    
        // Return the result rows with the rowsAsObject() method and print to the terminal.
        System.out.println(result.rowsAsObject());
      }
    }

    The Couchbase Capella free trial version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.kv.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.query.*;
    
    import java.time.Duration;
    
    public class StartUsing {
      // Update these variables to point to your Couchbase Server instance and credentials.
      static String connectionString = "localhost";
      static String username = "Administrator";
      static String password = "password";
      static String bucketName = "travel-sample";
    
      public static void main(String... args) {
        // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
        Cluster cluster = Cluster.connect("couchbase://" + connectionString, username, password);
        cluster.disconnect();
    
        // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
        cluster = Cluster.connect(
                "couchbase://" + connectionString,
                ClusterOptions.clusterOptions(username, password).environment(env -> {
                  // Customize client settings by calling methods on the "env" variable.
                })
        );
        
        // get a bucket reference
        Bucket bucket = cluster.bucket(bucketName);
        bucket.waitUntilReady(Duration.ofSeconds(10));
    
        // get a user defined collection reference
        Scope scope = bucket.scope("tenant_agent_00");
        Collection collection = scope.collection("users");
    
        // Upsert Document
        MutationResult upsertResult = collection.upsert(
                "my-document",
                JsonObject.create().put("name", "mike")
        );
    
        // Get Document
        GetResult getResult = collection.get("my-document");
        String name = getResult.contentAsObject().getString("name");
        System.out.println(name); // name == "mike"
    
        // Call the query() method on the scope object and store the result.
        Scope inventoryScope = bucket.scope("inventory");
        QueryResult result = inventoryScope.query("SELECT * FROM airline WHERE id = 10;");
        
        // Return the result rows with the rowsAsObject() method and print to the terminal.
        System.out.println(result.rowsAsObject());
      }
    }

    As well as the Java SDK (see below), and a running instance of Couchbase Server, you will need to load up the Travel Sample Bucket using either the Web interface or the command line.

    Quick Installation

    We recommend running the latest Java LTS version (i.e. at the time of writing JDK 17) with the highest patch version available. Couchbase publishes all stable artifacts to Maven Central.

    The latest version (as of December 2022) is 3.4.1.

    You can use your favorite dependency management tool to install the SDK.

    • Maven

    • Gradle

    <dependencies>
        <dependency>
            <groupId>com.couchbase.client</groupId>
            <artifactId>java-client</artifactId>
            <version>3.4.1</version>
        </dependency>
    </dependencies>
    implementation 'com.couchbase.client:java-client:3.4.1'

    See the installation page for more detailed instructions.

    Prerequisites

    The following code samples assume:

    • Couchbase Capella

    • Local Couchbase Server

    • You have signed up to Couchbase Capella.

    • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically by the Capella free trial.

    • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

    Couchbase Capella uses Roles to control user access to database resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.
    • Couchbase Server is installed and accessible locally.

    • You have created your own bucket, or loaded the Travel Sample dataset using the Web interface.

    • A user is created with permissions to access your cluster (at least Application Access permissions). See Manage Users, Groups and Roles for more details.

    Couchbase Server uses Role Based Access Control (RBAC) to control access to resources. In this guide we suggest using the Full Admin role created during setup of your local Couchbase Server cluster. For production client code, you will want to use more appropriate, restrictive settings.

    Step by Step

    Here are all the imports needed to run the sample code:

    import com.couchbase.client.java.*;
    import com.couchbase.client.java.kv.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.query.*;
    
    import java.time.Duration;

    If you haven’t already, create an empty class and add a main() method.

    public class YourClassName {
        public static void main(String... args) {}
    }

    Make sure to replace YourClassName with your own class name.

    Above the main() method, add the following variables and update them accordingly:

    • Couchbase Capella

    • Local Couchbase Server

    // Update these variables to point to your Couchbase Capella instance and credentials.
    static String connectionString = "cb.<your-endpoint-here>.cloud.couchbase.com";
    static String username = "username";
    static String password = "Password!123";
    static String bucketName = "travel-sample";
    // Update these variables to point to your Couchbase Server instance and credentials.
    static String connectionString = "localhost";
    static String username = "Administrator";
    static String password = "password";
    static String bucketName = "travel-sample";

    In the following sections we will populate the main() method.

    Connect

    Connect to your cluster by calling the Cluster.connect() method and pass it your connection details. The basic connection details that you’ll need are given below — for more background information, see Managing Connections.

    • Couchbase Capella

    • Local Couchbase Server

    // Simple connection.
    Cluster cluster = Cluster.connect("couchbases://" + connectionString, username, password);

    From version 3.3, the Java SDK includes Capella’s standard certificates by default, so you don’t need any additional configuration. You do need to enable TLS, which can be done by simply using couchbases:// in the connection string as in this example.

    Alternatively, you can use a Cluster Environment when you need to customize the client’s behavior (e.g. changing connection timeout settings).

    // Custom environment connection.
    cluster = Cluster.connect(
            "couchbases://" + connectionString,
            ClusterOptions.clusterOptions(username, password).environment(env -> {
              // Sets a pre-configured profile called "wan-development" to help avoid latency issues
              // when accessing Capella from a different Wide Area Network
              // or Availability Zone (e.g. your laptop).
              env.applyProfile("wan-development");
            })
    );

    When accessing Capella from a different Wide Area Network or Availability Zone, you may experience latency issues with the default connection settings. SDK 3.4 introduces a wan-development Configuration Profile, which provides pre-configured timeout settings suitable for working in high latency environments. Basic usage is shown in the example above, but if you want to learn more see Constrained Network Environments.

    The Configuration Profiles feature is currently a Volatile API and may be subject to change.
    // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
    Cluster cluster = Cluster.connect("couchbase://" + connectionString, username, password);

    For developing locally on the same machine as Couchbase Server, your URI can be couchbase://localhost as shown here. For production deployments, you will want to use a secure server, with couchbases://.

    Alternatively, you can use a Cluster Environment when you need to customize the client’s behavior (e.g. changing connection timeout settings).

    // For a secure cluster connection, use `couchbases://<your-cluster-ip>` instead.
    cluster = Cluster.connect(
            "couchbase://" + connectionString,
            ClusterOptions.clusterOptions(username, password).environment(env -> {
              // Customize client settings by calling methods on the "env" variable.
            })
    );

    Following successful authentication, add this code snippet to access your Bucket:

    // Get a bucket reference
    Bucket bucket = cluster.bucket(bucketName);
    bucket.waitUntilReady(Duration.ofSeconds(10));

    Add and Retrieve Documents

    The Java SDK supports full integration with the Collections feature introduced in Couchbase Server 7.0. Collections allow documents to be grouped by purpose or theme, according to a specified Scope.

    Here we refer to the users collection within the tenant_agent_00 scope from the Travel Sample bucket as an example, but you may replace this with your own data.

    // Get a user defined collection reference
    Scope scope = bucket.scope("tenant_agent_00");
    Collection collection = scope.collection("users");

    Data operations, like storing and retrieving documents, can be done using simple methods on the Collection class such as Collection.get() and Collection.upsert().

    Add the following code to create a new document and retrieve it:

    // Upsert Document
    MutationResult upsertResult = collection.upsert(
            "my-document",
            JsonObject.create().put("name", "mike")
    );
    
    // Get Document
    GetResult getResult = collection.get("my-document");
    String name = getResult.contentAsObject().getString("name");
    System.out.println(name); // name == "mike"

    SQL++ Lookup

    Couchbase SQL++ queries can be performed at the Cluster or Scope level by invoking Cluster.query() or Scope.query().

    Cluster level queries require you to specify the fully qualified keyspace each time (e.g. travel-sample.inventory.airline). However, with a Scope level query you only need to specify the Collection name — which in this case is airline:

    // Call the query() method on the scope object and store the result.
    Scope inventoryScope = bucket.scope("inventory");
    QueryResult result = inventoryScope.query("SELECT * FROM airline WHERE id = 10;");
    
    // Return the result rows with the rowsAsObject() method and print to the terminal.
    System.out.println(result.rowsAsObject());

    You can learn more about SQL++ queries on the Query page.

    Execute!

    Now that you’ve completed all the steps, run the example via your IDE or through the command line. You should expect to see the following output:

    mike
    [{"airline":{"country":"United States","iata":"Q5","name":"40-Mile Air","callsign":"MILE-AIR","icao":"MLA","id":10,"type":"airline"}}]

    Next Steps

    Now you’re up and running, try one of the following:

    Additional Resources

    The API reference is generated for each release and the latest can be found here. Older API references are linked from their respective sections in the Release Notes.

    Couchbase welcomes community contributions to the Java SDK. The Java SDK source code is available on GitHub.

    If you are planning to use Spring Data Couchbase, see the notes on version compatibility.

    Troubleshooting