Working with counter columns - marcusbb/astyanax GitHub Wiki
Cassandra supports counter columns which implement a distributed count.
public static final ColumnFamily<Long, String> CF_COUNTER1 =
new ColumnFamily<Long, String>(
"CounterColumnFamily",
LongSerializer.get(),
StringSerializer.get());
To increment using the single column mutator.
keyspace.prepareColumnMutation(CF_COUNTER1, rowKey, "CounterColumn1")
.incrementCounterColumn(1)
.execute();
To increment using the batch mutator
MutationBatch m = keyspace.prepareMutationBatch();
m.withRow(CF_COUNTER1, rowKey)
.incrementCounterColumn("MyCounter", 100);
m.execute();
Counter column values are retrieved using the same call as regular column except for that all calls except for getLongValue() will throw an exception.
Column<String> result = keyspace.prepareQuery(CF_COUNTER1)
.getKey(rowKey),
.getColumn("Column1"),
.execute().getResult();
Long counterValue = result.getLongValue();
To clear a counter first read the value and then add the negative of that value. Counter columns do not have TTL. They can be explicitly deleted using the following:
keyspace.prepareColumnMutation(CF_COUNTER1,key,columnName).deleteCounterColumn().execute();