I use Docker:
1 2 3 |
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:
1 2 |
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:
1 2 3 4 |
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:
1 |
cqlsh 192.168.99.100 32769 |
Now we can create the keyspace:
1 2 3 |
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.
1 |
go get github.com/gocql/gocql |
Our code is pretty simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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