Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Working with counter columns

Frisovdm edited this page · 3 revisions
Clone this wiki locally

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();
Something went wrong with that request. Please try again.