Skip to content

Instantly share code, notes, and snippets.

@jung-kim
Created June 20, 2017 17:17
Show Gist options
  • Save jung-kim/b004452a4b2168bf887331eff468d469 to your computer and use it in GitHub Desktop.
Save jung-kim/b004452a4b2168bf887331eff468d469 to your computer and use it in GitHub Desktop.
big table emulator test
package main
import (
"context"
"log"
"cloud.google.com/go/bigtable"
)
const (
col1 = "col1"
col2 = "col2"
colFam = "f1"
tablename = "test-table"
)
var (
client *bigtable.Client
ctx context.Context
)
func main() {
ctx = context.Background()
////////////////////////////////////////////////////////
// Test env setup, create table and create column fam //
////////////////////////////////////////////////////////
adminClient, err := bigtable.NewAdminClient(
ctx,
"proj",
"instance",
)
if err != nil {
log.Fatal("Couldn't get client", err)
}
err = adminClient.CreateTable(ctx, tablename)
if err != nil {
log.Println("WARN Couldn't create a table", err)
}
err = adminClient.CreateColumnFamily(ctx, tablename, colFam)
if err != nil {
log.Println("WARN Couldn't create column fam", err)
}
////////////////////////////////////////////////
// Open table, write a row, and read all rows //
////////////////////////////////////////////////
client, err := bigtable.NewClient(
ctx,
"proj",
"instance",
)
if err != nil {
log.Fatal("Couldn't get client", err)
}
btTable := client.Open(tablename)
err = write(btTable, "abc.1", "a", "b") // add row 1
if err != nil {
log.Fatal("Couldn't write a row", err)
}
rr := bigtable.PrefixRange("abc.")
err = btTable.ReadRows(ctx, rr, func(r bigtable.Row) bool {
// do something with r
log.Println(r)
return true // keep going
}, bigtable.RowFilter(bigtable.FamilyFilter(colFam)))
if err != nil {
log.Fatal("Couldn't read rows", err)
}
}
// write two column values for a row key to a table
func write(table *bigtable.Table, rowKey string, val1 string, val2 string) error {
mut := bigtable.NewMutation()
mut.Set(colFam, col1, bigtable.Now(), []byte(val1))
mut.Set(colFam, col2, bigtable.Now(), []byte(val2))
return table.Apply(ctx, rowKey, mut)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment