A newer version of this documentation is available.

View Latest

Install and Start Using the Ruby SDK with Couchbase Server

      +
      Installing the Couchbase Ruby SDK & a Hello World example program. The Couchbase Ruby SDK allows you to connect to a Couchbase cluster from Ruby. The Ruby SDK includes high-performance native Ruby extensions to handle communicating to the cluster over Couchbase’s binary protocols.

      Ruby SDK supports currently maintained Ruby versions, and recommends the latest stable version where possible (currently 3.1 as of May 2022.)

      Hello Couchbase

      On this page we show you how to quickly get up and running — installing the Couchbase Ruby SDK, and trying out the Hello World code example against Couchbase Capella, or against a local Couchbase cluster.

      We will go through the code sample step by step, but for those in a hurry to see it, here it is:

      • Couchbase Capella Sample

      • Local Couchbase Server

      If you are connecting to Couchbase Capella, be sure to get the correct endpoint as well as user, password — and see the Cloud section, below.

      require "couchbase"
      
      # Update these credentials for your Capella instance!
      options = Cluster::Options::Cluster.new
      options.authenticate("username", "Password!123")
      cluster = Cluster.connect("couchbases://cb.njg8j7mwqnvwjqah.cloud.couchbase.com?kv_timeout=10000", options)
      
      # get a bucket reference
      bucket = cluster.bucket("travel-sample")
      
      # get a user-defined collection reference
      scope = bucket.scope("tenant_agent_00")
      collection = scope.collection("users")
      
      # Upsert Document
      upsert_result = collection.upsert(
        "my-document-key",
        {
          "name" => "Ted",
          "age" => 31
        }
      )
      p cas: upsert_result.cas
      #=> {:cas=>223322674373654}
      
      # Get Document
      get_result = collection.get("my-document-key")
      p cas: get_result.cas,
        name: get_result.content["name"]
      #=> {:cas=>223322674373654, :name=>"Ted"}
      
      result = cluster.query('SELECT "Hello World" AS greeting')
      result.rows.each do |row|
        p row
        #=> {"greeting"=>"Hello World"}
      end
      
      cluster.disconnect

      The Couchbase Capella free tier version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

      require "couchbase"
      
      # Update these credentials for your Local instance!
      options = Cluster::ClusterOptions.new
      options.authenticate("username", "Password!123")
      cluster = Cluster.connect("couchbase://db", options)
      
      # get a bucket reference
      bucket = cluster.bucket("travel-sample")
      
      # get a user-defined collection reference
      scope = bucket.scope("tenant_agent_00")
      collection = scope.collection("users")
      
      # Upsert Document
      upsert_result = collection.upsert(
        "my-document-key",
        {
          "name" => "Ted",
          "age" => 31
        }
      )
      p cas: upsert_result.cas
      #=> {:cas=>223322674373654}
      
      # Get Document
      get_result = collection.get("my-document-key")
      p cas: get_result.cas,
        name: get_result.content["name"]
      #=> {:cas=>223322674373654, :name=>"Ted"}
      
      result = cluster.query('SELECT "Hello World" AS greeting')
      result.rows.each do |row|
        p row
        #=> {"greeting"=>"Hello World"}
      end
      
      cluster.disconnect

      As well as the Ruby SDK (see below), and a running instance of Couchbase Server, you will need to load up the Travel Sample Bucket using either the Web interface or the command line.

      Quick Installation

      The source package is available through https://rubygems.org/gems/couchbase and can be installed with

      gem install couchbase

      In addition to rubygems.org, we also maintain official gem repositories, where we publish not only source version of the package, but also precompiled binaries for Linux and MacOS.

      Step-by-step

      Start a new project (in VS Code or RubyMine, etc.) and create a file cb-test.rb.

      Prerequisites

      Install the latest SDK package — see above.

      The following code samples assume:

      • Couchbase Capella cluster, or Couchbase Server is installed and accessible locally (Do a Quick Install if you don’t already have Couchbase Server installed).

      • You have create a bucket (perhaps using the travel-sample dataset, or by creating a new bucket). Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

      • You have created a Couchbase user named "username" [change as appropriate] with permissions to access the cluster (at least Application Access permissions).

      Couchbase uses Role Based Access Control (RBAC) to control access to resources. Here we will use the Full Admin role created during installation of the Couchbase Data Platform. For production client code, you will want to use more appropriate, restrictive settings, but here we want to get you up and running quickly. If you’re developing client code on the same VM or machine as the Couchbase Server, your URI can be localhost.

      Firstly, you will need to have a few import statements at the top of your Ruby program:

      require "couchbase"

      Connection

      Then you can connect to the cluster:

      • Capella Connection

      • Local Server Connection

      # Update these credentials for your Capella instance!
      options = Cluster::Options::Cluster.new
      options.authenticate("username", "Password!123")
      cluster = Cluster.connect("couchbases://cb.njg8j7mwqnvwjqah.cloud.couchbase.com?kv_timeout=10000", options)

      From 3.3, the Ruby SDK includes Capella’s standard certificates by default, so you do not need to additional configuration. You do need to enable TLS, which can be done by simply using couchbases: in the Connection String as in this example.

      # Update these credentials for your Local instance!
      options = Cluster::ClusterOptions.new
      options.authenticate("username", "Password!123")
      cluster = Cluster.connect("couchbase://db", options)

      For developing locally on the same machine as the Couchbase Server, your URI can be couchbase://localhost as here. But for Production deployments, you will want to use a secure server, with couchbases://.

      The Cluster provides access to cluster-level operations like N1Ql queries, analytics, or full-text search. You will also find different management APIs on it. If you’re developing client code on the same VM or machine as the Couchbase Server, your connection string can be just localhost.

      If you are connecting to Couchbase Capella rather than a local Couchbase Server, then also refer to the Cloud section, below.

      Couchbase uses Role Based Access Control (RBAC) to control access to resources. For production client code, you will want to use more appropriate, restrictive settings — but here we want to get you up and running quickly, so you can use the Full Admin role created during installation of the Couchbase Data Platform, in which case set Administrator as the username, and use the password that you defined in setting up your test Couchbase cluster.

      Bucket, Scopes, and Collections

      Open the bucket:

      # get a bucket reference
      bucket = cluster.bucket("travel-sample")

      Collections allow Documents to be grouped by purpose or theme, according to specified Scope. Our Travel Sample bucket has separate scopes for inventory (flights, etc.), and for tenants (different travel agents).

      # get a user-defined collection reference
      scope = bucket.scope("tenant_agent_00")
      collection = scope.collection("users")

      To get you started the following code creates a new document in a custom scope and collection and then fetches it again, printing the result.

      # Upsert Document
      upsert_result = collection.upsert(
        "my-document-key",
        {
          "name" => "Ted",
          "age" => 31
        }
      )
      p cas: upsert_result.cas
      #=> {:cas=>223322674373654}
      
      # Get Document
      get_result = collection.get("my-document-key")
      p cas: get_result.cas,
        name: get_result.content["name"]
      #=> {:cas=>223322674373654, :name=>"Ted"}

      Other possible key/value CRUD Operations are described in detail on the KV Operations page.

      You can also perform a N1QL query with the cluster object:

      result = cluster.query('SELECT "Hello World" AS greeting')
      result.rows.each do |row|
        p row
        #=> {"greeting"=>"Hello World"}
      end

      You can learn more about N1QL queries on the Query page.

      After completing operations, finish with (otherwise resources will be released by garbage collector):

      cluster.disconnect

      Cloud Connections

      For developing on Couchbase Capella, if you are not working from the same Availability Zone as your Capella instance, refer to the following:

      Additional Resources

      The API reference is generated for each release and can be found here. Older API references are linked from their respective sections in the Release Notes.

      Couchbase welcomes community contributions to the Ruby SDK. The Ruby SDK source code is available on GitHub.

      Troubleshooting