Reputation: 8119
The recently released gocb lib (the official golang client for couchbase) offers API for performing bulk operations (Get, Delete, etc). I would love to see a complete example of such an operation, alas - my go skills are lacking and there's nothing online.
I'd like to see a snippet that (1) compiles and (2) performs multi-get and finally (3) manages to access the values returned from couchbase.
here's what little documentation exists online: http://developer.couchbase.com/documentation/server/4.0/sdks/go-beta/bulk-operations.html
the following code (which performs insert) is not enough: I want Get (and specifically - how one would review the contents of the get-operation results).
myBucket, _ := myCluster.OpenBucket("default", "")
var items []gocb.BulkOp
items = append(items, &gocb.InsertOp{Key: "document_name_1", Value: "Hello World 1"})
items = append(items, &gocb.InsertOp{Key: "document_name_2", Value: "Hello World 2"})
err := bucket.Do(items)
Upvotes: 3
Views: 1633
Reputation: 11
This is a working version, but I think it's quite verbose
package main
import (
"fmt"
"gopkg.in/couchbase/gocb.v1"
)
const (
COUCH_OP_COUNT = 3
)
// data interchange with Couchbase store
type StorageUrl struct {
Url string
}
func storeThings(b *gocb.Bucket) {
var ops []gocb.BulkOp
for i := 0; i < COUCH_OP_COUNT; i++ {
k := fmt.Sprintf("key_%v", i)
ops = append(ops, &gocb.UpsertOp{
Key: k,
Value: StorageUrl{Url: fmt.Sprintf("http://www.i-%v.com", i)},
})
}
b.Do(ops)
}
func fetchThings(b *gocb.Bucket) {
var err error
var ops []gocb.BulkOp
var results []interface{}
for i := 0; i < COUCH_OP_COUNT; i++ {
k := fmt.Sprintf("key_%v", i)
results = append(results, &StorageUrl{})
ops = append(ops, &gocb.GetOp{
Key: k,
Value: results[i],
})
}
err = b.Do(ops)
if err != nil {
fmt.Println(err)
return
}
for _, op := range ops {
getOp := op.(*gocb.GetOp)
v := getOp.Value.(*StorageUrl)
fmt.Println(v)
}
}
func main() {
cluster, err := gocb.Connect("couchbase://127.0.0.1")
if err != nil {
fmt.Println(err)
return
}
bucket, err := cluster.OpenBucket("test", "")
if err != nil {
fmt.Println(err)
return
}
storeThings(bucket)
fetchThings(bucket)
}
Upvotes: 1
Reputation: 24818
Just replace the *InsertOp
values with *GetOp
values, then read their Value
field:
package main
import "fmt"
import "gopkg.in/couchbaselabs/gocb.v1"
func main() {
getKeys()
}
func getKeys() {
myCluster, err := gocb.Connect("couchbase://<couchbase-address>")
if err != nil {
fmt.Println("cluster error:", err)
}
myBucket, err := myCluster.OpenBucket("Test", "") //case sensitive!
if err != nil {
fmt.Println("bucket error:", err)
}
var items []gocb.BulkOp
items = append(items, &gocb.GetOp{Key: "document_name_1"})
items = append(items, &gocb.GetOp{Key: "document_name_2"})
err = myBucket.Do(items)
if err != nil {
fmt.Println("Do error:", err)
panic(err)
}
for _, g := range items {
//"downcast" the instance back to its concrete type - GetOp
t := g.(*gocb.GetOp)
fmt.Println(t)
}
}
Upvotes: 1