Search code examples
cassandrahector

How to update multiple rows using Hector


Is there a way I can update multiple rows in cassandra database using column family template like supply a list of keys. currently I am using updater columnFamilyTemplate to loop through a list of a keys and do an update for each row. I have seen queries like multigetSliceQuery but I don't know their equivalence in doing updates.


Solution

  • There is no utility method in ColumnFamilyTemplate that allow you to just pass a list of keys with a list of mutation in one call. You can implement your own using mutators.

    This is the basic code on how to do it in hector

    Set<String> keys = MY_KEYS;
    Map<String, String> pairsOfNameValues = MY_MUTATION_BY_NAME_AND_VALUE;
    
    Set<HColumn<String, String>> colums = new HashSet<HColumn<String,String>>();
    for (Entry<String, String> pair : pairsOfNameValues.entrySet()) {
        colums.add(HFactory.createStringColumn(pair.getKey(), pair.getValue()));
    }
    
    Mutator<String> mutator = template.createMutator();
    String column_family_name = template.getColumnFamily();
    for (String key : keys) {
        for (HColumn<String, String> column : colums) {
            mutator.addInsertion(key, BASIC_COLUMN_FAMILY, column);
        }
    }
    mutator.execute();
    

    Well it should look like that. This is an example for insertion, be sure to use the following methods for batch mutations:

    mutator.addInsertion 
    mutator.addDeletion
    mutator.addCounter
    mutator.addCounterDeletion
    

    since this ones will execute right away without waiting for the mutator.execute():

    mutator.incrementCounter
    mutator.deleteCounter
    mutator.insert
    mutator.delete
    

    As a last note: A mutator allows you to batch mutations on multiple rows on multiple column families at once ... which is why I generally prefer to use them instead of CF templates. I have a lot of denormalization for functionalities that use the "push-on-write" pattern of NoSQL.