Skip to content

Instantly share code, notes, and snippets.

@0x6e6562
Created January 31, 2014 08:21
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save 0x6e6562/8728333 to your computer and use it in GitHub Desktop.
Save 0x6e6562/8728333 to your computer and use it in GitHub Desktop.
Simple gocql batch example
package main
import (
"github.com/tux21b/gocql"
"log"
)
// create table foo (
// bar bigint,
// baz ascii,
// primary key (bar)
// );
func main() {
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "logs_ks"
session, err := cluster.CreateSession()
if err != nil {
log.Panic(err)
}
batch := gocql.NewBatch(gocql.LoggedBatch)
stmt := "INSERT INTO foo (bar,baz) VALUES (?,?)"
for i := 0; i < 10000; i++ {
batch.Query(stmt, i, "foo")
if i%50 == 0 {
err = session.ExecuteBatch(batch)
if err != nil {
log.Panic(err)
}
batch = gocql.NewBatch(gocql.LoggedBatch)
}
}
err = session.ExecuteBatch(batch)
if err != nil {
log.Panic(err)
}
}
@gabsn
Copy link

gabsn commented May 31, 2018

Be careful, you're batching queries with different partition keys, which is an anti-pattern that can lead to poor performance: https://docs.datastax.com/en/cql/3.3/cql/cql_using/useBatchBadExample.html

@rsj123
Copy link

rsj123 commented Apr 12, 2022

In the line 23 and 34
gocql.NewBatch(gocql.LoggedBatch)
Use session.NewBatch instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment