A counter is a special column for storing a number that is changed in
increments.
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
-
Create a keyspace. For example, create a keyspace for use in a single data
center and a replication factor of 3. Use the default data center name from the
output of nodetool status, for example datacenter1.
-
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)
);
-
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