Search code examples
cassandracomposite-keyhector

How to define composite key for a column family and then reference it using Hector?


where can I find samples for this?

Most of my code using ColumnFamilyTemplate to do CRUD on the data records, see below. Once I have the composite key defined, can I still use ColumnFamilyTemplate to access my data having composite keys?

private static final ColumnFamilyTemplate<UUID, String> template = 
    new ThriftColumnFamilyTemplate<UUID, String>(
        Bootstrap.keyspace, 
        "User", 
        UUIDSerializer.get(), 
        StringSerializer.get(),
        HFactory.createMutator(Bootstrap.keyspace, UUIDSerializer.get()));

Solution

  • It shouldn't matter which API you use to do the CRUD on the records; CompositeType (or DynamicCompositeType) is just another type (e.g. similar to UUID) which has a corresponding serializer (CompositeSerializer). So, your example might become:

    private static final ColumnFamilyTemplate<Composite, String> template = 
    new ThriftColumnFamilyTemplate<Composite, String>(
        Bootstrap.keyspace, 
        "User", 
        CompositeSerializer.get(), 
        StringSerializer.get(),
        HFactory.createMutator(Bootstrap.keyspace, CompositeSerializer.get()));
    

    Only extra would be to create the Composite before using template (assume composite of UUID & Long):

    Composite key = new Composite();
    key.addComponent(someUUID, UUIDSerializer.get());
    key.addComponent(someLong, LongSerializer,get());
    ColumnFamilyResult<Composite,String> result = template.queryColumns(key);
    

    When fetching results, one way to get the components of the key:

    myUUID = result.getKey().get(0, UUIDSerializer.get());
    myLong = result.getKey().get(1, LongSerializer,get());