gocql is the cassandra driver for the go programming language. It support for all common cassandra data types including
udt etc. Custom types can implement a
Unmarshaler interface. It built-in support for UUIDs, cluster management, TLS/SSL communication, automatic query preparation, etc.
On my previous post I have discussed about building cassandra scala client application. In this post I will discuss about building cassandra golang client application with using gocql package. All source codes which relates to this post available on gitlab. Please clone the repository and continue the post.
I have run Cassandra with
Elassandra docker image. Elassandra built by combining Elasticseach with Cassandra. It comes Elasticsearch as a Cassandra plugin. Basically it has Cassandra API as well as Elasticsearch API. When data save on Cassandra it will automatically index on Elasticsearch. Read more about elassandra from here. Following is the
docker-compose.yml to run the elassandra.
Now I can run the Elassandra with following commands. It will start Cassandra on my local machine. I can access the Cassandra via
Cqlsh inside the Elassandra docker container.
In cassandra I have a keyspace named
mystiko and table a named
documents. documents table contains a
signatures. Following are the schemas.
I have used
gocql (golang cassandra client driver) and
mapstructure (golang library for decoding generic map values to structures and vice versa) libraries. Following is the way to install these libraries
The cassandra configurations defined in
config.go file. It contains
keyspace etc informations. There configurations can be loaded via environment variables(12factor apps)
I have defined the
signatures in cassandra schema as
struct types. These struct objects used when creating/querying the documents on cassandra.
In order to interact with cassandra, I need to create a
gocql.Session with cassandra cluster configurations.
gocql.Session is safe for concurrent use by multiple goroutines and a typical usage scenario is to have one global session object to interact with the whole Cassandra cluster(no need to create connection pool).
Following are the various query function that I have defined to create, update, search documents.
Following is the main application(
main.go) which executes these queries. It first initialize the session, then execute queries and finally close the session.