Cassandra prepared statements
Cassandra supports prepared statements, which can compile once and run multiple times. When prepare the statement, Cassandra will parse the query string, cache the result and return a unique identifier (the
PreparedStatement object keeps an internal reference to that identifier). When you bind and execute a prepared statement, the driver will only send the identifier, which allows Cassandra to skip the parsing phase.
In this post I will discuss about how to use cassandra prepared statements with
scala to do query operations. On my previous post I have discussed about using
CQL queries to do querying from cassandra. 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.
IntelliJ Idea as my IDE to work with Scala applications. I need to create
sbt project and add the
build.sbt dependency file with
cassandra and other dependencies. Following is the
build.sbt dependency file.
The cassandra configurations defined in
cassandra.conf file. It contains
keyspace etc informations.
These configs load into
CassandraConf.scala trait and use to create the cassandra
Then I need to create a cassandra
session which can use to execute queries. I have defined
I have defined the
signatures in cassandra schema as
case class objects. These objects used when creating/querying the documents on cassandra.
To create a document, I have bind the values to create document prepared statement and execute it. Since document contains
SET, I need to convert
When querying the document I need to convert
SET into scala
Following is the prepared statement and function to use update the document. It simply binds update fields in prepared statement and execute.
tags field is a
SET in cassandra. Following are the prepared statements and functions to add/remove tags to the document.
signatures field is a
SET in cassandra. Cassandra does not support to bind prepared statements in UDT type collections. Due to this reason I have used
QueryBuilder to add/remove signatures into the document.