CQL for Cassandra 2.x

Using a counter

A counter is a special column used to store a number that is changed in increments. For example, you might use a counter column to count the number of times a page is viewed.

Cassandra 2.1 counter column improves the implementation of counters and provides a number of configuration options to tune counters. In Cassandra 2.1 and later, you can configure how long the coordinator can wait for counter writes to complete, the size of the counter cache in memory, how long Cassandra waits before saving counter cache keys, the number of keys to save, and concurrent_counter_writes. You set the options in the cassandra.yaml file. The replicate_on_write table property used by the Cassandra 2.0.x counter implementation has been removed from Cassandra 2.1.

Define a counter in a dedicated table only and use the counter data type. You cannot index, delete, or and re-adding a counter column.

To load data into a counter column, or to increase or decrease the value of the counter, use the UPDATE command. Cassandra rejects USING TIMESTAMP or USING TTL in the command to update a counter column.

Procedure

  1. Create a keyspace. For example, on Linux create a keyspace for use in a single data center having a replication factor of 3. Use the default data center name from the output of the nodetool status command, for example datacenter1.
    CREATE KEYSPACE counterks WITH REPLICATION =
    { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 };
    
  2. Create a table for the counter column.
     
    CREATE TABLE counterks.page_view_counts
      (counter_value counter,
      url_name varchar,
      page_name varchar,
      PRIMARY KEY (url_name, page_name)
    );
  3. Load data into the counter column.
    UPDATE counterks.page_view_counts
     SET counter_value = counter_value + 1
     WHERE url_name='www.datastax.com' AND page_name='home';
  4. Take a look at the counter value.
    SELECT * FROM counterks.page_view_counts;
    Output is:
     url_name         | page_name | counter_value
    ------------------+-----------+---------------
     www.datastax.com |      home |             1
  5. Increase the value of the counter.
    UPDATE counterks.page_view_counts
      SET counter_value = counter_value + 2
      WHERE url_name='www.datastax.com' AND page_name='home';
  6. Take a look at the counter value.
     url_name         | page_name | counter_value
    ------------------+-----------+---------------
     www.datastax.com |      home |             3
Show/hide