Created
June 30, 2014 16:14
-
-
Save beccam/0aa0c6fa28d9341fe32c to your computer and use it in GitHub Desktop.
Getting Started with Apace Cassandra and Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/gocql/gocql" | |
) | |
func main() { | |
// connect to the cluster | |
cluster := gocql.NewCluster("127.0.0.1") | |
cluster.Keyspace = "demo" | |
session, _ := cluster.CreateSession() | |
defer session.Close() | |
// insert a user | |
if err := session.Query("INSERT INTO users (lastname, age, city, email, firstname) VALUES ('Jones', 35, 'Austin', '[email protected]', 'Bob')").Exec(); err != nil { | |
log.Fatal(err) | |
} | |
// Use select to get the user we just entered | |
var firstname, lastname, city, email string | |
var age int | |
if err := session.Query("SELECT firstname, age FROM users WHERE lastname='Jones'").Scan(&firstname, &age); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(firstname, age) | |
// Update the same user with a new age | |
if err := session.Query("UPDATE users SET age = 36 WHERE lastname = 'Jones'").Exec(); err != nil { | |
log.Fatal(err) | |
} | |
// Select and show the change | |
iter := session.Query("SELECT firstname, age FROM users WHERE lastname='Jones'").Iter() | |
for iter.Scan(&firstname, &age) { | |
fmt.Println(firstname, age) | |
} | |
if err := iter.Close(); err != nil { | |
log.Fatal(err) | |
} | |
// Delete the user from the users table | |
if err := session.Query("DELETE FROM users WHERE lastname = 'Jones'").Exec(); err != nil { | |
log.Fatal(err) | |
} | |
// Show that the user is gone | |
session.Query("SELECT * FROM users").Iter() | |
for iter.Scan(&lastname, &age, &city, &email, &firstname) { | |
fmt.Println(lastname, age, city, email, firstname) | |
} | |
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
Hi - thanks for putting together this gist. Very helpful. One thing to note is that with the release of DSE 5 and/or when using Cassandra 3, you need to configure gocql to use protocol 4. I added the following line after setting the keyspace:
cluster.ProtoVersion = 4
And now everything works fine on the latest versions.