Using a counter
A counter is a special column for storing a number that is changed in increments.
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.
Apache 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.
Define a counter in a dedicated table only and use the counter data type. You cannot index, delete, or re-add a counter column. All non-counter columns in the table must be defined as part of the primary key.
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
-
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 };
-
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) );
-
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';
-
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
-
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';
-
Take a look at the counter value.
url_name | page_name | counter_value ------------------+-----------+--------------- www.datastax.com | home | 3