Skip to content

Instantly share code, notes, and snippets.

@klausbrunner
Created November 20, 2012 14:25
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save klausbrunner/4118224 to your computer and use it in GitHub Desktop.
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
@jhuamanchumo
Copy link

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