CQL 3 Cassandra 1.2 counter: how to insert a primary key?

I want to use Cassandra counters in CQL3 like this

create table count1 (id int PRIMARY KEY, c1 counter);

I know that to update the counter I need to do something like a form:

update count1 set c1 = c1 + 1 where ..

but before that I need to insert the value into my key (id); but I get:

 cqlsh:test2> insert into count1 (id) values (4); Bad Request: INSERT statement are not allowed on counter tables, use UPDATE instead 

what gives?

+4
source share
1 answer

In Cassandra, there is no concept of a primary key, whether it exists or not, it is only cells that exist with a specific primary key.

So, for regular column families (i.e. non-counter) you can insert or update (they are semantically identical) if anything was previously inserted with this primary key.

Regarding counter tables, CQL requires you to use update , not insert , so that it is clear that it increments rather than sets a value. You cannot set the counter value in Cassandra, only inc / dec. If there was no previous counter, it is assumed that it has a value of 0. Thus, you can run

 update count1 set c1 = c1 + 1 where id = 2; 

and the counter will have a value of 1:

 select * from count1; id | c1 ----+---- 2 | 1 
+6
source

Source: https://habr.com/ru/post/1491979/


All Articles