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 synchronous APIs as well as reactive and asynchronous equivalents to maximize flexibility and performance.

    The Couchbase Java SDK 3.x is a complete rewrite of the 2.x API, providing a simpler surface area and adding support for Couchbase Server features like Collections and Scopes (available in Couchbase Server 7.0). The (reactive) API also migrated from RxJava to Reactor, along with other improvements to performance, logging, debugging and timeout troubleshooting. If you’re upgrading your application from Java SDK 2.x, please read our Migrating 2.x code to SDK 3.0 Guide.

    Installing the SDK

    At least Java 8 is required for current releases; see the Compatibility section for details. We recommend running the latest Java LTS version (i.e. at the time of writing JDK 17) with the highest patch version available. Java 17 has various enhancements like sealed classes, pattern matching for switch expressions (in preview), and further updates and improvements on core libraries.

    Couchbase publishes all stable artifacts to Maven Central. The latest version (as of April 2022) is 3.2.7.

    You can use your favorite dependency management tool to install the SDK. The following snippet shows how to do it with Maven.

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

    For Gradle, you can use:

    implementation 'com.couchbase.client:java-client:3.2.7'

    Alternatively, we provide a zip file with all the dependencies bundled if you wish to manually include the jar files in your classpath. Refer to the Release Notes for further details. You can also find links to the hosted javadocs there.

    Hello Couchbase

    Once you have the Java client installed, open your IDE, and try out the following:

    Cluster cluster = Cluster.connect(connectionString, username, password);

    Couchbase uses Role Based Access Control (RBAC) to control access to resources. Here we will use the Full Admin role created during installation of the Couchbase Data Platform. For production client code, you will want to use more appropriate, restrictive settings — but here we want to get you up and running quickly. If you’re developing client code on the same VM or machine as the Couchbase Server, your connection string can be just localhost.

    The Cluster provides access to cluster-level operations like N1Ql queries, analytics or full-text search. You will also find different management APIs on it.

    If you are not using an IDE or are new to Java, the following imports are necessary to build the following snippets:

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

    To access the KV (Key/Value) API or to query views, you need to open a Bucket:

    // get a bucket reference
    Bucket bucket = cluster.bucket(bucketName);

    If you installed the travel-sample data bucket, substitute travel-sample for bucketName.

    The 3.2 SDK supports full integration with the Collections feature in the latest release of the Couchbase Data Platform, Couchbase Server 7.0. This brings complete support of Collections, allowing Documents to be grouped by purpose or theme, according to a specified Scope. Here we will use the users collection within the tenant_agent_00 scope from travel-sample bucket as an example.

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

    KV Operations are described in detail on the KV Operations page, but to get you started the following code creates a new document and then fetches it again, printing the result.

    // 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"

    You can also perform a N1QL query at the cluster level:

    // Call the query() method on the cluster object and store the result.
    QueryResult result = cluster.query("select \"Hello World\" as greeting");
    
    // Return the result rows with the rowsAsObject() method and print to the terminal.
    System.out.println(result.rowsAsObject());

    You can learn more about N1QL queries on the Query page. Other services (like analytics, search or views) work very similar to the two shown above. Please refer to their respective documentation sections to learn more.

    Full Example

    If you want to copy and paste to run the full example, here it is:

    • Local Couchbase Server

    • Couchbase Capella Sample

    /*
     * Copyright (c) 2020 Couchbase, Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *    http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    import com.couchbase.client.java.*;
    import com.couchbase.client.java.kv.*;
    import com.couchbase.client.java.json.*;
    import com.couchbase.client.java.query.*;
    
    public class StartUsing {
    
      static String connectionString = "localhost";
      static String username = "Administrator";
      static String password = "password";
      static String bucketName = "travel-sample";
    
      public static void main(String... args) {
        Cluster cluster = Cluster.connect(connectionString, username, password);
    
        // get a bucket reference
        Bucket bucket = cluster.bucket(bucketName);
    
        // 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 cluster object and store the result.
          QueryResult result = cluster.query("select \"Hello World\" as greeting");
          
          // Return the result rows with the rowsAsObject() method and print to the terminal.
          System.out.println(result.rowsAsObject());
        }
      }
    
    }

    If you are connecting to Couchbase Capella, be sure to get the correct endpoint as well as user, password, and bucket  — and see the Cloud section, below.

    // Update these variables to point to your Couchbase Capella instance and credentials.
    String endpoint = "--your-instance--.dp.cloud.couchbase.com";
    String bucketname = "bucketname";
    String username = "username";
    String password = "password";
    
    String tlsCertificate = "-----BEGIN CERTIFICATE-----\n" +
      "... your certificate content in here ...\n" +
      "-----END CERTIFICATE-----";
    // User Input ends here.
    
    // Configure TLS
    List<X509Certificate> cert = SecurityConfig.decodeCertificates(Collections.singletonList(tlsCertificate));
    SecurityConfig.Builder securityConfig = SecurityConfig
      .enableTls(true) // Enable transport security
      .trustCertificates(cert); // Configure the cloud certificate
      // During development, if you want to trust all certificates you can connect
      // to your cloud like with the InsecureTrustManagerFactory. As the name points
      // out, this is INSECURE!
      // .trustManagerFactory(InsecureTrustManagerFactory.INSTANCE)
    
    // Build the environment with the TLS config
    ClusterEnvironment env = ClusterEnvironment
      .builder()
      .securityConfig(securityConfig)
      .build();
    
    // Initialize the Connection
    Cluster cluster = Cluster.connect(endpoint, ClusterOptions.clusterOptions(username, password).environment(env));
    Bucket bucket = cluster.bucket(bucketname);
    bucket.waitUntilReady(Duration.parse("PT10S")) ;
    Collection collection = bucket.defaultCollection();
    
    // 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
    collection.upsert("u:king_arthur", arthur);
    
    // Load the Document and print it
    // Prints Content and Metadata of the stored Document
    System.out.println(collection.get("u:king_arthur"));
    
    // Create a N1QL Primary Index
    cluster.queryIndexes().createPrimaryIndex(
      bucketname,
      createPrimaryQueryIndexOptions().ignoreIfExists(true)
    );
    
    // Perform a N1QL Query
    QueryResult result = cluster.query(
      "SELECT name FROM " + bucketname + " WHERE $1 IN interests",
      queryOptions()
        .parameters(JsonArray.from("African Swallows"))
        .scanConsistency(QueryScanConsistency.REQUEST_PLUS)
    );
    
    // Print each found Row
    for (JsonObject row : result.rowsAsObject()) {
        System.out.println("Query row: " + row);
    }

    Cloud Connections

    For developing on Capella, if you are not working from the same Availability Zone, refer to 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.