Skip to content

Working with counter columns

Frisovdm edited this page May 2, 2013 · 3 revisions

Cassandra supports counter columns which implement a distributed count.

Command to create a counter column family via the CLI

See Cassandra Counter Columns

Defining the ColumnFamily for a counter column

public static final ColumnFamily<Long, String> CF_COUNTER1 =
    new ColumnFamily<Long, String>(
        "CounterColumnFamily",
        LongSerializer.get(),
        StringSerializer.get());

Incrementing counter columns

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();

Querying counter column values

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();

Clearing a counter

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();
Clone this wiki locally