Using a counter
A counter is a special column for storing a number that is updated by increments or decrements.
To load data into a counter column, or to increase or decrease the value of the counter, use the UPDATE command. Apache Cassandra rejects USING TIMESTAMP or USING TTL in the command to update a counter column.
Procedure
-
Create a table for the counter column.
CREATE TABLE IF NOT EXISTS cycling.popular_count ( id UUID PRIMARY KEY, popularity counter );
-
Loading data into a counter column is different than other tables. The data is updated rather than inserted.
BEGIN COUNTER BATCH UPDATE cycling.popular_count SET popularity = popularity + 1 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; UPDATE cycling.popular_count SET popularity = popularity + 125 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; UPDATE cycling.popular_count SET popularity = popularity - 64 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; APPLY BATCH;
UPDATE cycling.popular_count SET popularity = popularity + 2 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
-
The
popularity
column has a value of 64.SELECT * FROM cycling.popular_count;
bplist00�XUTI-Data�_$com.apple.traditional-mac-plain-text_public.utf8-plain-text_public.utf16-plain-textO*select_all_from_popular_count.results copy_*select_all_from_popular_count.results copyOTs e l e c t _ a l l _ f r o m _ p o p u l a r _ c o u n t . r e s u l t s c o p y B [ u � � &
Additional increments or decrements changes the value of the counter column.