Connecting to Couchbase

Anaconda Enterprise enables you to connect to a Couchbase NoSQL database from within your notebook sessions.

To do so, you’ll need to do the following to install the essential elements required to connect to a Couchbase server:

  1. Download the release RPM from Couchbase to set up the Couchbase repository:

    wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-4-x86_64.rpm
    
  2. Install the RPM using yum:

    sudo yum localinstall couchbase-release-1.0-4-x86_64.rpm -y
    
  3. Install the packages required to install the pip package:

    sudo yum install libcouchbase-devel libcouchbase2-bin gcc gcc-c++ -y
    
  4. Install the pip package:

    pip install couchbase
    

NOTE: Any packages you install from the command line are available during the current session only. If you want them to persist, add them to the project’s anaconda-project.yml file. For more information, see Developing a project.

You can then use code such as this to import the modules and connect to Couchbase from within a notebook session:

# Import the modules
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator

import json

"""
Get credentials from Kubernetes. The credentials were set up as a dictionary. For example:
{
    "username": "USERNAME",
    "password": "PASSWORD"
}
"""
credentials = None
with open('/var/run/secrets/user_credentials/couchbase_credentials') as f:
 credentials = json.load(f)

# Verify the credentials were pulled correctly
if credentials:
    # Try the connection and pass in authentication details
    bucket = None
    try:
        cluster = Cluster(f"couchbase://{credentials.get('hostname')}")
        cluster.authenticate(
            PasswordAuthenticator(
                credentials.get('username'),
                credentials.get('password')
            )
        )
        bucket = cluster.open_bucket('beer-sample')
    except Exception as e:
        print(f'There was an error connecting to the bucket: {e}')

    # Confirm the bucket is connected
    if bucket and bucket.connected:
        # Get a value from the bucket by index and print out the result
        print(json.dumps(bucket.get('21st_amendment_brewery_cafe').value, indent=4))

        # Close connection
        bucket._close()