CQL for Cassandra 1.2

Using a counter

A counter is a special kind of column used to store a number that incrementally counts the occurrences of a particular event or process. For example, you might use a counter column to count the number of times a page is viewed.

Counter column tables must use Counter data type. Counters may only be stored in dedicated tables. You cannot index a counter column.

You load data into a counter column using the UPDATE command instead of INSERT. To increase or decrease the value of the counter, you also use UPDATE.

Procedure

  1. Create a keyspace on Linux for use in a single data center. Use the default data center name from the output of nodetool status, for example datacenter1.
  2. Create a table for the counter column.
    CREATE KEYSPACE counterks WITH REPLICATION =
    { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 };
    
    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