Couchbase Java SDK Tutorial – CRUD Operations

In this blog, we will learn to implement CRUD operations in Couchbase with a Java application.

So, let’s begin with a quick introduction of the Couchbase Server.

Introduction to Couchbase

Couchbase Server is an open source, distributed, NoSQL document-oriented engagement database with many advantages over traditional RDBMS like:-

  • Fast key-value store with managed cache for sub-millisecond data operations.
  • Purpose-built indexers for fast queries.
  • A powerful query engine for executing SQL-like queries.
  • Can run natively on-device and manages synchronization to the server.
  • Provide low-latency data management.

It is a document database at its core, as it stores keys and values as JSON documents(if they are valid JSON).

Here’s a comparison of how data is stored in RDBMS vs. Document Oriented Database.

For more information, See: Couchbase Documentation

Enough introduction? So let’s proceed with how to interact with the Couchbase Server to perform the basic CRUD operations on the Couchbase documents & buckets.

Install and Setup Couchbase Java SDK

Add a Couchbase Java Client

To perform CRUD operations through Java, A couchbase java client is required which can be added with the following dependency-

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

Establish a connection to the Couchbase Server

Start a Server with default configuration.

final Cluster cluster = CouchbaseCluster.create();

Start a server on a given node.

final Cluster cluster = CouchbaseCluster.create(“127.10.10.20”);

Start a server with a given environment.

final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
           .builder().connectTimeout(10000)
           .retryStrategy(FailFastRetryStrategy.INSTANCE)
           .build();

final Cluster cluster = CouchbaseCluster.create(env);

Cluster Authentication

This is an important step, as skipping this would require us to authenticate each bucket individually.

cluster.authenticate(“Administrator”, “password”);

These are the default credentials for Couchbase.

Open a Bucket to use

This bucket will be used for all the CRUD operations.

Bucket bucket = cluster.openBucket(“sample-bucket”);

Opens the bucket with the given name, And, If the bucket doesn’t exist already, you will get BucketDoesNotExistException.
However, if you want to create a bucket, you can also create one. See CRUD Operations for Couchbase Buckets.

Disconnecting from the Couchbase Server

You need to make sure to disconnect properly from the cluster to free all resources when your application shuts down.

cluster.disconnect();

Using the SDK: CRUD Operations for Couchbase Documents

We will be using JsonDocument to perform basic CRUD operations with Couchbase Server and Java SDK, as the SDK comes with built-in handling for JSON documents.

JsonDocument is a public class in Couchbase Java Client and one of the most integral parts of the API. It is intended to be used as a canonical wrapper around retrieval and mutation operations, abstracting away JSON internals.

Create Document

A documentId is the unique identifier for the document.

final String documentId = “user-doc”;

JsonObject user = JsonObject.create()
               .put(“firstname”, “Neha”)
               .put(“lastname”, “Bhardwaj”)
               .put(“job”, “Software Consultant”);

JsonDocument document = JsonDocument.create(documentId, user);

Insert Document

bucket.insert(document);

Be careful, An attempt to insert a document that is already present in the bucket will result in DocumentAlreadyExistsException.

Update Document

Create a new JsonObject or modify an existing one to update the document.

Here, we are modifying an existing user.

JsonObject updatedUser = user
               .put(“location”, “Delhi”)
               .putNull(“salary”)
               .removeKey(“job”);

Use the documentId of the Document to be updated.

bucket.upsert(JsonDocument.create(documentId, updatedUser));

If you care about concurrent updates, use replace() instead.

See more: https://developer.couchbase.com/documentation/server/3.x/developer/java-2.0/documents-updating.html

Delete Document

Remove the document from the bucket.

bucket.remove(documentId);

Retrieve Documents

JsonDocument resultantDocument = bucket.get(documentId);

You can use this JsonDocument for retrieving values further from the resultant JSON.

String firstname = resultantDocument.content().getString(“firstname”);

Using the SDK: CRUD Operations for Couchbase Buckets

Create Bucket

BucketSettings sampleBucket = new DefaultBucketSettings.Builder()
        .type(BucketType.COUCHBASE)
        .name("new-bucket")
        .port(0)
        .quota(100) // megabytes
        .replicas(1)
        .indexReplicas(true)
        .enableFlush(true)
        .build();

This will create a new bucket with the given properties. You can customize the bucket settings as required. But this bucket is not added to the cluster yet. So, let’s insert the newly created bucket into the cluster with the next step.

Insert Bucket

cluster.clusterManager(USERNAME,PASSWORD).insertBucket(sampleBucket);

Also, if you want to provide a timeout while inserting the bucket, you can do this by-

cluster.clusterManager(USERNAME, PASSWORD).insertBucket(sampleBucket, 10000, TimeUnit.MILLISECONDS);

You may encounter ​BucketAlreadyExists Exception If a bucket with the same name already exists.

Read/Open Bucket

To use any bucket, we must open it first with the following step-

Bucket bucket = cluster.openBucket(BUCKET_NAME);

//Using the bucket to insert a new JsonDocument.
bucket.insert(JsonDocument.create("document-id"));

Delete Bucket

cluster.clusterManager().removeBucket(BUCKET_NAME);

This was all about the basic CRUD in couchbase, however, we can do much more like querying documents using the Couchbase Java SDK, but we’ll cover that in the upcoming blog.

Hope this is helpful for you, Please feel free to comment for any queries.

Thank you.

References


knoldus-advt-sticker

 

Written by 

Neha is a Software Consultant having experience of more than 1.5 years . She is a Java enthusiast and has the knowledge of various programming languages. She is familiar with Object Oriented Programming Paradigms. She is always eager to learn new and advance concepts in order to expand her horizon and apply them in project development with her existing knowledge.Her hobbies include Coding , Writing technical blogs , Watching Reality Shows in spare time.

Leave a Reply

%d bloggers like this: