A few days ago, I set up a Cassandra node on my machine.  Time to write some code now! In this post, we’ll get started with HectorSharp, a .NET client for Cassandra.

I assume you have a Cassandra node up and running on your machine on port 9160. If you didn’t do this already, you might find this useful. You will need to download and build the HectorSharp library (I didn’t find any pre-built binaries?).

To get a first taste, here is the traditional “Hello World!”:

var clientFactory = new KeyedCassandraClientFactory(
    new CassandraClientPoolFactory().Create(),
    new KeyedCassandraClientFactory.Config());

var client = clientFactory.Make(new Endpoint("localhost", 9160));

var keyspace = client.GetKeyspace("Keyspace1");

var path = new ColumnPath("Standard1", null, "greeting");

keyspace.Insert("0", path, "Hello World!");
Column column = keyspace.GetColumn("0", path);
Console.WriteLine(column.Value);

Looks pretty straight forward. Let’s do a quick walk-through:

var clientFactory = new KeyedCassandraClientFactory(
    new  CassandraClientPoolFactory().Create(),
    new  KeyedCassandraClientFactory.Config());

We create a factory for the clients we will be using to access Cassandra. The factory takes two parameters: a pool for clients, as you’d have for database connections, and a configuration object.

var client = clientFactory.Make(new Endpoint("localhost", 9160));

The factory is used to get a client for the local machine on port 9160, where our Cassandra server is already listening and waiting for requests.

var keyspace = client.GetKeyspace("Keyspace1");

I didn’t change the out-of-the box config. It happens that the default key space name is Keyspace1.

var path = new ColumnPath("Standard1", null, "greeting");

The column path object indicates where a column is located in a family or super family. Standard1 is the family name. The second argument is null since the column we want to acess is not embedded into a super column. The last argument is the column name. If you are confused about Cassandra’s data model, you can have a look at this post.

keyspace.Insert("0", path, "Hello World!");
Column column = keyspace.GetColumn("0", path);
Console.WriteLine(column.Value);

We used the path object to put and get back the string “Hello World!”. The column family at row “0″ is now containing a key “greeting” pointing to the value “Hello World!”.

Hello World!

So far, HectorSharp seems to be doing the job. Time to write a bigger application!