Couchbase SDK for JAVA
This covers the basic concepts of Couchbase such as creating an environment, connecting to cluster and accessing data bucket.
CouchbaseDB is a NoSQL database which basically a distributed document database with a powerful search engine and in-built operational and analytical capabilities.
Couchbase has a three products, they are
- Couchbase Capella
- Couchbase Server
- Couchbase Lite
In this blog we will see how to connect couchbaseDB from a JAVA application and perform few operations of the documents using Couchbase SDK.
This SDK provides the CouchbaseEnvironment interface and an implementation class DefaultCouchbaseEnvironment containing default settings to manage clusters and buckets. If necessary, we can also configure it depending on our requirement by overriding defaults settings.
Couchbase Java SDK 3.x has a vast upgrade compare to 2.x API, which provides a simpler surface area and also supports the Couchbase Server features like Collections and Scopes which is available from Couchbase Server 7.0. It is recommended to run the application on latest Java LTS version ( i.e., Java 11 or more), but least it will work on Java 8 as well.
We can download the SDK either from couchbase official site. If you are using maven then add the following dependency to your pom.xml
Creating connection to the Cluster with default environment settings
Once the dependency is added to the java project, we can create a connection with the default settings to the cluster by simply providing IP address of one or more nodes.
The following example will connect to a single-node cluster on our local environment
Cluster cluster = Cluster.connect("localhost","username","password");
To connect multiple nodes cluster, we need to specify IP address of the two nodes with coma separated.
Cluster cluster = Cluster.connect("192.168.0.10,192.168.0.20","username","password");
This will ensure if any of the node is down or not accessible then the application will attempt to establish connection with another node.
This is how we will connect to couchbase DB using default settings. Let's see how to connect with custom environment settings.
TimeoutConfig.Builder timeoutConfigBuilder = TimeoutConfig.builder()
ClusterEnvironment env = ClusterEnvironment.builder()
ClusterOptions clusterOptions = ClusterOptions.clusterOptions("username","password")
.environment(env);Cluster cluster = Cluster.connect("localhost",clusterOptions);
In similar way, we can create connection for multiple nodes.
Opening a Bucket
Couchbase DB can have multiple buckets and after creating connection to the cluster we can access all the buckets available in the cluster.
we can also open a bucket by specifying the name of the bucket
Bucket bucket = cluster.bucket("sampleBucket");
In the latest version of couchbase i.e., 7.x and above has a new concept called scope & collection inside the bucket and can connect to them by mentioning the name of scope & collection
// creating connection to scope "automobiles"
Scope automobilesScope = bucket.scope("automobiles");// creating connection to "four_wheelers" collections inside "automobiles" scope
Collection fourWheelerCollection = automobilesScope.collection("four_wheelers);
Performing CRUD operations in Couchbase
So, to create a document in couchbase DB first we need to create a JSONDocument which holds unique id (i.e., primary key) and the content which in the form of JSONObject.
JSONObject instance can be created by the following way
JsonObject data = JsonObject.create()
Using this instance we can insert the created a JSONDocument object. (note: id mentioning below needs to be unique for each document otherwise the old data will be overridden by the latest document. we can use UUID, which is provided by the JAVA by default.)
String id = UUID.randomUUID().toString();
Inserting a Document
Now, this JSONDocument can be added to the bucket by the following command.
MutationResult insertedDocument = fourWheelersCollection.insert(id, data);
The insert method will accept the Object like JsonObject/JsonArray which needs to be inserted and returns the MutationResult object which contains all the properties of the original document and also CAS value that couchbase uses for version tracking. If the document is already exist in the bucket then it will throws DocumentAlreadyExistsException.
Updating or replacing a Document
upsert is another method which will either insert the document if ID is not available or update the document if ID exists.
JsonDocument upsertDocument = bucket.upsert(document);
replace is one more method, which will replace if any document exist with the given ID. If its fails to find the document with given id in the couchbase DB then it throws DocumentDoesNotExistException.
JsonDocument replaceDocument = bucket.replace(document);
Retrieving a Document
To retrieve a document by its id, we use get method which will return document if available other it returns null value.
JsonDocument document = bucket.get(id);
Deleting a Document
To delete a document, we can use remove method.
This method accepts either the document or the id of the document which needs to be deleted and it returns the JsonDocument object which will have only CAS properties set and all other properties will be removed from the returned object.
If the document doesn't exist with the given id, it throws DocumentDoesNotExistException.
These are the basic concepts of Couchbase Java SDK i.e., connecting to DB and performing CRUD operations. Example code can be found in GitHub project.
You can explore more about the Couchbase SDK Couchbase SDK documentation site.