Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cassandra and gocql quick start
/*
* Assuming a schema similar to the Cassandra wiki quick start (http://wiki.apache.org/cassandra/GettingStarted):
* CREATE TABLE mykeyspace.users (
* user_id int PRIMARY KEY,
* fname text,
* lname text,
* user_id int
* )
*
* RETURNs THIS:
* ID=300 USERS: johan blingers
* LNAME='smith' USERS: john 1745
* LNAME='smith' USERS: patty 1744
* ID in(ids) USERS: johan 300
* ID in(ids) USERS: patty 1744
* ID in(ids) USERS: john 1745
* ID in(ids) USERS: patty 1746
*/
package main
import (
"fmt"
"log"
"tux21b.org/v1/gocql"
)
func main() {
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "mykeyspace"
cluster.Consistency = gocql.Quorum
session, session_err := cluster.CreateSession()
if session_err != nil {
log.Fatal(session_err)
}
defer session.Close()
cql_insert := `INSERT INTO users (fname, lname, user_id) VALUES (?, ?, ?)`
fname := "johan"
lname := "blingers"
user_id := 300
// insert a tweet
if err := session.Query(cql_insert, fname, lname, user_id).Exec(); err != nil {
log.Fatal(err)
}
var first_name string
var last_name string
var userid int
/* NOTE:: returning vars like '&first_name' is BAD because value can be set in first query and returned in later queries...
*/
// select a single tweet
if err := session.Query(`SELECT fname, lname FROM users WHERE user_id = ? LIMIT 1`,
300).Consistency(gocql.One).Scan(&first_name, &last_name); err != nil {
log.Fatal(err)
}
fmt.Println("ID=300 USERS:", first_name, last_name)
// list all given last name
iter := session.Query(`SELECT fname, user_id FROM users WHERE lname = ?`, "smith").Iter()
for iter.Scan(&first_name, &userid) {
fmt.Println("LNAME='smith' USERS:", first_name, userid)
}
ids := [...]int{300, 1744, 1745, 1746}
// list all users given range of ids
iter_two := session.Query(`SELECT fname, user_id FROM users WHERE user_id IN ?`, ids).Iter()
for iter_two.Scan(&first_name, &userid) {
fmt.Println("ID in(ids) USERS:", first_name, userid)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.