tags | |
---|---|
|
This guide explains how to use Couchbase Go SDK to store and retrieve a JSON document in Couchbase Server.
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.
-
15-30 minutes
-
A Go code editor
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.
Status shows that the index was successfully created.
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.
-
Download and Install XCode.
-
Install the XCode CLI tools as
xcode-select --install
. -
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 yourPATH
environment variable. You may need to restart any open Terminal sessions for the change to take effect. -
Create a directory
Go
in your home directory and setGOPATH
to that directory. -
Now you are ready to install Couchbase Go SDK:
go get gopkg.in/couchbase/gocb.v1
This will install the Couchbase Go packages.
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.
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.
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.