Getting started with Couchbase-Java

Hello everyone,

In this blog, we will understand how to use the couchbase server with the Java SDK.

Couchbase is not a new term in the market, its there since 2012 January. Couchbase-server is an open-source, distributed multi-model NoSQL document-oriented database software package that is optimized for interactive applications. These applications may serve many concurrent users by creating, storing, retrieving, aggregating, manipulating and presenting data. In support of these kinds of application needs, Couchbase Server is designed to provide easy-to-scale key-value or JSON document access with low latency and high sustained throughput. It is designed to be clustered from a single machine to very large-scale deployments spanning many machines.

As we proceed we shall see how to interact with couchbase document database, create an environment, cluster and other stuff required to run our queries on the database.

Before we start, you can download couchbase-server by clicking: Download Here

After you download the server.deb file follow these steps to get your server up and running:

Installing "couchbaseServer.deb" file on Linux.

Step1: Open up a terminal/commandPrompt and move to the folder containig your downloaded file.

Step2: Check if you have openssl installed on your system issue the following command : openssl version if it is not installed then install it first.

Step3: Run sudo dpkg -i 

Step3 will start couchbase as a service on your system to check if service is installed and working issue the following command: 
- sudo service couchbase-server status
you will see following output:

● couchbase-server.service - Couchbase Server
 Loaded: loaded (/lib/systemd/system/couchbase-server.service; enabled; vendor
 Active: active (running) since Sun 2018-04-08 19:45:28 IST; 2s ago
 Docs: http://docs.couchbase.com

Now that you have installed the couchbase server you can look at its UI  here localhost:8091. Once you provide the username and password to your server you are good to go start creating your buckets on the server.

So let’s get started.

Step1: I’ll be using a Maven project here, and we would need to add the following dependency to our pom.xml to integrate couchbase with our application:

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

Step2: Start with the Default Environment provide by the Couchbase or go ahead and create your own custom Environment, But be cautious Couchbase community advises the users to ensure that only one CouchbaseEnvironment is active in the JVM, since the use of two or more environments may lead to an unpredictable behavior. If you don’t need any fine-tuning of the basic settings just use the DefaultCouchbaseEnvironment and associate that to your cluster by simply issuing the following:

Cluster cluster = CouchbaseCluster.create("127.0.0.1");// here we connect to a single node cluster on our localhost

To connect to a multi-node cluster, we need to specify at least two nodes in case one of them is unavailable when the application attempts to establish the connection, as shown:

Cluster cluster = CouchbaseCluster.create("192.168.254.237","192.168.254.238");//there can be other nodes as well in the cluster but we don't need to pass them all here since the couchbase environment would later on query the cluster on connection establishment to discover the other nodes if present.  

In case you want to create your custom environment use the following configurations and then connect to the cluster using this environment:


CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
.connectTimeout(6000)
.kvTimeout(1000)
.build();

Cluster cluster= CouchbaseCluster.create( env , "127.0.0.1");

Step3: After establishing the connection to the cluster next step is to create a bucket or use an existing bucket, a bucket is your key-value store wherein you store your Documents indexed with a unique id for fast transactions. To open an existing bucket you just need to know the bucket name(a password protected bucket is also available which requires both the bucket name and password to be passed to open the bucket) and issue the following segment:

Bucket bucket = cluster.openBucket("bucket-name");

In case we want to create our own bucket with some custom settings we can do so by:

//Create your bucket.....
BucketSettings sampleBucket = new DefaultBucketSettings.Builder()
.type(BucketType.COUCHBASE)
.name("bucket-name")
.password("")
.quota(200) // megabytes
.replicas(1)
.indexReplicas(true)
.enableFlush(true)
.build();

and then we just need to add our newly created bucket to the cluster we have formed, this could be done with the help of the clusterManager method of Cluster class, as shown below:

cluster.clusterManager("couchbase.cluster.username", "couchbase.cluster.password")
.insertBucket(sampleBucket);

The above statement will insert our sampleBucket into the cluster.

Step4: Now that the Bucket has been inserted we need to store the Documents in the bucket and later we will query directly on those documents, for querying purpose couchbase uses a query language called the non-first normal form query language, N1QL (pronounced nickel) is used for manipulating the JSON data in Couchbase, just like SQL manipulates data in RDBMS. It has SELECT, INSERT, UPDATE, DELETE, MERGE statements to operate on JSON data.

Example:

{
  "email": "anyMail@gmail.com",
  "address": [
    {"city":"ABC"},
    {"city":"DEF"}
  ]
}
Like Query:
SELECT * FROM `sampleBucket` WHERE email LIKE "%@gmail.com";
Array Query:
SELECT * FROM `sampleBucket` WHERE ANY person IN address SATISFIES person.city = "DEF" END;

I hope that this information helps while you start off with couchbase server, for more detailed programming logic you can clone the repository that I have setup for my couchbase implementation.

Clone Me

In case you run into any trouble while dealing with couchbase you can always get in touch with me and I would try to resolve your doubts and issues ASAP. Please feel free to comment your doubts or anything else that you would like to add or want me to introduce in my post.

Thanks for the support. 🙂 🙂

knoldus-advt-sticker

References:

https://developer.couchbase.com/documentation/server/5.1/introduction/intro.html

Written by 

Prashant is a Software Consultant having experience of more than 1.5 years. He is familiar with Object Oriented Programming Paradigms and has worked upon Java and Scala-based technologies. He is a good team player and always eager to learn new and advance concepts in order to expand his horizon and apply them in project development with his existing knowledge. His hobbies include Teaching, Playing Sports, Cooking, watching Sci-Fi movies and travelling with friends.

Leave a Reply

%d bloggers like this: