Couchbase Java SDK – Introduction

Table of contents
Reading Time: 2 minutes

Couchbase Java SDK provides synchronous as well as asynchronous interfaces that make your application to interact with the Couchbase Cluster efficiently.
So, in this blog, we will look into the various aspects like how we can manage the connection to a cluster and how we can configure the environment, CRUD operations related to document.

Wait!!  ✋ you must know some BASICS before reading this blog.

Just check it out here  ¯\_(ツ)_/¯  Couchbase – Lets Get Started

Install Couchbase Java SDK
Add the following dependency in your pom.xml



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>2.5.4</version>
</dependency>
view raw

gistfile1.txt

hosted with ❤ by GitHub

Now, this dependency will pull more two transitive dependencies – One which is meant for performing tasks like IO and management of cluster and another one is RxJava which perform asynchronous operations using Observable (for getting started with RxJava, you can refer my blog Getting Started with RxJava).

Managing Connection
Managing connection is a multi-step process which includes the following:
1) Initialising Couchbase Cluster
2) Cluster Authentication
3) Opening of Bucket

All the above operation can be done synchronously as well as asynchronously.
We can connect to a Cluster with a Default environment by simply initializing the CouchbaseCluster and just provide one or more nodes in the cluster followed by the authentication of the cluster



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


//Connecting Synchronously
Cluster cluster = CouchbaseCluster.create("node1");
cluster.authenticate("username","password");
Bucket bucket = cluster.openBucket("bucketname");
//Connecting Asynchronously
AsyncCluster cluster = CouchbaseAsyncCluster.create("node1")
Observable<AsyncBucket> bucket = cluster.openBucket("bucketname")
view raw

gistfile1.txt

hosted with ❤ by GitHub

But, what if you want to switch from sync to async operations. what I mean to say is that you are connecting to the bucket synchronously and then want to switch from sync to async operation, then you can do in the following manner



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


Cluster cluster = CouchbaseCluster.create("node1");
cluster.authenticate("username","password");
Bucket bucket = cluster.openBucket("bucketname");
AsyncBucket asyncBucket = bucket.async();
view raw

gistfile1.txt

hosted with ❤ by GitHub

Configuring the Environment

We can also customize the settings provided by DefaultCouchbaseEnvironment in the following manner.



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


CouchbaseEnvironment couchbaseEnvironment = DefaultCouchbaseEnvironment.builder()
.connectTimeout(50000)
.kvTimeout(50000)
.build();
cluster = CouchbaseCluster.create(couchbaseEnvironment, "node1");
view raw

gistfile1.txt

hosted with ❤ by GitHub

here in the above example, I have updated the connectTimeout and kvtimeout.  More configuration options can be found here

Document Operations

As Couchbase deals with a bucket which store documents having unique ID known as document Id. So, in this part, we will see different operations provided by Couchbase Java SDK.
So, let’s take a simple example. We will be performing CRUD with the following JSON document.

{
“empId” : “1”,
“empName” : “ABC”
}

1) Fetching the document

We can simply fetch the document by the documentId



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


//documentId is the unique Id
JsonDocument jsonDocument = bucket.get(documentId)
view raw

gistfile1.txt

hosted with ❤ by GitHub

2) Inserting the document



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


//create JSONObject containing employee details
JsonObject jsonObject = JsonObject.create()
.put("emplId", "1")
.put("empName", "ABC");
//create JSONDocument object containing Id and the content(employee details)
JsonDocument jsonDocument = JsonDocument.create(id, jsonObject);
//Add document to the bucket using insert method
JsonDocument doc = bucket.insert(jsonDocument);
view raw

gistfile1.txt

hosted with ❤ by GitHub

So, in the above example, we are creating JSON Document that requires one string value that is document ID and the content and then inserting the jsonDocument in Couchbase using insert Method. But what if the document already exists in the Couchbase, it will throw an exception like DocumentAlreadyExistsException.

3) Updating the document



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


JsonDocument doc = bucket.upsert(newDocument);
view raw

gistfile1.txt

hosted with ❤ by GitHub

A document can be updated using upsert method. It will simply update the document when the document exists in Couchbase, otherwise will create a new document.
And replace method can also be used to update the document and even it will throw a DocumentDoesNotExistException exception if that particular document does not exist.

4) Removing the document



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


JsonDocument removed = bucket.remove(documentId);
view raw

gistfile1.txt

hosted with ❤ by GitHub

In the above example, the remove method accepts document Id.

Conclusion

I hope now you are pretty much clear with the Couchbase basics and how can we interact with the Couchbase by the application.
Hope this is helpful. Please feel free to provide your suggestion 🙂

References:

  1. https://developer.couchbase.com
  2. Baeldung.com

Knoldus-Scala-Spark-Services