Example about how to use map cql type with DataStax java driver

ftrujillo picture ftrujillo · Dec 3, 2013 · Viewed 15.4k times · Source

I am trying to use the datastax java driver to update and query a column family that has a map field. Does anyone an example about how to use cql collections with the Datastax Java Driver?

Thanks

Answer

Aaron picture Aaron · Dec 3, 2013

Normally I'd ask what you've tried, but I know that this isn't in the DataStax documentation for the Java Driver. I'll go through what worked for me.

A couple of things to note:

  • The DataStax Cassandra Java class directed me to put my variables directly into the CQL text string (instead of binding the map). I'm guessing that binding collections wasn't working at the time of production (for the class videos).
  • Collections can't be queried using DevCenter, so you'll need to check their values via the command line with cqlsh if you want to see what they are outside your app.

To update an existing row (in the "users" table which has a Map<varchar,varchar> phone_numbers), try something like this:

String cqlQuery = "UPDATE users SET phone_numbers = phone_numbers + ";
cqlQuery += "{'" + phoneType + "':'" + phoneNumber+ "'} ";
cqlQuery += "WHERE username = ?";

PreparedStatement preparedStatement = getSession().prepare(cqlQuery);
BoundStatement boundStatement = preparedStatement.bind(user);
getSession().execute(boundStatement);

The better way to do this (assuming a Map<String,String> phoneNumbers), is to bind the collection to the prepared statement, like this:

String cqlQuery = "UPDATE users SET phone_numbers = ? ";
cqlQuery += "WHERE username = ?";

PreparedStatement preparedStatement = getSession().prepare(cqlQuery);
BoundStatement boundStatement = preparedStatement.bind(phoneNumbers,user);
getSession().execute(boundStatement);

Likewise, to read it back out:

String cqlQuery2 = "SELECT phone_numbers FROM users WHERE username = ?";

PreparedStatement preparedStatement2 = getSession().prepare(cqlQuery2);
BoundStatement boundStatement2 = preparedStatement2.bind(user);
ResultSet result2 = getSession().execute(boundStatement2);

Map<String,String> newMap = result2.one().getMap("phone_numbers", String.class, String.class);

They just covered this today in the (free) CAS101J class on DataStax Academy.