I use Docker:
docker pull cassandra
mkdir ucs-cassandra-db
docker run -d -P --name cassandra -v `pwd`/ucs-cassandra-db/:/var/lib/cassandra cassandra
(Notice that using boot2docker or docker machine on virtual box doesn't work very well because the directories are created under different user name. You have two choices: Don't mount persistent directories with boot2docker or log into the virtual box guest (docker-machine ssh dev) and launch the container there.)
Make sure its up:
docker inspect cassandra
docker logs cassandra
Now lets create a Keyspace (or Database in SQL terms). Connect to it by connecting to cassandra where the 9042 port is mapped:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1ec821d4f59 cassandra "/docker-entrypoint.s" 34 minutes ago Up 34 minutes 0.0.0.0:32772->7000/tcp, 0.0.0.0:32771->7001/tcp, 0.0.0.0:32770->7199/tcp, 0.0.0.0:32769->9042/tcp, 0.0.0.0:32768->9160/tcp cassandra
Here we see that port 9042 is mapped to 32769. To connect we run:
cqlsh 192.168.99.100 32769
Now we can create the keyspace:
cqlsh> CREATE KEYSPACE ucstechspecs WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '1' };
cqlsh> USE ucstechspecs;
cqlsh> CREATE TABLE fabricInterconnects (partNumber text, name text, attributes map<text, text>, pictures list<text>, PRIMARY KEY (partNumber));
Now let's use it with a Go program.
go get github.com/gocql/gocql
Our code is pretty simple:
package main
import (
"fmt"
"log"
"github.com/gocql/gocql"
)
func main() {
fmt.Printf("Test\n")
cluster := gocql.NewCluster("192.168.99.100")
cluster.Port = 32869
cluster.ProtoVersion = 4
cluster.Keyspace = "ucstechspecs"
session, err := cluster.CreateSession()
defer session.Close()
if err != nil {
fmt.Printf("%s\n", err)
return
}
m := make(map[string]string)
m["color"] = "red"
m["car"] = "ferrari"
pictures := []string{"http://fi.1.org", "http://lmgtfy"}
err = session.Query(`INSERT INTO fabricInterconnects (partNumber, name, attributes, pictures) VALUES (?, ?, ?, ?)`,
"UCSFI-61234", "UCS FI 6120", m, pictures).Exec()
log.Println("Inserted data")
if err != nil {
log.Fatal(err)
}
var model string
iter := session.Query(`SELECT name FROM fabricInterconnects WHERE partNumber = ? `,
"UCSFI-61234").Iter()
for iter.Scan(&model) {
fmt.Println("Model: ", model)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
}
If that worked then you created an entry and go data back. You are now off to the races writing golang code to a cassandra database.
TODO:
- Scale out to multiple cassandra servers
- Show how this works in mantil.io