Encoding Dynamic Maps for Cassandra in JavaScript

Cassandra is a scalable NoSQL database system first developed by Facebook. Within its implementation, it includes a query language similar to SQL called CQL, which can be used for pretty much any data operation. This language uses a data type similar to JSON called maps.

While its implementation makes sense for the most part, a prominent issue that I found while implementing the dynamic creation of keyspaces and column families is that there is no simple way of converting a JavaScript object to a valid Cassandra map, mainly because it only accepts single quotes for key names and values, while the common JSON.stringify(...) outputs double-quoted strings. Therefore, while something like the following should work, it doesn’t:

var query = "CREATE KEYSPACE name WITH REPLICATION=";
var replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
query += JSON.stringify(replication);

This will not create a valid query. The cassandra server will complain about the double quotes generated by the JSON method and will fail the query.

Fortunately, I went through the trouble of creating a pseudo-JSON implementation in JavaScript that outputs valid CQL maps, which I call cassandraMAP. With it, converting JS data types into valid Cassandra map strings is as easy as this:

var cassandraMAP = require("cassandra-map");
var query = "CREATE KEYSPACE name WITH REPLICATION=";
var replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
query += cassandraMAP.stringify(replication);

That is, assuming you are running Node.js and have installed the cassandra-map module. There are instructions on the GitHub page for using the library in other environments.

Although the library doesn’t do much, it gets rid of the annoying issue of generating valid dynamic CQL-compliant maps that can be used to generate successful queries.

Keep querying,
Juan Camilo Osorio