/go-sdk

Getting Started with Go and Couchbase

Primary LanguageGo

tags
go-sdk

This guide explains how to use Couchbase Go SDK to store and retrieve a JSON document in Couchbase Server.

What you’ll build

Couchbase is an open source NoSQL document database. It can be programmed using a variety of languages. This guide will show how to write a simple Go application to store a JSON document representing a Book JSON document in Couchbase Server using the Couchbase Go SDK.

What you’ll need

Setup

Install and Start Couchbase

Install and start Couchbase for your operating system as explained at: http://developer.couchbase.com/documentation/server/current/getting-started/installing.html. A default bucket by the name default is created.

Open Couchbase Web Console at http://localhost:8091, go to the Query tab, create a primary index using CREATE PRIMARY INDEX on default and click on Execute button to create the index.

couchbase default bucket create index

Status shows that the index was successfully created.

Install Go Client SDK

Couchbase Go Client SDK can be installed on different operating systems. Complete set of instructions are available at http://developer.couchbase.com/documentation/server/current/sdk/go/start-using-sdk.html. OSX specific instructions are given below.

Go Client SDK on OSX requires to install Go language programming language distribution. This in turn requires to install XCode and the process could take a few minutes depending upon your connectivity. If you already have XCode and Go installed, then you can skip the first few steps.

  1. Download and Install XCode.

  2. Install the XCode CLI tools as xcode-select --install.

  3. Download Go package installer, open it and follow the prompts to install it. The package installs the Go distribution in the /usr/local/go directory.

    The installer adds /usr/local/go/bin directory in your PATH environment variable. You may need to restart any open Terminal sessions for the change to take effect.

  4. Create a directory Go in your home directory and set GOPATH to that directory.

  5. Now you are ready to install Couchbase Go SDK:

    go get gopkg.in/couchbase/gocb.v1

    This will install the Couchbase Go packages.

Code

Create Application

In your favorite editor, create a new file app.go. Copy the following code in that file:

package main

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

type Book struct {
	isbn string `json:"isbn"`
	name string `json:"name"`
	cost string `json:"cost"`
}

func main() {
	cluster, _ := gocb.Connect("couchbase://localhost")
	bucket, _ := cluster.OpenBucket("default", "")

	bucket.Upsert("u:book1",
		Book{
			isbn: "978-1-4919-1889-0",
			name: "Minecraft Modding with Forge",
			cost: "29.99",
		}, 0)

	// Get the value back
	var inBook Book
	bucket.Get("u:book1", &inBook)
	fmt.Printf("Book: %v\n", inBook)

	// Use query
	query := gocb.NewN1qlQuery("SELECT * FROM default")
	rows, err := bucket.ExecuteN1qlQuery(query, nil)
	if (err != nil) {
		fmt.Printf(err.Error())
		return;
	}
	var row interface{}
	for rows.Next(&row) {
		fmt.Printf("Row: %v", row)
	}
}

Couchbase Go library, defined by gopkg.in/couchbase/gocb.v1 package, is used in this class.

A new Go struct named Book is defined that mimics the JSON document structure. Connect method creates a connection to the Couchbase Server running on localhost. The default bucket is opened using the OpenBucket method. A fresh install of Couchbase has an empty default bucket.

Upsert method inserts or replaces a JSON document in the bucket. So the document will be inserted for the first run. Subsequent runs of this application will replace the document. In this method, a key book1 is given to uniquely identify the document. The document itself is the JSON fragment and is the second parameter of the method.

The inserted document can be easily accessed using bucket.Get() method by passing the key used during creation. A new N1QL query is created to retrieve all documents from the database. The result is stored in rows and errors in err variable.

Any error messages are printed and the program is terminated. Finally, if there are no errors messages then all documents are looped using the Next method and printed.

Run

Build Application

Open a terminal or command prompt and give the following command to build the application:

go buid app.go

This will compile the source code and generate the binary file.

Run Application

In the same directory, run the application by giving the command:

app

It will show the output as:

Book: {978-1-4919-1889-0 Minecraft Modding with Forge 29.99}
Row: map[default:map[name:Minecraft Modding with Forge cost:29.99 isbn:978-1-4919-1889-0]]

The first result comes from bucket.Get("u:book1", &inBook) method. The second line comes from executing the N1QL query and iterating over all the documents.

Summary

Congratulations! You set up a Couchbase server and wrote a simple Go application that stores and retrieves a JSON document in Couchbase.