A newer version of this documentation is available.

View Latest

Connecting to Couchbase

  • how-to
    +
    How to connect to a Couchbase Cluster.

    Introduction

    Connecting to Couchbase can be done in several ways. This guide will take you through some of the most common methods used to access a Couchbase cluster with an SDK client or CLI tool.

    A Couchbase Cluster is a combination of multiple server nodes, which can be accessed by users or applications with a username and password. Each server node can also be its own cluster or join an existing multi-node setup.

    Couchbase uses Role Based Access Control (RBAC) to control access to its various services. A user or application can connect to a cluster and use these services, assuming that valid credentials with relevant access roles are provided.

    Before You Begin

    If you want to try out the examples in this section, follow the instructions given in Do a Quick Install to install Couchbase Server, configure a cluster, and load a sample dataset.

    Couchbase Clients

    Clients access data by connecting to a Couchbase cluster over the network. The most common type of client is a Couchbase SDK, which is a full programmatic API that enables applications to take the best advantage of Couchbase. This developer guide focuses on the most commonly-used SDKs, but full explanations and reference documentation for all SDKs is available.

    The command line clients also provide a quick and streamlined interface for simple access and are suitable if you just want to access an item without writing any code.

    With some editions, the command line clients are provided as part of the installation of Couchbase Server. Assuming a default installation, you can find them in the following location, depending on your operating system:

    Linux

    /opt/couchbase/bin

    Windows

    C:\Program Files\Couchbase\Server\bin

    macOS

    /Applications/Couchbase Server.app/Contents/Resources/couchbase-core/bin

    If the command line client is not provided with your installation of Couchbase Server, you must install the C SDK in order to use the command line clients.

    Read the following for further information about the clients available:

    Connecting to Couchbase Server

    Couchbase Server can be configured to run with unencrypted or encrypted network access. When running Couchbase in a production environment, the latter is always recommended.

    Basic Auth

    To connect to a standalone or Docker installation with unencrypted network access, set up a user with appropriate access levels and a secure password.

    • Web Console

    • cbc

    • .NET

    • Java

    • Node.js

    • Python

    To access a cluster via the Couchbase Server Web Console over an unencrypted connection, navigate to the Web Console address with your browser (by default, localhost:8091) and enter your credentials.

    The Couchbase Admin

    See Authenticating with the Console for more information.

    Most cbc sub-commands will require some form of authentication to access a cluster or perform operations on data within a bucket.

    1. To connect to Couchbase Server using cbc, pass -u for the username, -P for the password and -U for the connection URL immediately after a sub-command.

    2. Provide the bucket name required in the connection URL (i.e., couchbase://localhost/<bucket-name>).


    The example below connects to the travel-sample bucket with Admin level credentials and performs a ping to check what services are running in a single-node cluster environment.

    cbc ping -u Administrator -P password -U couchbase://localhost/travel-sample \
    	--count=1 \
    	--table
    Result
    -------------------------------------------------------------------------------
    | type  | id       | status | latency, us | remote          | local           |
    -------------------------------------------------------------------------------
    | cbas  | 0xec22b0 | ok     |        3003 | localhost:8095  | 127.0.0.1:38612 |
    | fts   | 0xec0dc0 | ok     |        3842 | localhost:8094  | 127.0.0.1:35636 |
    | kv    | 0xeaa220 | ok     |        4446 | localhost:11210 | 127.0.0.1:49426 |
    | n1ql  | 0xead260 | ok     |        4249 | localhost:8093  | 127.0.0.1:56740 |
    | views | 0xec0430 | ok     |        4045 | localhost:8092  | 127.0.0.1:60088 |
    -------------------------------------------------------------------------------
    If the user credentials are invalid, cbc will return a LCB_ERR_AUTHENTICATION_FAILURE error.

    For further details, refer to cbc(1).

    Call the Cluster.ConnectAsync() method with a connection URL, username and password.


    The example below connects to a single-node cluster environment with basic auth credentials.

    var cluster = await Cluster.ConnectAsync("couchbase://your-ip", "Administrator", "password");
    var bucket =  await cluster.BucketAsync("travel-sample");
    var collection = bucket.DefaultCollection();
    
    // You can access multiple buckets using the same Cluster object.
    var anotherBucket = await cluster.BucketAsync("travel-sample");
    
    // You can access collections other than the default
    // if your version of Couchbase Server supports this feature.
    var inventory = bucket.Scope("inventory");
    var airline = inventory.Collection("airline");
    
    // For a graceful shutdown, disconnect from the cluster when the program ends.
    await cluster.DisposeAsync();

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Call the Cluster.connect() method with a connection URL, username and password.


    The example below connects to a single-node cluster environment with basic auth credentials.

    Cluster cluster = Cluster.connect("127.0.0.1", "username", "password");
    Bucket bucket = cluster.bucket("travel-sample");
    Collection collection = bucket.defaultCollection();
    
    // You can access multiple buckets using the same Cluster object.
    Bucket anotherBucket = cluster.bucket("beer-sample");
    
    // You can access collections other than the default
    // if your version of Couchbase Server supports this feature.
    Scope customerA = bucket.scope("customer-a");
    Collection widgets = customerA.collection("widgets");
    
    // For a graceful shutdown, disconnect from the cluster when the program ends.
    cluster.disconnect();
    If the user credentials provided are invalid, the SDK will return a AuthenticationFailureException error.

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Call the connect() function with a connection URL, and a ConnectOptions object containing the username and password.


    The example below connects to a single-node cluster environment with basic auth credentials.

    var cluster = await couchbase.connect('couchbase://localhost', {
      username: 'Administrator',
      password: 'password',
    })
    If the user credentials provided are invalid, the SDK will return a AuthenticationFailureError error.

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    1. Call the Cluster.connect() function with a connection URL, and a ClusterOptions object containing a PasswordAutheticator.

    2. Provide a username and password to the PasswordAutheticator.


    The example below connects to a single-node cluster environment with basic auth credentials.

    cluster = Cluster.connect("couchbase://your-ip", ClusterOptions(PasswordAuthenticator("Administrator", "password")))
    bucket = cluster.bucket("travel-sample")
    collection = bucket.default_collection()
    
    # You can access multiple buckets using the same Cluster object.
    another_bucket = cluster.bucket("beer-sample")
    
    # You can access collections other than the default
    # if your version of Couchbase Server supports this feature.
    customer_a = bucket.scope("customer-a")
    widgets = customer_a.collection("widgets")
    If the user credentials provided are invalid, the SDK will return a AuthenticationException error.

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    TLS

    To connect to a cluster configured with TLS (Transport Layer Security), for encrypted network access, you must supply an X.509 certificate. Before using X.509 certificate based authentication, you should run through the following:

    • Web Console

    • cbc

    • .NET

    • Java

    • Node.js

    • Python

    To access a cluster via the Couchbase Server Web Console over an encrypted connection, navigate to the secure Web Console address with your browser (by default, https://localhost:18091) and enter your credentials.

    The Couchbase Admin

    See Manage Console Access for more information.

    1. To securely connect to Couchbase Server using cbc, pass -U for the connection URL immediately after a sub-command.

    2. Provide the bucket name required in the connection URL (i.e., couchbases://127.0.0.1/<bucket-name>). Note that "couchbases://" implies an encrypted connection scheme is used.

    3. Pass a certpath query parameter to the connection URL, after the bucket name.


    The example below connects to the travel-sample bucket with a client certificate, and performs a ping to check what services are running in a single-node secured cluster environment.

    cbc ping -v -U "couchbases://127.0.0.1/travel-sample?certpath=ca.pem" \
    	--count=1 \
    	--table

    For further details, refer to cbc(1).

    1. Call the WithX509CertificateFactory() method on a ClusterOptions() object.

    2. Provide the certificate store information to the WithX509CertificateFactory() method.

    3. Call the ConnectAsync() method and pass it the cluster options object.


    The example below connects to a single-node cluster over a secure connection with a client certificate.

    It is assumed that a valid client certificate and certificate store have been set up.

    Unresolved include directive in modules/guides/pages/connect.adoc - include::dotnet-sdk:howtos:example$Auth.cs[]

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    1. Load a Java keystore file containing your client certificate and pass it to the CertificateAuthenticator.fromKeyStore() method along with the required password.

    2. Call the Cluster.connect() method and pass the connection string along with cluster options containing the CertificateAuthenticator object previously created.


    The example below connects to a single-node cluster over a secure connection with a client certificate.

    It is assumed that a valid client certificate and a Java keystore have been set up.

    // Replace the following line with code that gets your actual key store.
    // The key store contains the client's certificate and private key.
    KeyStore keyStore = loadKeyStore();
    
    Authenticator authenticator = CertificateAuthenticator.fromKeyStore(
        keyStore,
        "keyStorePassword"
    );
    
    Cluster cluster = Cluster.connect(
        "couchbases://127.0.0.1",
        clusterOptions(authenticator)
            .environment(env -> env
                .securityConfig(security -> security
                    // Tell the client to trust the cluster's root certificate.
                    // If your cluster's root certificate is from a well-known
                    // Certificate Authority (CA), you can skip this.
                    .trustCertificate(Paths.get("/path/to/ca-cert.pem"))
                )
            )
    );        

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Call the connect() function with a connection URL, and a ConnectOptions object containing a certificate trustStorePath and user credentials.


    The example below connects to a single-node cluster over a secure connection with a client certificate.

    It is assumed that a valid client certificate has been set up.

    cluster = await couchbase.connect('couchbases://localhost', {
      trustStorePath: '/path/to/ca/certificates.pem',
      username: 'Administrator',
      password: 'password',
    })

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    1. Call the Cluster.connect() function with a connection URL, and a ClusterOptions object containing a PasswordAutheticator.

    2. Provide a username and password to the PasswordAutheticator.

    3. Supply a certificate path to the PasswordAutheticator.


    The example below connects to a single-node cluster over a secure connection with a client certificate.

    It is assumed that a valid client certificate has been set up.

    cluster = Cluster("couchbases://your-ip",ClusterOptions(PasswordAuthenticator("Administrator","password",cert_path="/path/to/cluster.crt")))

    Click the GitHub button to view this code in context.

    For further details, refer to Cluser.

    Connecting to Couchbase Capella

    To connect to the database via Couchbase Capella, create a valid account and set up some database credentials.

    The Security Certificate

    Download a security certificate to connect an SDK or CLI client to Capella.

    • Web Console

    • cbc

    • .NET

    • Java

    • Node.js

    • Python

    Navigate to https://cloud.couchbase.com/login to access the Capella Web Console.

    The Couchbase Capella Login

    See Cluster and Data for more information.

    1. To connect to Couchbase Capella using cbc, pass -u for the username, -P for the password and -U for the connection URL immediately after a sub-command.

    2. Provide the bucket name required in the connection URL (i.e., cb.<your endpoint address>.dp.cloud.couchbase.com/<bucket-name>).


    The example below connects to a bucket on Couchbase Capella with a client certificate, and performs a ping to check what services are running.

    cbc ping -u username -P "passworD#1" \
    	-U "couchbases://cb.oawlpi4audpc6jp5.cloud.couchbase.com/travel-sample?certpath=cert.pem" \
    	--count=1 \
    	--table
    Result
    -----------------------------------------------------------------------------------------------------------------------------------
    | type  | id             | status | latency, us | remote                                                      | local             |
    -----------------------------------------------------------------------------------------------------------------------------------
    | fts   | 0x7fecf9407a70 | ok     |      198657 | evb8loulphaibjnn.oawlpi4audpc6jp5.cloud.couchbase.com:18094 | 172.20.10.6:54394 |
    | kv    | 0x7fecfb00d110 | ok     |       69737 | evb8loulphaibjnn.oawlpi4audpc6jp5.cloud.couchbase.com:11207 | 172.20.10.6:54391 |
    | n1ql  | 0x7fecfb0110f0 | ok     |      210735 | evb8loulphaibjnn.oawlpi4audpc6jp5.cloud.couchbase.com:18093 | 172.20.10.6:54392 |
    | views | 0x7fecf961e2e0 | ok     |      330057 | evb8loulphaibjnn.oawlpi4audpc6jp5.cloud.couchbase.com:18092 | 172.20.10.6:54393 |
    -----------------------------------------------------------------------------------------------------------------------------------

    For further details, refer to cbc(1).

    Call the Cluster.ConnectAsync() method with a Couchbase Capella endpoint, username, password, and client certificate.


    The example below connects to a Couchbase Capella instance over a secure connection with a client certificate.

    Unresolved include directive in modules/guides/pages/connect.adoc - include::dotnet-sdk:devguide:example$dotnet/Cloud.cs[]

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Call the Cluster.connect() method method with a Couchbase Capella endpoint, username, password, and client certificate.


    The example below connects to a Couchbase Capella instance over a secure connection with a client certificate.

    /*
     * Copyright (c) 2020 Couchbase, Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *    http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    import static com.couchbase.client.java.query.QueryOptions.queryOptions;
    
    import java.io.ByteArrayInputStream;
    import java.nio.charset.StandardCharsets;
    import java.security.KeyStore;
    import java.security.cert.CertificateException;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;
    import java.util.Collections;
    import java.util.List;
    import java.util.stream.Collectors;
    
    import com.couchbase.client.core.deps.io.netty.handler.ssl.util.InsecureTrustManagerFactory;
    import com.couchbase.client.core.env.IoConfig;
    import com.couchbase.client.core.env.SecurityConfig;
    import com.couchbase.client.java.Bucket;
    import com.couchbase.client.java.Cluster;
    import com.couchbase.client.java.ClusterOptions;
    import com.couchbase.client.java.Collection;
    import com.couchbase.client.java.Scope;
    import com.couchbase.client.java.env.ClusterEnvironment;
    import com.couchbase.client.java.json.JsonArray;
    import com.couchbase.client.java.json.JsonObject;
    import com.couchbase.client.java.manager.query.CreatePrimaryQueryIndexOptions;
    import com.couchbase.client.java.query.QueryResult;
    
    /**
     * Example of Cas (Check and Set) handling in Java for the Couchbase Developer
     * Guide ported from 2.x. See StartUsingCapella.java for 3.x.
     */
    
    public class Cloud {
        // Update this to your certificate.
        private static final String CERT = "-----BEGIN CERTIFICATE-----\n"
                + "MIIDFTCCAf2gAwIBAgIRANLVkgOvtaXiQJi0V6qeNtswDQYJKoZIhvcNAQELBQAw\n"
                + "JDESMBAGA1UECgwJQ291Y2hiYXNlMQ4wDAYDVQQLDAVDbG91ZDAeFw0xOTEyMDYy\n"
                + "MjEyNTlaFw0yOTEyMDYyMzEyNTlaMCQxEjAQBgNVBAoMCUNvdWNoYmFzZTEOMAwG\n"
                + "A1UECwwFQ2xvdWQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCfvOIi\n"
                + "enG4Dp+hJu9asdxEMRmH70hDyMXv5ZjBhbo39a42QwR59y/rC/sahLLQuNwqif85\n"
                + "Fod1DkqgO6Ng3vecSAwyYVkj5NKdycQu5tzsZkghlpSDAyI0xlIPSQjoORA/pCOU\n"
                + "WOpymA9dOjC1bo6rDyw0yWP2nFAI/KA4Z806XeqLREuB7292UnSsgFs4/5lqeil6\n"
                + "rL3ooAw/i0uxr/TQSaxi1l8t4iMt4/gU+W52+8Yol0JbXBTFX6itg62ppb/Eugmn\n"
                + "mQRMgL67ccZs7cJ9/A0wlXencX2ohZQOR3mtknfol3FH4+glQFn27Q4xBCzVkY9j\n"
                + "KQ20T1LgmGSngBInAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE\n"
                + "FJQOBPvrkU2In1Sjoxt97Xy8+cKNMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0B\n"
                + "AQsFAAOCAQEARgM6XwcXPLSpFdSf0w8PtpNGehmdWijPM3wHb7WZiS47iNen3oq8\n"
                + "m2mm6V3Z57wbboPpfI+VEzbhiDcFfVnK1CXMC0tkF3fnOG1BDDvwt4jU95vBiNjY\n"
                + "xdzlTP/Z+qr0cnVbGBSZ+fbXstSiRaaAVcqQyv3BRvBadKBkCyPwo+7svQnScQ5P\n"
                + "Js7HEHKVms5tZTgKIw1fbmgR2XHleah1AcANB+MAPBCcTgqurqr5G7W2aPSBLLGA\n"
                + "fRIiVzm7VFLc7kWbp7ENH39HVG6TZzKnfl9zJYeiklo5vQQhGSMhzBsO70z4RRzi\n"
                + "DPFAN/4qZAgD5q3AFNIq2WWADFQGSwVJhg==\n" + "-----END CERTIFICATE-----";
    
        public static void main(String... args) throws Exception {
            // Update this to your cluster
            String endpoint = "cb.<your endpoint address>.dp.cloud.couchbase.com";
            String bucketName = "yourBucketName";
            String username = "user";
            String password = "password";
            // User Input ends here.
    
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            trustStore.setCertificateEntry("server", decodeCertificates(Collections.singletonList(CERT)).get(0));
    
            ClusterEnvironment env = ClusterEnvironment.builder()
                    .securityConfig(
                            SecurityConfig.enableTls(true).trustManagerFactory(InsecureTrustManagerFactory.INSTANCE))
                    .ioConfig(IoConfig.enableDnsSrv(true))
                    .build();
    
            // Initialize the Connection
            Cluster cluster = Cluster.connect(endpoint, ClusterOptions.clusterOptions(username, password).environment(env));
            Bucket bucket = cluster.bucket(bucketName);
            Scope scope = bucket.defaultScope();
            Collection collection = bucket.defaultCollection();
    
            // Create a N1QL Primary Index (but ignore if it exists)
            cluster.queryIndexes().createPrimaryIndex(bucketName,
                    CreatePrimaryQueryIndexOptions.createPrimaryQueryIndexOptions().ignoreIfExists(true));
    
            // Create a JSON Document
            JsonObject arthur = JsonObject.create()
                    .put("name", "Arthur")
                    .put("email", "kingarthur@couchbase.com")
                    .put("interests", JsonArray.from("Holy Grail", "African Swallows"));
    
            // Store the Document
            collection.upsert("u:king_arthur", arthur);
    
            // Load the Document and print it
            // Prints Content and Metadata of the stored Document
            System.out.println(collection.get("u:king_arthur"));
    
            // Perform a N1QL Query
            QueryResult result = cluster.query(
                    String.format("SELECT name FROM `%s` WHERE $1 IN interests", bucketName),
                    queryOptions().parameters(JsonArray.from("African Swallows"))
            );
    
            // Print each found Row
            for (JsonObject row : result.rowsAsObject()) {
                System.out.println(row);
            }
        }
    
        public static List<X509Certificate> decodeCertificates(final List<String> certificates) {
            final CertificateFactory cf;
            try {
                cf = CertificateFactory.getInstance("X.509");
            } catch (CertificateException e) {
                throw new RuntimeException(e);
            }
            return certificates.stream().map(c -> {
                try {
                    return (X509Certificate) cf.generateCertificate(
                            new ByteArrayInputStream(c.getBytes(StandardCharsets.UTF_8))
                    );
                } catch (CertificateException e) {
                    throw new RuntimeException(e);
                }
            }).collect(Collectors.toList());
        }
    }

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Call the connect() function with a Couchbase Capella endpoint, and a ConnectOptions object containing the username, password and client certificate.


    The example below connects to a Couchbase Capella instance over a secure connection with a client certificate.

    // tag::imports[]
    var couchbase = require('couchbase')
    // end::imports[]
    
    async function main() {
      // tag::connect[]
      const clusterConnStr = 'couchbases://cb.<your-endpoint>.cloud.couchbase.com'
      const username = 'username'
      const password = 'Password!123'
      const bucketName = 'travel-sample'
    
      const cluster = await couchbase.connect(clusterConnStr, {
        username: username,
        password: password,
        // Sets a pre-configured profile called "wanDevelopment" to help avoid latency issues
        // when accessing Capella from a different Wide Area Network
        // or Availability Zone (e.g. your laptop).
        configProfile: 'wanDevelopment',
      })
      // end::connect[]
    
      // tag::bucket[]
      const bucket = cluster.bucket(bucketName)
      // end::bucket[]
    
      // tag::default-collection[]
      // Get a reference to the default collection, required only for older Couchbase server versions
      const defaultCollection = bucket.defaultCollection()
      // end::default-collection[]
    
      // tag::collection[]
      const collection = bucket.scope('tenant_agent_00').collection('users')
      // end::collection[]
    
      // tag::upsert-get[]
      const user = {
        type: 'user',
        name: 'Michael',
        email: 'michael123@test.com',
        interests: ['Swimming', 'Rowing'],
      }
    
      // Create and store a document
      await collection.upsert('michael123', user)
    
      // Load the Document and print it
      // Prints Content and Metadata of the stored Document
      let getResult = await collection.get('michael123')
      console.log('Get Result: ', getResult)
      // end::upsert-get[]
    
      // tag::query[]
      // Perform a SQL++ (N1QL) Query
      const queryResult = await bucket
        .scope('inventory')
        .query('SELECT name FROM `airline` WHERE country=$1 LIMIT 10', {
          parameters: ['United States'],
        })
      console.log('Query Results:')
      queryResult.rows.forEach((row) => {
        console.log(row)
      })
      // end::query[]
    }
    
    // tag::run-main[]
    // Run the main function
    main()
      .catch((err) => {
        console.log('ERR:', err)
        process.exit(1)
      })
      .then(process.exit)
    // end::run-main[]

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    1. Call the Cluster.connect() function with a Couchbase Capella endpoint, and a ClusterOptions object containing a PasswordAutheticator.

    2. Provide a username and password to the PasswordAutheticator.

    3. Provide a client certificate path to the PasswordAutheticator.


    The example below connects to a Couchbase Capella instance over a secure connection with a client certificate.

    # 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('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[]

    Click the GitHub button to view this code in context.

    For further details, refer to Cluster.

    Reference and explanation:

    Connecting with SDKs: