Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Couchbase

You're reading from  Learning Couchbase

Product type Book
Published in Nov 2015
Publisher
ISBN-13 9781785288593
Pages 248 pages
Edition 1st Edition
Languages
Author (1):
Henry Potsangbam Henry Potsangbam
Profile icon Henry Potsangbam

Table of Contents (12) Chapters

Introduction to Couchbase The Couchbase Administration Interface Storing Documents in Couchbase Using Buckets Designing a Document for Couchbase Introducing Client SDK Retrieving Documents without Keys Using Views Understanding SQL-Like Queries – N1QL Full Text Search Using ElasticSearch Data Replication and Compaction Administration, Tuning, and Monitoring Case Study – An E-Commerce Application Index

Chapter 5. Introducing Client SDK

In this chapter, we will provide an overview of the various client APIs that connect to Couchbase. Conceptually, we will understand the various methods that are available for interacting with Couchbase. These are applicable to most client APIs irrespective of the programming language you choose to develop your applications. Finally, we will introduce APIs specific to Java SDK 2.1. This chapter will also explain the concept behind counters and locking mechanisms that are provided by the Couchbase SDK APIs. Next, you will learn about the features that are used to connect asynchronously and working with the Observable class. We can also use this feature to determine the presence of a specific document in the Couchbase storage, asynchronously. Finally, towards the end of the chapter, we will discuss connection management provided by the client SDK.

By the end of this chapter, you will be able to write applications that connect to Couchbase and perform various...

A Couchbase SDK overview


So far, in the previous chapters, we have understood how to create buckets and store documents in them using the bucket editor via the web admin console. We have also discussed some of the guidelines used for designing document-based database systems.

What if we need to connect and perform operations on the Couchbase cluster from an application? This can be achieved using the Couchbase client libraries, which are also collectively known as Couchbase Software Development Kit (SDK). The Couchbase SDK APIs are language dependent. The concepts remain the same and are applicable to all languages that are supported by the SDK. However, there are some features such as thread safe, asynchronous operations, and so on that are language dependent. For example, thread safe features are tested and certified for Java SDK and .NET SDK, version 1.0 and above.

You can refer to the Couchbase website (http://docs.couchbase.com/developer/dev-guide-3.0/thread-safety.html) for further details...

Understanding write operation in the Couchbase cluster


Let's see how the write operation works in the Couchbase cluster. When a write command is issued using the set operation in the Couchbase cluster, the server immediately responds once the document is written to the memory of that particular node. How do clients know which nodes in the cluster will be responsible for storing the document? You might recall that every operation requires a document ID, using this document ID, the hash algorithm determines the vBucket in which it belongs. Then, this vBucket is used to determine the node that will store the document. All mapping information, vBucket to node, is stored in each of the Couchbase client SDKs, which form the cluster map. The Couchbase client library polls cluster to update the cluster map information all the time.

After the node has responded to the write operation, the Couchbase node puts a copy of the document in the disk queue to flush the document to the disk for durability...

Understanding the Couchbase API


Any database operation usually falls under one of the four categories of CRUD (Create, Read, Update, and Delete). What is CRUD really about? Whenever we develop an application that requires some information to be stored at the backend, before performing any activity we need to store the data, which is the primary role of any database. This is represented by C to signify creation of record in the database. Then, we fetch data for manipulating or displaying, which is represented by R to signify a read operation. Sometimes, we need to update or delete data after it is stored in the database, that is, U and D signify the update and delete operations, respectively. Most databases provide these basic operational features. Couchbase also provides these with different operation names.

CRUD operations using the Couchbase API

Let me introduce some operations and their different forms provided by Couchbase for performing CRUD operations. These are abstract methods. The...

Understanding Java SDK


We discussed the various APIs provided by the Couchbase SDK for connecting to the Couchbase server and performing operations on it. Let's now try to focus on the APIs specific to Java. We are going to explain Java SDK 2.1.3. If you are a seasoned software developer, you might have some ideas about what are required to perform operations on the database system. We need to know the hostname or the IP address of the servers that run the Couchbase database. Of course, you need the database name, which is the bucket in the Couchbase system, to connect to it before performing any operations:

Cluster cluster = CouchbaseCluster.create();
Bucket defaultBucket = cluster.openBucket();

The preceding statements create a Cluster object using a CouchbaseCluster factory class, which will be used to connect to the bucket. If you didn't specify any parameters to the create() method, then it will connect to the localhost; that is, Couchbase should be running on the server in which the...

Understanding locking


In any database system, whenever a client is trying to update a record, it acquires a lock in that record so that another client cannot update the same record. This is done to maintain consistency in RDBMS.

Sometimes, when we perform a bulk update, this locking of records escalates to locking a table, and all access is denied to that particular table. This has an adverse impact on the application's performance. A majority of the application performance issues that arise in the production environment happen due to locking of records or tables. There are various levels of locking in RDBMS depending on the application logic requirement. In my experience as a SQL DBA, I have often observed queries getting timed out while waiting to get locked on a particular record, which is already being locked by another query impacting the application's performance. I have spent a lot of time determining locks that a particular query has on a table to understand its impact on performance...

Understanding counters


There are times when we would like to have some counters defined to keep a track of documents. For example, if we want to track the sales of the book, Learning Couchbase, we can define a counter and increment it by 1 whenever someone buys the book. A counter can also be used to keep a track of users visiting the web page. It can be done as shown here:

theBucket.counter("NumberOfCopies", 1);

Initially, when the NumberOfCopies counter is not present in the bucket, it will be assigned a default value of 0. Here, the counter, NumberOfCopies, is increased by a value of 1.

async operations


Sometimes, applications perform operations on a database that doesn't need to wait until it is completed for further processing. Such operations will optimize resources in terms of CPU and disk I/O. Instead of holding the current thread and waiting for the response of that database queries, it proceeds further. Such asynchronous operations are allowed to use using Couchbase SDK. Let me show you a sample code and explain more about this:

AsyncBucket aBucket = theBucket.async();
  aBucket.get("2007").map(new Func1<JsonDocument, String>() {
                  public String call(JsonDocument jsonDocument) {
                     jsonDocument.content().put("name"," Mr " + jsonDocument.content().getString("name")); 
                      return jsonDocument.content().getString("name");
                  }
              }).subscribe(new Action1<String>() {
              
                public void call(String name) {
                    System.out.println(" Async Call...

Connection management


By now, you have understood how to connect to the bucket and perform various operations using the Java SDK. We can conclude that there are two ways of connecting to the bucket:

  • Synchronously:

    Cluster cluster = CouchbaseCluster.create();
    Bucket bucket = cluster.openBucket();
  • Asynchronously:

    AsyncBucket asyncBucket = bucket.async();

    Note

    It's best practice to create one instance of CouchbaseCluster per application.

Couchbase SDKs based on Java and .Net are designed to be thread-safe for each operation. There is a class called CouchbaseEnvironment that can be used to customize connection to the cluster.

How we create this environment is given in the following code:

CouchbaseEnvironment clusterEnv = DefaultCouchbaseEnvironment
          .builder()
          .computationPoolSize(5)
          .build();

    Cluster cluster = CouchbaseCluster.create(clusterEnv, "ourserver.com");

You need to pass the CouchbaseEnvironment object to the cluster factory method while creating the cluster...

Summary


We discussed how read, write, and delete operations work on the Couchbase server. Also, you understood various operations that are provided by the client SDK to connect and perform activities on the Couchbase cluster. We explored the concepts of the Java API. We also saw a full-fledged CRUD example. We touched upon the asynchronous operation provided by the Java SDK. Finally, we talked about customizing the connection properties.

In the next chapter, you will understand how to retrieve documents from Couchbase using views and how to write views using JavaScript. We will also discuss the concepts of MapReduce.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning Couchbase
Published in: Nov 2015 Publisher: ISBN-13: 9781785288593
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}