• Articles
  • Tutorials
  • Interview Questions

Guidelines

Tutorial Playlist

Administration guide :

A large number of varying tools allow the administration of this Server.
Web Console :
This tool allows the controlling governing and complete building up of the installation of this Server. It is a default management system.
Command-line Interface (CLI) :

This tool allows the data for installing and supervising of the server. Along with the scripts, it can be utilized to gain superfluous features including equipment malfunction and fault tolerant problems.

Looking  for Top  Jobs ? This blog post gives you all the information you need !

REST API :

It is an interface responsible for the management of the server. It is scripted in a Hyper Text Transmission Protocol.

Direct  accessing of the Server :

For accessing the Server directly we have to open and go online with any browser using the  internet.

Indirect Accessing of the Server :

For indirect accessing of the server, with a memory cached one no particular libraries are needed. The replication and extension of data are automatically done without the knowledge of the client.

Read these Top Trending Couchbase  Interview Q’s now that helps you grab high-paying jobs !

Developer Guide :

This provides byroad  data concerning to interacting with the Server. SDKs have the most gifted APIs obtainable for accessing data. They offer a consistent and likely practice for our idiom. SDKs try to chase frequent verbs and semantics  as much as the entity language allows. Examples of using SDKs will be long-established in Python, but we can with no trouble be copied in other languages. Numerous illustrations are also on hand in other languages.

EXAMPLES:

Developer Guide Examples

Few examples according to their connections are given below:

Basic Connection

For connecting a bucket with a remote Couchbase cluster Basic connection is used.

C Program:

#include<libcouchbase/couchbase.h>
#include <string.h>
#include <stdlib.h>
static void
die(lcb_error_t rc, const char *msg)
{
fprintf(stderr, "%s failed. (0x%x, %s)\n", msg, rc, lcb_strerror(NULL, rc));
exit(EXIT_FAILURE);
}
int
main(int argc, char **argv)
{
lcb_t instance;
struct lcb_create_st cropts;
lcb_error_t rc;
memset(&cropts, 0, sizeof cropts);
cropts.version = 3;
cropts.v.v3.connstr = "couchbase://10.0.0.31/default";
rc = lcb_create(&instance, &cropts);
if (rc != LCB_SUCCESS)
{ die(rc, "Creating instance");
}
rc = lcb_connect(instance);
if (rc != LCB_SUCCESS)
{ die(rc, "Connection scheduling");
}
/* This function required to actually schedule the operations on the network */
lcb_wait(instance);
/* Determines if the bootstrap/connection succeeded */
rc = lcb_get_bootstrap_status(instance);
if (rc != LCB_SUCCESS)
{
die(rc, "Connection bootstraping");
}
else
{
printf("Connection succeeded. Cluster has %d nodes\n",
lcb_get_num_nodes(instance));
}
lcb_destroy(instance); return 0;
}

Python program:

#!/usr/bin/env python
from __future__ import print_function
from couchbase.bucket import Bucket
import couchbase.exceptions as E
cb = Bucket('couchbase://10.0.0.31/default')
# This always works!
print('Upserting')
cb.upsert('docid', {'property': 'value'})
print('Getting item back. Value is:',
cb.get('docid').value)
print('...')
print('Will try to insert the document. Should fail because the item already exists..')
try:
cb.insert('docid', {'property': 'value'})
except E.KeyExistsError:
print('Insert failed because item already exists!')
print('...')
print('Replacing the document. This should work because the item already exists')
cb.replace('docid', {'property': 'new_value'})
print('Getting document again. Should contain the new contents:',
cb.get('docid').value)
print('...')
print('Removing document.')
# Remove the item, then try to replace it!
cb.remove('docid')
print('Replacing document again. Should fail because document no longer exists')
try:
cb.replace('docid', {'property': 'another value'})
except E.NotFoundError:
print('Get failed since item does not exist')

JAVA Program:

package com.couchbase.devguide;
import java.util.Arrays;
import java.util.List;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import org.apache.log4j.Logger;
public class ConnectionBase
{ protected static final Logger LOGGER = Logger.getLogger("devguide");
protected final Cluster cluster;
protected final Bucket bucket;
//=== EDIT THESE TO ADAPT TO YOUR COUCHBASE INSTALLATION ===
public static final String bucketName = "default";
public static final String bucketPassword = "";
public static final List<
String> nodes = Arrays.asList("127.0.0.1");
protected ConnectionBase()
{
//connect to the cluster by hitting one of the given nodes cluster = CouchbaseCluster.create(nodes); //
get a Bucket reference from the cluster to the configured bucket bucket = cluster.openBucket(bucketName, bucketPassword);
}
private void disconnect()
{
//release shared resources and close all open buckets cluster.disconnect();
}
public void execute()
{
//connection has been done in the constructor doWork();
disconnect();
}
/** * Override this method to showcase specific examples.
* Make them executable by adding a main method calling new ExampleClass().
execute();
*/
protected void doWork()
{
//this one just showcases connection methods, see constructor and shutdown()
LOGGER.info("Connected to the cluster, opened bucket " + bucketName);
}
public static void main(String[] args)
{
new ConnectionBase().execute();
}
}

SSL Connection:
For the SSL connections the examples are:
Cprogram:

#include <libcouchbase/couchbase.h>
#include <string.h>
#include <stdlib.h>
static void
die(lcb_error_t rc, const char *msg)
{
fprintf(stderr, "%s failed. (0x%x, %s)\n", msg, rc, lcb_strerror(NULL, rc));
exit(EXIT_FAILURE);
}
int
main(int argc, char **argv)
{
lcb_t instance;
struct lcb_create_st cropts;
lcb_error_t rc;
memset(&cropts, 0, sizeof cropts);
cropts.version = 3;
cropts.v.v3.connstr = "couchbases://10.0.0.31/default?certpath=/tmp/couchbase-ssl-certificate.pem";
rc = lcb_create(&instance, &cropts);
if (rc != LCB_SUCCESS) {
die(rc, "Creating instance");
}
rc = lcb_connect(instance);
if (rc != LCB_SUCCESS) {
die(rc, "Connection scheduling");
}
/* This function required to actually schedule the operations on the network */
lcb_wait(instance);
/* Determines if the bootstrap/connection succeeded */
rc = lcb_get_bootstrap_status(instance);
if (rc != LCB_SUCCESS) {
die(rc, "Connection bootstraping");
} else {
printf("Connection succeeded. Cluster has %d nodes\n",
lcb_get_num_nodes(instance));
}
/* SSL connections use different ports. For example, the REST API
* connection will use port 18091 rather than 8091 when using SSL */
const char *node = lcb_get_node(instance, LCB_NODE_HTCONFIG, 0);
printf("First node address for REST API: %s\n", node);
lcb_destroy(instance);
return 0;
}

Java program:

package com.couchbase.devguide;
import java.util.Arrays;
import java.util.List;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
import org.apache.log4j.Logger;
public class ConnectingSsl {
protected static final Logger LOGGER = Logger.getLogger("devguide");
protected final Cluster cluster;
protected final Bucket bucket;
protected final CouchbaseEnvironment env;
//=== EDIT THESE TO ADAPT TO YOUR COUCHBASE INSTALLATION ===
public static final String bucketName = "default";
public static final String bucketPassword = "";
public static final List<String> nodes = Arrays.asList("127.0.0.1");
//=== You need to correctly set up your JVM keystore first! ===
//see instructions in http://developer.couchbase.com/documentation/server/4.0/sdks/java-2.2/managing-connections.html#story-h2-5
protected ConnectingSsl() {
//configure the SDK to use SSL and point it to the keystore
env = DefaultCouchbaseEnvironment.builder()
.sslEnabled(true)
.sslKeystoreFile("/path/tokeystore")
.sslKeystorePassword("password")
.build();
//connect using the SSL configuration, by hitting one of the given nodes
cluster = CouchbaseCluster.create(env, nodes);
//get a Bucket reference from the cluster to the configured bucket
bucket = cluster.openBucket(bucketName, bucketPassword);
}
private void disconnect() {
//release shared resources and close all open buckets
cluster.disconnect();
//also release the environment since we created it ourselves (notice this is an async operation so we block on it)
env.shutdownAsync().toBlocking().first();
}
public void execute() {
//connection has been done in the constructor
doWork();
disconnect();
}
/**
* Override this method to showcase specific examples.
* Make them executable by adding a main method calling new ExampleClass().execute();
*/
protected void doWork() {
//this one just showcases connection methods, see constructor and shutdown()
LOGGER.info("Connected to the cluster, opened bucket " + bucketName);
}
public static void main(String[] args) {
new ConnectingSsl().execute();
}
}

Python program:

#!/usr/bin/env python
from couchbase.bucket import Bucket
# Note the `couchbases` in the scheme. This is required for SSL connections!
cb = Bucket('couchbases://10.0.0.31/default?certpath=/tmp/couchbase-ssl-certificate.pem')
print cb.server_nodes

Updating/Storing :

For storing the cluster with items, the examples are as follows:

C Program :

#include <libcouchbase/couchbase.h>
#include <libcouchbase/api3.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
lcb_error_t rc;
lcb_cas_t cas;
} my_OPINFO;
static void
update_callback(lcb_t instance, int cbtype, const lcb_RESPBASE *resp)
{
my_OPINFO *info = resp->cookie;
info->rc = resp->rc;
info->cas = resp->cas;
}
int
main(int argc, char **argv)
{
lcb_t instance;
struct lcb_create_st crst;
lcb_error_t rc;
lcb_CMDSTORE cmd = { 0 };
const char *key, *value;
my_OPINFO info;
memset(&crst, 0, sizeof crst);
crst.version = 3;
crst.v.v3.connstr = "couchbase://10.0.0.31/default";
/* See connecting.c for error checking */
lcb_create(&instance, &crst);
lcb_connect(instance);
lcb_wait(instance);
/* Set global storage callback */
lcb_install_callback3(instance, LCB_CALLBACK_STORE, update_callback);
key = "docid";
value = "{\"property\":\"value\"}";
LCB_CMD_SET_KEY(&cmd, key, strlen(key));
LCB_CMD_SET_VALUE(&cmd, value, strlen(value));
lcb_sched_enter(instance);
/* Schedule unconditional upsert (LCB_SET). Should always succeed */
cmd.operation = LCB_SET;
if ((rc = lcb_store3(instance, &info, &cmd) != LCB_SUCCESS)) {
printf("Couldn't schedule store operation: %s\n", lcb_strerror(NULL, rc));
exit(EXIT_FAILURE);
}
lcb_sched_leave(instance);
lcb_wait(instance);
printf("Upsert for %s got code %d (0 is success)\n", key, info.rc);
/* Preserve the operation structure, just changing the operation type */
lcb_sched_enter(instance);
/* Do an insert (LCB_ADD). This will fail since the item already exists */
cmd.operation = LCB_ADD;
lcb_store3(instance, &info, &cmd);
lcb_sched_leave(instance);
lcb_wait(instance);
printf("Insert for %s got code %d (%s) (0 is success). Failure expected\n",
key, info.rc, lcb_strerror(NULL, info.rc));
/* Do a replace (LCB_REPLACE) */
cmd.operation = LCB_REPLACE;
lcb_sched_enter(instance);
lcb_store3(instance, &info, &cmd);
lcb_sched_leave(instance);
lcb_wait(instance);
printf("Replace for %s got code %d\n", key, info.rc);
lcb_destroy(instance);
return 0;
}

Python Program :

#!/usr/bin/env python
from __future__ import print_function
from couchbase.bucket import Bucket
import couchbase.exceptions as E
cb = Bucket('couchbase://10.0.0.31/default')
# This always works!
print('Upserting')
cb.upsert('docid', {'property': 'value'})
print('Getting item back. Value is:',
cb.get('docid').value)
print('...')
print('Will try to insert the document. Should fail because the item already exists..')
try:
cb.insert('docid', {'property': 'value'})
except E.KeyExistsError:
print('Insert failed because item already exists!')
print('...')
print('Replacing the document. This should work because the item already exists')
cb.replace('docid', {'property': 'new_value'})
print('Getting document again. Should contain the new contents:',
cb.get('docid').value)
print('...')
print('Removing document.')
# Remove the item, then try to replace it!
cb.remove('docid')
print('Replacing document again. Should fail because document no longer exists')
try:
cb.replace('docid', {'property': 'another value'})
except E.NotFoundError:
print('Get failed since item does not exist')

Java Program :

package com.couchbase.devguide;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.error.DocumentAlreadyExistsException;
/**
* Example of Updating/Storing in Java for the Couchbase Developer Guide.
*/
public class Updating extends ConnectionBase {
@Override
protected void doWork() {
String key = "javaDevguideExampleUpdating";
//create content
JsonObject content = JsonObject.create().put("topic", "storing").put("mutation", true);
//create document
JsonDocument document = JsonDocument.create(key, content);
LOGGER.info("Prepared document " + document);
//store the document (upsert will always work whether or not a value is already associated to the key)
document = bucket.upsert(document);
LOGGER.info("Document after upsert: " + document); //notice the CAS changed (the returned document is updated with correct CAS)
//prepare an update
document.content().put("update", "something");
//see that inserting it fails because it already exists
try {
bucket.insert(document);
} catch (DocumentAlreadyExistsException e) {
LOGGER.warn("Couldn't insert it, DocumentAlreadyExists... Let's try to replace it");
}
//on the other hand, updating works (it would have failed if the key was not in database)
document = bucket.replace(document);
LOGGER.info("Replaced the old document by the new one: " + document); //notice the document's CAS changed again...
LOGGER.info("Got the following from database: " + bucket.get(key)); //... which is consistent with a get (RYOW)
}
public static void main(String[] args) {
new Updating().execute();
}
}

.NET Program :

using Couchbase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DevGuide
{
public class Update : ConnectionBase
{
public override async Task ExecuteAsync()
{
var key = "dotnetDevguideExampleUpdate-" + DateTime.Now.Ticks;
var data = new Data
{
Number = 42,
Text = "Life, the Universe, and Everything",
Date = DateTime.UtcNow
};
// Prepare the document
// Note that upsert works whether the document exists or not
await _bucket.UpsertAsync(key, data);
// Change the data
data.Number++;
data.Text = "What's 7 * 6 + 1?";
data.Date = DateTime.UtcNow;
// Try to insert under the same key should fail
var insertResult = await _bucket.InsertAsync(key, data);
if (!insertResult.Success)
Console.WriteLine("Inserting under an existing key fails as expected.");
// Replace existing document
// Note this only works if the key already exists
var replaceResult = await _bucket.ReplaceAsync(key, data);
// Check that the data was updated
var newDocument = await _bucket.GetAsync<Data>(key);
Console.WriteLine("Got: " + data.Text);
}
static void Main(string[] args)
{
new Update().ExecuteAsync().Wait();
}
}
}

Retrieving :

For emptying the clusters from the items th examples are as follows:

C Programming:

#include <libcouchbase/couchbase.h>
#include <libcouchbase/api3.h>
#include <string>
#include <string.h>
#include <iostream>
struct Result {
std::string value;
lcb_error_t status;
Result() : status(LCB_SUCCESS) {
}
};
extern "C" {
static void
get_callback(lcb_t, int, const lcb_RESPBASE *rb)
{
// "cast" to specific callback type
const lcb_RESPGET *resp = reinterpret_cast<const lcb_RESPGET*>(rb);
Result *my_result = reinterpret_cast<Result*>(rb->cookie);
my_result->status = resp->rc;
my_result->value.clear(); // Remove any prior value
if (resp->rc == LCB_SUCCESS) {
my_result->value.assign(
reinterpret_cast<const char*>(resp->value),
resp->nvalue);
}
}
}
int
main(int, char **)
{
lcb_create_st crst;
lcb_t instance;
memset(&crst, 0, sizeof crst);
crst.version = 3;
crst.v.v3.connstr = "couchbase://10.0.0.31/default";
lcb_create(&instance, &crst);
lcb_connect(instance);
lcb_wait(instance);
// Store a key first, so we know it will exist later on. In real production
// environments, we'd also want to install a callback for storage operations
// so we know if they succeeded
lcb_CMDSTORE scmd = { 0 };
const char *key = "a_key";
const char *value = "{\"some\":\"json\"}";
LCB_CMD_SET_KEY(&scmd, key, strlen(key));
LCB_CMD_SET_VALUE(&scmd, value, strlen(value));
scmd.operation = LCB_SET; // Upsert
lcb_sched_enter(instance);
lcb_store3(instance, NULL, &scmd);
lcb_sched_leave(instance);
lcb_wait(instance);
// Install the callback for GET operations. Note this can be done at any
// time before the operation is scheduled
lcb_install_callback3(instance, LCB_CALLBACK_GET, get_callback);
Result my_result;
lcb_CMDGET gcmd = { 0 };
LCB_CMD_SET_KEY(&gcmd, key, strlen(key));
lcb_sched_enter(instance);
lcb_get3(instance, &my_result, &gcmd);
lcb_sched_leave(instance);
lcb_wait(instance);
std::cout << "Status for getting " << key << ": ";
std::cout << lcb_strerror(NULL, my_result.status);
std::cout << ". Value: " << my_result.value << std::endl;
// Let's see what happens if we get a key that isn't yet stored:
key = "non-exist-key";
LCB_CMD_SET_KEY(&gcmd, key, strlen(key));
lcb_sched_enter(instance);
lcb_get3(instance, &my_result, &gcmd);
lcb_sched_leave(instance);
lcb_wait(instance);
std::cout << "Status for getting " << key << ": ";
std::cout << lcb_strerror(NULL, my_result.status) << std::endl;
lcb_destroy(instance);
}

 

Python Program:

#!/usr/bin/env python
from __future__ import print_function
from couchbase.bucket import Bucket
from couchbase.exceptions import NotFoundError
cb = Bucket('couchbase://10.0.0.31/default')
print('Getting non-existent key. Should fail..')
try:
cb.get('non-exist-document')
except NotFoundError:
print('Got exception for missing document!')
print('...')
print('Upserting...')
cb.upsert('new_document', {'foo': 'bar'})
print('Getting...')
print(cb.get('new_document').value)

Java Program:

package com.couchbase.devguide;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
/**
* Example of Retrieving in Java for the Couchbase Developer Guide.
*/
public class Retrieving extends ConnectionBase {
@Override
protected void doWork() {
String key = "javaDevguideExampleRetrieving";
LOGGER.info("Getting non-existent key. Should fail..");
JsonDocument nonExistentDocument = bucket.get("non-exist-document");
if (nonExistentDocument == null) {
LOGGER.info("Got null for missing document, it doesn't exist!");
}
LOGGER.info("Upserting...");
JsonDocument document = JsonDocument.create(key, JsonObject.create().put("foo", "bar"));
bucket.upsert(document);
LOGGER.info("Getting...");
LOGGER.info(bucket.get(key));
}
public static void main(String[] args) {
new Retrieving().execute();
}
}

.NET Program:

using Couchbase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DevGuide
{
public class Retrieve : ConnectionBase
{
public override async Task ExecuteAsync()
{
var key = "dotnetDevguideExampleRetrieve-" + DateTime.Now.Ticks;
var data = new Data
{
Number = 42,
Text = "Life, the Universe, and Everything",
Date = DateTime.UtcNow };
// Get non-existent document.
// Note that it's enough to check the Status property,
// We're only checking all three to show they exist.
var notFound = await _bucket.GetAsync<dynamic>
(key);
if (!notFound.Success &&
notFound.Status == Couchbase.IO.ResponseStatus.KeyNotFound &&
notFound.Value == null)
Console.WriteLine("Document doesn't exist!");
// Prepare a string value await _bucket.UpsertAsync(key, "Hello Couchbase!");
// Get a string value var nonDocResult = await _bucket.GetAsync<string>
(key);
Console.WriteLine("Found: " + nonDocResult.Value);
// Prepare a JSON document value await _bucket.UpsertAsync(key, data);
// Get a JSON document string value var docResult = await _bucket.GetAsync<Data>
(key);
Console.WriteLine("Found: " + docResult.Value);
}
static void Main(string[] args)
{
new Retrieve().ExecuteAsync().Wait();
}
}
}

Conclusion

Couchbase has become pervasive in our everyday lives. Many Fortune companies are using Couchbase these days. With Couchbase in the picture, Companies create exceptional engagements for customers and employees with its unmatched developer agility, flexibility, and unparalleled performance at any scale on the easiest platform to manage. To learn Couchbase in detail, check out the Couchbase Training by Intellipaat where You will get hands-on experience in working with Couchbase Server that can store credentials and key-values.In this course, you will learn in detail about Couchbase distributed architecture, Couchbase Server, searching, querying, indexing data, Couchbase flexible data model. And you will also work on real-life industry projects.

Course Schedule

Name Date Details
Couchbase Training 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Couchbase Training 04 May 2024(Sat-Sun) Weekend Batch
View Details
Couchbase Training 11 May 2024(Sat-Sun) Weekend Batch
View Details

Advanced-Certification-in-Data-Science-and-AI-IITR.png

Find MongoDB Training in Other Regions

Bangalore Chennai Delhi Hyderabad London Sydney United States