Hello World

      +
      Install, connect, try. A quick start guide to get you up and running with Couchbase and the Python SDK.

      Couchbase has a simple interface for creating and modifying records in a document, based upon the collection into which the documents are organized. You can read more about data modeling below, but first let’s look at those data operations, and installing the Python SDK.

      Upsert with Replication set to Majority Durability:
      # Upsert with Durability level Majority
      document = dict(foo="bar", bar="foo")
      opts = UpsertOptions(durability=ServerDurability(Durability.MAJORITY))
      result = collection.upsert("document-key", document, opts)

      upsert inserts (creates) the document if it does not exist, or replaces it if it does. We’ll explore creating and retrieving data records in more detail below, after walking through a quick installation.

      This page walks you through a quick installation, and CRUD examples against the Data Service. Elsewhere in this section you can find a fully worked-through Sample Application.

      Before You Start

      Couchbase Capella, our Database-as-a-Service, lets you get on with what matters, while we take care of the administration for you. Alternately, if you need to control every aspect of deployment — or just want to run the Server in a VM on your laptop — there are several self-managed options available:

      • Couchbase Capella

      • Self-Managed Couchbase Server

      If you haven’t already got a cluster set up, the easiest route is to sign up to Couchbase Capella and deploy a free tier cluster, then come back to this page. Make a note of the endpoint to connect to, and remember the credentials for the user that you set up.

      Install Couchbase Server locally, or in your private Cloud:

      For the example code below to run, you’ll need the username and password of the Administrator user that you create, and the IP address of at least one of the nodes of the cluster.

      Prerequisites

      The Couchbase Python SDK aims to support Python versions in security or bug-fix (a.k.a. maintenance) status.

      Details of all build dependencies are in the full installation guide.

      The code examples also assume:

      • Couchbase Capella

      • Self-Managed Couchbase Server

      • You have signed up to Couchbase Capella.

      • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

      • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

      Couchbase Capella uses Roles to control user access to cluster resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In production, Couchbase strongly recommends setting up users with more granular access roles as a best practice for data security.
      • Couchbase Server is installed and accessible locally.

      • You have created your own bucket, or loaded the Travel Sample dataset using the Web interface.

      • A user is created with permissions to access your cluster (at least Application Access permissions). See Manage Users, Groups and Roles for more details.

      Couchbase Server uses Role-Based Access Control (RBAC) to control access to cluster resources. In this guide we suggest using the Full Admin role created during setup of your local Couchbase Server cluster. In production, Couchbase strongly recommends setting up users with more granular access roles as a best practice for data security.

      Installation

      Given the above prerequisites, use pip to install the SDK:

      $ sudo -H python3 -m pip install couchbase

      Details of all build dependencies and platform variations are in the full installation guide. The compatibility guide lists compatible OSs and Python versions.

      IDE Plugins

      To make development easier, Couchbase plugins are available for VSCode and the IntelliJ family of IDEs and editors. For links and more information on these and other integrations across the Python ecosystem, check out the Integrations & Ecosystem page.

      Grab the Code

      If you’re all set up and in a real hurry, just grab this code sample and add in your Capella details.

      Complete Hello World code sample [Click to open or collapse the listing]
      # tag::imports[]
      from datetime import timedelta
      
      # needed for any cluster connection
      from couchbase.auth import PasswordAuthenticator
      from couchbase.cluster import Cluster
      # needed for options -- cluster, timeout, SQL++ (N1QL) query, etc.
      from couchbase.options import (ClusterOptions, ClusterTimeoutOptions,
                                     QueryOptions)
      
      # end::imports[]
      
      # tag::connect[]
      # Update this to your cluster
      endpoint = "--your-instance--.dp.cloud.couchbase.com"
      username = "username"
      password = "Password!123"
      bucket_name = "travel-sample"
      # User Input ends here.
      
      # Connect options - authentication
      auth = PasswordAuthenticator(username, password)
      
      # get a reference to our cluster
      options = ClusterOptions(auth)
      # Sets a pre-configured profile called "wan_development" to help avoid latency issues
      # when accessing Capella from a different Wide Area Network
      # or Availability Zone(e.g. your laptop).
      options.apply_profile('wan_development')
      cluster = Cluster.connect('couchbases://{}'.format(endpoint), options)
      
      # Wait until the cluster is ready for use.
      cluster.wait_until_ready(timedelta(seconds=5))
      # end::connect[]
      
      # tag::bucket[]
      # get a reference to our bucket
      cb = cluster.bucket(bucket_name)
      # end::bucket[]
      
      # tag::collection[]
      cb_coll = cb.scope("inventory").collection("airline")
      # end::collection[]
      
      # tag::upsert-func[]
      
      
      def upsert_document(doc):
          print("\nUpsert CAS: ")
          try:
              # key will equal: "airline_8091"
              key = doc["type"] + "_" + str(doc["id"])
              result = cb_coll.upsert(key, doc)
              print(result.cas)
          except Exception as e:
              print(e)
      # end::upsert-func[]
      
      # tag::get-func[]
      # get document function
      
      
      def get_airline_by_key(key):
          print("\nGet Result: ")
          try:
              result = cb_coll.get(key)
              print(result.content_as[str])
          except Exception as e:
              print(e)
      # end::get-func[]
      
      # tag::lookup-func[]
      # query for new document by callsign
      
      
      def lookup_by_callsign(cs):
          print("\nLookup Result: ")
          try:
              inventory_scope = cb.scope('inventory')
              sql_query = 'SELECT VALUE name FROM airline WHERE callsign = $1'
              row_iter = inventory_scope.query(
                  sql_query,
                  QueryOptions(positional_parameters=[cs]))
              for row in row_iter:
                  print(row)
          except Exception as e:
              print(e)
      # end::lookup-func[]
      
      
      # tag::test-doc[]
      airline = {
          "type": "airline",
          "id": 8091,
          "callsign": "CBS",
          "iata": None,
          "icao": None,
          "name": "Couchbase Airways",
      }
      # end::test-doc[]
      
      # tag::upsert-invoke[]
      upsert_document(airline)
      # end::upsert-invoke[]
      
      # tag::get-invoke[]
      get_airline_by_key("airline_8091")
      # end::get-invoke[]
      
      # tag::lookup-invoke[]
      lookup_by_callsign("CBS")
      # end::lookup-invoke[]

      Otherwise, read on as we introduce the CRUD API and connection to Capella or self-managed Couchbase Server.

      There’s a View link to the complete sample code on GitHub above each of the snippets on these SDK pages, and a Copy icon to grab just the snippet shown.

      Connect to your Database

      Connect to your Couchbase Capella operational cluster (or your local Couchbase Cluster, if you are trying out self-managed Couchbase).

      • Couchbase Capella

      • Self-Managed Couchbase Server

      # Update this to your cluster
      endpoint = "--your-instance--.dp.cloud.couchbase.com"
      username = "username"
      password = "Password!123"
      bucket_name = "travel-sample"
      # User Input ends here.
      
      # Connect options - authentication
      auth = PasswordAuthenticator(username, password)
      
      # get a reference to our cluster
      options = ClusterOptions(auth)
      # Sets a pre-configured profile called "wan_development" to help avoid latency issues
      # when accessing Capella from a different Wide Area Network
      # or Availability Zone(e.g. your laptop).
      options.apply_profile('wan_development')
      cluster = Cluster.connect('couchbases://{}'.format(endpoint), options)
      
      # Wait until the cluster is ready for use.
      cluster.wait_until_ready(timedelta(seconds=5))

      Note, the client certificate for connecting to a Capella cluster is included in the SDK installation.

      # Update this to your cluster
      username = "Administrator"
      password = "password"
      bucket_name = "travel-sample"
      # User Input ends here.
      
      # Connect options - authentication
      auth = PasswordAuthenticator(
          username,
          password,
      )
      
      # Get a reference to our cluster
      # NOTE: For non-TLS/SSL connection use 'couchbase://<your-ip-address>' instead
      cluster = Cluster.connect('couchbases://your-ip', ClusterOptions(auth))
      
      # Wait until the cluster is ready for use.
      cluster.wait_until_ready(timedelta(seconds=5))

      wait_until_ready is an optional call, but it is good practice to use it. Making connections, and opening resources such as buckets, is asynchronous — that is, the cluster.bucket call (below) returns immediately and proceeds in the background. waitUntilReady ensures that the bucket resource is fully loaded before proceeding.

      For a deeper look at connection options, read Managing Connections.

      The connection code for getting started uses the Administrator password that you were given during set up. In any production app you should create a role restricted to the permissions needed for your app — more on this in the Security documentation.

      Opening a Bucket

      Following successful authentication, open the bucket with:

      # get a reference to our bucket
      cb = cluster.bucket(bucket_name)

      Collections allow documents to be grouped by purpose or theme, according to a specified scope — see data modeling, below. Here we will use the airport collection within the inventory scope from travel-sample bucket as an example.

      cb_coll = cb.scope("inventory").collection("airline")

      Create, Read, Update, Delete

      Couchbase documents are organized into buckets, scopes, and collections. CRUD operations — Create, Read, Update, Delete — can be performed upon documents in a collection.

      Insert (Create) and Upsert

      insert and upsert will both create a new document. The difference between the two is that if a document with that key already exists, the insert operation will fail, while the upsert operation will succeed, replacing the content.

      Here is a function to wrap upsert:

      
      
      def upsert_document(doc):
          print("\nUpsert CAS: ")
          try:
              # key will equal: "airline_8091"
              key = doc["type"] + "_" + str(doc["id"])
              result = cb_coll.upsert(key, doc)
              print(result.cas)
          except Exception as e:
              print(e)

      We’ll create a new document…​

      Creating a new document
      airline = {
          "type": "airline",
          "id": 8091,
          "callsign": "CBS",
          "iata": None,
          "icao": None,
          "name": "Couchbase Airways",
      }

      … And call our wrapper function

      Upserting the document
      upsert_document(airline)

      Get (Read)

      The get method reads a document from a collection.

      # get document function
      
      
      def get_airline_by_key(key):
          print("\nGet Result: ")
          try:
              result = cb_coll.get(key)
              print(result.content_as[str])
          except Exception as e:
              print(e)

      Replace (Update) and Overloads

      The replace method updates the value of an existing document
      # Replace document with CAS
      result = collection.get("document-key")
      doc = result.content_as[dict]
      doc["bar"] = "baz"
      opts = ReplaceOptions(cas=result.cas)
      result = collection.replace("document-key", doc, opts)

      When you replace a document, it’s usually good practice to use optimistic locking, as in the above example, using CAS. Otherwise, changes might get lost if two people change the same document at the same time.

      Remove (Delete)

      The remove method deletes a document from a collection:

      # remove document with options
      result = collection.remove(
          "document-key",
          RemoveOptions(
              cas=12345,
              durability=ServerDurability(
                  Durability.MAJORITY)))

      Like replace, remove also optionally takes the CAS value if you want to make sure you are only removing the document if it hasn’t changed since you last fetched it.

      Data Modeling

      Documents are organized into collections — collections of documents that belong together. You get to decide what it means to "belong." Developers usually put documents of the same type in the same collection.

      For example, imagine you have two types of documents: customers and invoices. You could put the customer documents in a collection called customers, and the invoice documents in a collection called invoices.

      Each document belongs to exactly one collection. A document’s ID is unique within the collection.

      Different scopes can hold collections with different names. There is no relationship between collections in different scopes. Each collection belongs to just one scope and a collection’s name is unique within the scope.

      More details can be found on the Data Model page.

      What Next?

      Next Steps