Monday, October 8, 2012

CQL, Astyanax and Compound/Composite Keys: Writing Data

In my previous post, I showed how to connect the dots between Astyanax and CQL, but it focused primarily on reading.  Here is the update that connects the dots on write.

I created a sample project and put it out on github.  Let me know if you have any trouble.

Extending the previous example to accomodate writes, you need to use the AnnotatedCompositeSerializer when writing as well.  Here is the code:

    public void writeBlog(String columnFamilyName, String rowKey, FishBlog blog, byte[] value) throws ConnectionException {
        AnnotatedCompositeSerializer entitySerializer = new AnnotatedCompositeSerializer(FishBlog.class);
        MutationBatch mutation = keyspace.prepareMutationBatch();
        ColumnFamily columnFamily = new ColumnFamily(columnFamilyName,
                StringSerializer.get(), entitySerializer);
        mutation.withRow(columnFamily, rowKey).putColumn(blog, value, null);

Now, if you recall from the previous post, we had a single object, FishBlog, that represented the compound/composite column name:

public class FishBlog {
    @Component(ordinal = 0)
    public long when;
    @Component(ordinal = 1)
    public String fishtype;
    @Component(ordinal = 2)
    public String field;

We mapped this object to the following schema:
    CREATE TABLE fishblogs (
        userid varchar,
        when timestamp,
        fishtype varchar,
        blog varchar,
        image blob,
        PRIMARY KEY (userid, when, fishtype)

We had one member variable in FishBlog, field, that specified which piece of data we were writing: image or blog.  Because of how things work with CQL and the Java API, you actually need *two* mutations to create a row.  Here is the code from the unit test:

       AstyanaxDao dao = new AstyanaxDao("localhost:9160", "examples");
       FishBlog fishBlog = new FishBlog();
       dao.writeBlog("fishblogs", "bigcat", fishBlog, "myblog.".getBytes());
       FishBlog image = new FishBlog();
       image.when = now;
       byte[] buffer = new byte[10];
       buffer[0] = 1;
       dao.writeBlog("fishblogs", "bigcat", image, buffer);

All parts of the primary key need to be the same between the the different mutations.  Then, after you perform both mutations, you'll get a row back in CQL that looks like:

cqlsh:examples> select * from fishblogs;
 userid | when                     | fishtype | blog            | image
 bigcat | 2012-10-08 12:08:10-0400 |  CATFISH | this is myblog. | 01000000000000000000

Hopefully this clears things up for people.

No comments: