Start Using the SDK
Edit this article in GitHub
Version 2.2

Start Using the SDK

The Couchbase Go SDK allows you to connect to a Couchbase cluster from Go. It is a native Go library and uses the high-performance gocbcore to handle communicating to the cluster over Couchbase’s binary protocols

Installation

You can install the SDK via go get
$ go get gopkg.in/couchbase/gocb.v1

Information on new features, fixes, known issues as well as information on how to install older release versions is in the release notes.

Hello Couchbase

Once you've installed the SDK you can run this simple code snippet showcasing some of its features.
  • Error checking has been omitted for brevity.
  • Replace localhost with the IP or hostname of a cluster node, if the host running the example is not also a Couchbase node.
package main

import (
	"fmt"
	"gopkg.in/couchbase/gocb.v1"
)

type User struct {
	Id string `json:"uid"`
	Email string `json:"email"`
	Interests []string `json:"interests"`
}

func main() {
        cluster, _ := gocb.Connect("couchbase://localhost")
        bucket, _ := cluster.OpenBucket("default", "")
        
        bucket.Manager("", "").CreatePrimaryIndex("", true, false)
        
        bucket.Upsert("u:kingarthur",
                User{
                        Id: "kingarthur",
                        Email: "kingarthur@couchbase.com",
                        Interests: []string{"Holy Grail", "African Swallows"},
                }, 0)
        
        // Get the value back
        var inUser User
        bucket.Get("u:kingarthur", &inUser)
        fmt.Printf("User: %v\n", inUser)
        
        // Use query
        query := gocb.NewN1qlQuery("SELECT * FROM default WHERE $1 IN interests")
        rows, _ := bucket.ExecuteN1qlQuery(query, []interface{}{"African Swallows"})
        var row interface{}
        for rows.Next(&row) {
                fmt.Printf("Row: %v", row)
        }
}

The above example demonstrates the upsert, get, and N1QL query functionality as used in the Go SDK. First a Cluster object is created with the address of a cluster node, then a connection to a data bucket is opened in the form of Cluster.OpenBucket.

Data operations are performed against Bucket objects. In this case a document is stored into the cluster using Bucket.Upsert. The document is then retrieved using its ID (primary key) using the Bucket.Get, and lastly it is queried with the N1QL query language using Bucket.ExecuteN1qlQuery.

The above example also shows how you can use your own document types. Note that JSON annotations are not required for operations, but demonstrate how existing objects may fit into your application.

Additional Resources