Skip to content

Latest commit

 

History

History
867 lines (628 loc) · 31.6 KB

File metadata and controls

867 lines (628 loc) · 31.6 KB

Hello World

Install, connect, try. A quick start guide to get you up and running with Couchbase and the {name-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 {name-sdk}.

Upsert with Replication set to Majority Durablity:
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.

Tip
This page walks you through a quick installation, and CRUD examples against the Data Service. Elsewhere in this section you can find a fully worked-through hello-world:sample-application.adoc and, for those new to document (NoSQL) databases, our Student Record Tutorial.

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:

Couchbase Capella

If you haven’t already got a cluster set up, the easiest route is to sign up to Couchbase Capella and deploy a free tier cluster. Once the set up is complete, come back to this page. Make a note of the endpoint to connect to, and remember the credentials for the user that you set up.

Self-Managed Couchbase Server

Install Couchbase Server locally, or in your private Cloud:

  • Deployment overview

  • Docker Install

  • Couchbase Autonomous Operator

    • Kubernetes

    • Openshift

  • Cloud Marketplace:

    • AWS Marketplace

    • Azure Marketplace

    • GCP Marketplace

To run the example code below, you will need the username and password of the Administrator user that you create, and the IP address of a minimum of one node in the cluster.

Prerequisites

  • The Java SDK is tested against the LTS versions of Oracle JDK and OpenJDK — see the compatibility docs.

    OpenJDK 21 with HotSpot JVM is recommended.

It is also assumed that:

Couchbase Capella
  • 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 when deploying a Capella free tier cluster.

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

Important
Couchbase Capella uses Roles to control user access to cluster resources. Use the Organization Owner role that is automatically assigned to your account during installation of the Capella cluster. In production, as a best practice and also for data security, it is strongly recommended to set up the users with more granular access roles.
Self-Managed Couchbase Server
  • 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 (with the required Application Access permissions). See Manage Users, Groups and Roles for more details.

Important
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, as a best practice and also for data security, it is strongly recommended to set up the users with more granular access roles.

Installation

At the time of writing JDK 21, it is recommended to run the latest Java LTS version with the highest patch version available. Couchbase publishes all stable artifacts to Maven Central.

The latest version of {sdk_dot_minor}.x is {sdk_current_version}.

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

Maven
<dependencies>
    <dependency>
        <groupId>com.couchbase.client</groupId>
        <artifactId>java-client</artifactId>
        <version>{sdk_current_version}</version>
    </dependency>
</dependencies>
Gradle
implementation 'com.couchbase.client:java-client:{sdk_current_version}'

IDE Plugins

To make the 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 {name_platform} ecosystem, check out the project-docs:third-party-integrations.adoc page.

Grab the Code

If you’re all set up and are in real hurry, take the below code sample and add in your Capella details.

Complete Hello World code sample [Click to open or collapse the listing]
link:devguide:example$java/StartUsingCapella.java[role=include]

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

Tip
There’s a View link to the complete sample code on GitHub above each of the snippets on these SDK pages. A Copy icon is also available that allows you to grab just the displayed snippet.

Connect to your Database

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

Couchbase Capella
link:devguide:example$java/StartUsingCapella.java[role=include]
Self-Managed Couchbase Server
link:devguide:example$java/StartUsing.java[role=include]
link:devguide:example$java/StartUsing.java[role=include]
Cloud Native Gateway (CNG)

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

Read more on the Connections page.

Quarkus

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

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

For a deeper look at connection options, read howtos:managing-connections.adoc.

Tip
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.

Tip
Simpler Connection

There’s also a simpler version of Cluster.connect() for when you don’t need to customize the cluster environment:

link:devguide:example$java/SimpleConnect.java[role=include]

Opening a Bucket

Following successful authentication, open the bucket with:

link:devguide:example$java/StartUsingCapella.java[role=include]

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.

link:devguide:example$java/StartUsingCapella.java[role=include]

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 the howtos:json.adoc page.

link:devguide:example$java/StartUsingCapella.java[role=include]

Insert (Create) and Upsert

insert and upsert both create a new document. The difference is that if the document key already exists, the insert operation fails and displays the DocumentExistsException error. However, the upsert operation succeeds and replaces the content.

Always provide a unique ID as the key, and use a UUID as shown below.

Creating a new document
link:devguide:example$java/StartUsingCapella.java[role=include]

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.

link:devguide:example$java/StartUsingCapella.java[role=include]

Replace (Update) and Overloads

The replace method updates the value of an existing document
link:devguide:example$java/StartUsingCapella.java[role=include]
Caution
While replacing a document, it is a good practice to use optimistic locking. Otherwise, changes could be 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, consider you have two types of documents: customers and invoices. You can put the customer documents in a collection named customers, and the invoice documents in a collection named invoices.

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

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

More details can be found on the Data Model page.

What Next?

Help and Troubleshooting

  • Troubleshooting common network problems.

  • Help forum.

  • Discord channel.

  • Read the error handling page.

  • Get help from Couchbase iQ.

Next Steps

  • Learn more about the Data Service.

  • Discover SQL++ — our SQL-family querying language.

  • Explore some of the third party integrations with Couchbase and the {name_platform} SDK, across the {name_platform} ecosystem.

Next Steps

Now that your setup is up and running, try one of the following:

  • Our Travel Sample Application demonstrates all the basics you need to know.

  • Explore Key Value Operations (CRUD) against a document database.

  • Query with our SQL-based {sqlpp} query language.

  • Try longer-running queries with our Analytics Service.

  • A Full Text Search.

  • Read about which service fits your use case.

Additional Resources

The API reference is generated for every release. The latest can be found here.

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

Troubleshooting

  • Couchbase Server is designed to work in the same WAN or availability zone as the client application. If you are running the SDK on your laptop against a Capella cluster, see further information on:

    • Notes on Constrained Network Environments.

    • Network Requirements.

    • If you have a consumer-grade router which has problems with the DNS-SRV records, review the Troubleshooting Guide.

  • The community forum is a great source of help.

Tip
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.