Hello World | Couchbase Docs (original) (raw)

Install, connect, try. A quick start guide to get you up and running with Couchbase and the Java SDK.

Couchbase has a simple interface for creating and modifying records in a document, based upon the collection into which the documents are organized. You can read more about data modeling below, but first let’s look at those data operations, and installing the Java SDK.

collection.upsert("my-document", JsonObject.create().put("doc", true),
    upsertOptions().durability(DurabilityLevel.MAJORITY));

upsert inserts (creates) the document if it does not exist, or replaces it if it does. We’ll explore creating and retrieving data records in more detail below(and touch lightly upon a little of Java’s functional programming approach as we go), after walking through a quick installation.

Before You Start

Couchbase Capella, our Database-as-a-Service, lets you get on with what matters, while we take care of the administration for you. Alternately, if you need to control every aspect of deployment — or just want to run the Server in a VM on your laptop — there are several self-managed options available:

Prerequisites

The code examples also assume:

| | Couchbase Capella uses Roles to control user access to cluster 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 production, Couchbase strongly recommends setting up users with more granular access roles as a best practice for data security. | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| | Couchbase Server uses Role-Based Access Control (RBAC) to control access to cluster resources. In this guide we suggest using the Full Admin role created during setup of your local Couchbase Server cluster. In production, Couchbase strongly recommends setting up users with more granular access roles as a best practice for data security. | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Installation

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

The latest version of 3.8.x is 3.8.2.

More details of the installation process are in thefull installation guide. In most cases, given the above prerequisites, use your favorite dependency management tool to install the SDK.

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

IDE Plugins

To make development easier, Couchbase plugins are available for VSCode and the IntelliJ family of IDEs and editors. For links and more information on these and other integrations across the Java ecosystem, check out the 3rd Party Integrations page.

Grab the Code

If you’re all set up and in a real hurry, just grab this code sample and add in your Capella details.

Complete Hello World code sample [Click to open or collapse the listing]

/*

// tag::imports[] import com.couchbase.client.java.Cluster; import com.couchbase.client.java.ClusterOptions; import com.couchbase.client.java.env.ClusterEnvironment; import com.couchbase.client.java.env.SecurityConfig; import com.couchbase.client.java.json.JsonObject; import com.couchbase.client.java.kv.GetResult; import com.couchbase.client.java.kv.ReplaceOptions;

import java.time.Duration; import java.util.UUID; // end::imports[]

public class Cloud { public static void main(String[] args) { // tag::connect[] // Update this to your cluster String endpoint = "cb..cloud.couchbase.com"; String username = "username"; String password = "Password!123"; String bucketName = "travel-sample";

    ClusterEnvironment env = ClusterEnvironment.builder()
        .securityConfig(SecurityConfig.enableTls(true))
        // 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).
        .applyProfile(ClusterEnvironment.WanDevelopmentProfile.INSTANCE)
        .build();

    Cluster cluster = Cluster.connect(
        "couchbases://" + endpoint,
        ClusterOptions.clusterOptions(username, password).environment(env)
    );
    // end::connect[]

    // tag::bucket[]
    var bucket = cluster.bucket(bucketName);
    bucket.waitUntilReady(Duration.ofSeconds(30));
    // end::bucket[]

    // tag::collection[]
    var collection = bucket.scope("inventory").collection("airport");
    // end::collection[]

    // tag::json[]
    JsonObject json = JsonObject.create().put("status", "awesome");
    // end::json[]

    // tag::upsert[]
    String docId = UUID.randomUUID().toString();
    try {
        collection.upsert(docId, json);
    } catch (CouchbaseException e) {
        System.err.println("Error: " + e.getMessage());
    }
    // end::upsert[]

    // tag::get[]
    // Get a document
    try {
        GetResult result = collection.get(docId);
        JsonObject content = result.contentAsObject();
        String status = content.getString("status");
        System.out.println("Couchbase is " + status);
    } catch (Exception e) {
        System.err.println("Error getting document: " + e.getMessage());
    }
    // end::get[]

    // tag::get-for[]
    try {
        String status = collection.get(docId)
            .contentAsObject()
            .getString("status");
        System.out.println("Couchbase is " + status);
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    // end::get-for[]

    // tag::replace-options[]
    try {
        collection.replace(
            docId,
            json,
            ReplaceOptions.replaceOptions()
                .expiry(Duration.ofSeconds(10))
                .durability(com.couchbase.client.java.kv.Durability.MAJORITY)
        );
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    // end::replace-options[]

    // tag::replace-named[]
    try {
        collection.replace(
            docId,
            json,
            ReplaceOptions.replaceOptions()
                .durability(com.couchbase.client.java.kv.Durability.MAJORITY)
        );
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    // end::replace-named[]
}

}

Otherwise, read on as we introduce the CRUD API and connection to Capella or self-managed Couchbase Server.

| | There’s a View link to the complete sample code on GitHub above each of the snippets on these SDK pages, and a Copy icon to grab just the snippet shown. | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Connect to your Database

Connect to your Couchbase Capella operational cluster (or your local Couchbase Cluster, if you are trying out self-managed Couchbase).

// Update this to your cluster
String endpoint = "cb.<your-endpoint>.cloud.couchbase.com";
String username = "username";
String password = "Password!123";
String bucketName = "travel-sample";

ClusterEnvironment env = ClusterEnvironment.builder()
    .securityConfig(SecurityConfig.enableTls(true))
    // 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).
    .applyProfile(ClusterEnvironment.WanDevelopmentProfile.INSTANCE)
    .build();

Cluster cluster = Cluster.connect(
    "couchbases://" + endpoint,
    ClusterOptions.clusterOptions(username, password).environment(env)
);
// Update these variables to point to your Couchbase Server instance and credentials.
static String connectionString = "couchbase://127.0.0.1";
static String username = "Administrator";
static String password = "password";
static String bucketName = "travel-sample";
// Use the following code to connect to your cluster.
Cluster cluster = Cluster.connect(
    connectionString,
    ClusterOptions.clusterOptions(username, password).environment(env -> {
      // Customize client settings by calling methods on the "env" variable.
    })
);

Couchbase’s large number of ports across the URLs of many services can be proxied by using a couchbase2:// endpoint as the connection string — currently only compatible with recent versions of Couchbase Autonomous Operator:

Cluster cluster = Cluster.connect(
  "couchbase2://10.12.14.16",
  ClusterOptions
    .create(username, password)
    .environment(env)
)

Our Couchbase Quarkus Java Extension docs cover installing and connecting with the Quarkus extension in detail, but if you already have Quarkus installed and a project ready (with quarkus-couchbase in your pom.xml or build.gradle), then your src/main/resources/application.properties file needs to contain:

quarkus.couchbase.connection-string=localhost
quarkus.couchbase.username=username
quarkus.couchbase.password=password

| | The connection code for getting started uses the Administrator password that you were given during set up. In any production app you should create a role restricted to the permissions needed for your app — more on this in the Security documentation. | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

The ClusterEnvironment.Builder is covered more fully on the Client Settings page.

| | Simpler Connection There’s also a simpler version of Cluster.connect() for when you don’t need to customize the cluster environment: // Alternatively, connect without customizing the cluster envionrment. Cluster cluster = Cluster.connect(connectionString, username, password); | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Opening a Bucket

Following successful authentication, open the bucket with:

var bucket = cluster.bucket(bucketName);
bucket.waitUntilReady(Duration.ofSeconds(30));

waitUntilReady is an optional call, but it is good practice to use it. Opening resources such as buckets is asynchronous — that is, the cluster.bucket call returns immediately and proceeds in the background.waitUntilReady ensures that the bucket resource is fully loaded before proceeding. If not present, then the first key-value (KV) operation on the bucket will wait for it to be ready. As with the earlier Cluster.connect, we use .get on the result here for simplicity.

Collections allow documents to be grouped by purpose or theme, according to a specified scope — see data modeling, below. Here we will use the airport collection within the inventory scope from travel-sample bucket as an example.

var collection = bucket.scope("inventory").collection("airport");

Create, Read, Update, Delete

Couchbase documents are organized into buckets, scopes, and collections.CRUD operations — Create, Read, Update, Delete — can be performed upon documents in a collection.

JSON

We’ll create a snippet of JSON to work with, using the client’s own JSON library, but you can read about the Scala SDK’s support for other JSON libraries on theJSON Modelling page.

JsonObject json = JsonObject.create().put("status", "awesome");

Insert (Create) and Upsert

insert and upsert will both create a new document. The difference between the two is that if a document with that key already exists, the insert operation will fail, while the upsert operation will succeed, replacing the content.

We need to provide a unique ID as the key, and we’ll use a UUID here:

Creating a new document

String docId = UUID.randomUUID().toString();
try {
    collection.upsert(docId, json);
} catch (CouchbaseException e) {
    System.err.println("Error: " + e.getMessage());
}

Get (Read)

The get method reads a document from a collection.

Wrapping the method in a Try / Catch is a good way to handle exceptions:

// Get a document
try {
    GetResult result = collection.get(docId);
    JsonObject content = result.contentAsObject();
    String status = content.getString("status");
    System.out.println("Couchbase is " + status);
} catch (Exception e) {
    System.err.println("Error getting document: " + e.getMessage());
}

Replace (Update) and Overloads

The replace method updates the value of an existing document

try {
    collection.replace(
        docId,
        json,
        ReplaceOptions.replaceOptions()
            .expiry(Duration.ofSeconds(10))
            .durability(com.couchbase.client.java.kv.Durability.MAJORITY)
    );
} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
}

| | When you replace a document, it’s usually good practice to use optimistic locking. Otherwise, changes might get lost if two people change the same document at the same time. | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Remove (Delete)

The remove method deletes a document from a collection:

try {
  collection.remove("my-document");
} catch (DocumentNotFoundException ex) {
  System.out.println("Document did not exist when trying to remove");
}

Like replace, remove also optionally takes the CAS value if you want to make sure you are only removing the document if it hasn’t changed since you last fetched it.

Data Modeling

Documents are organized into collections — collections of documents that belong together. You get to decide what it means to "belong." Developers usually put documents of the same type in the same collection.

For example, imagine you have two types of documents: customers and invoices. You could put the customer documents in a collection called customers, and the invoice documents in a collection called invoices.

Each document belongs to exactly one collection. A document’s ID is unique within the collection.

Different scopes can hold collections with different names. There is no relationship between collections in different scopes. Each collection belongs to just one scope and a collection’s name is unique within the scope.

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.

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

Troubleshooting

| | Connecting to Cloud Native Gateway, for Kubernetes or OpenShift Couchbase’s large number of ports across the URLs of many services can be proxied by using a couchbase2:// endpoint as the connection string — read more on the Connections page. | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |