Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
creating and using a Cassandra counter column in CQL
-- creating and using a Cassandra counter column in CQL
-- NOTE: this is CQL 2.0 syntax, it will NOT work with CQL 3 (for syntax reasons and because CQL 3.0 drops the very notion of dynamic columns...sigh)
CREATE KEYSPACE test WITH strategy_class = 'SimpleStrategy'
AND strategy_options:replication_factor = '1';
USE test;
CREATE TABLE stats (KEY text PRIMARY KEY) WITH comparator=text AND default_validation=counter;
-- dynamically create a new counter column starting at 0
-- it seems that a counter cannot be set to an absolute value, only inc/dec possible (as per CQL 2.0 spec)
UPDATE stats SET count1 = count1 + 1 WHERE KEY = 'key1';
SELECT * FROM stats WHERE KEY = 'key1';
-- KEY | count1
-- ------+--------
-- key1 | 1
UPDATE stats SET count2 = count2 - 1 WHERE KEY='key1';
-- dynamically add another counter
SELECT * FROM stats WHERE KEY = 'key1';
-- KEY | count1 | count2
-- ------+--------+--------
-- key1 | 1 | -1
UPDATE stats SET count1 = count1 + 1, count2 = count2 - 1 WHERE KEY='key1';
-- both counters updated in one call
UPDATE stats SET count1 = count1 + 25, count2 = count2 - 7 WHERE KEY='key1';
-- any integer decrement/increment is possible
@gitusersada

This comment has been minimized.

Copy link

gitusersada commented Jul 4, 2018

How do i write it(@query) in casssandraRepositry update method for java

@jhuamanchumo

This comment has been minimized.

Copy link

jhuamanchumo commented Aug 16, 2019

try this:

import java.util.Optional;
import java.util.UUID;

import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.query.Param;

public interface PopularCountRepository extends CassandraRepository<PopularCount, UUID> {

	@Query(value=" UPDATE popular_count SET popularity = popularity + 1 WHERE id = :id;")
	void incrementPopularity(@Param("id") UUID id) throws Exception;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.