Search code examples
cassandracqlcassandra-3.0

Increment field on row if exists, else insert new row


Imagine a table storing tags for questions, like the tags that go on stack overflow questions.

I want to track how many questions have a tag.

I made this table

create table tag (name text primary key, questions counter);

Now I want to add a tag to the table, but if it already exists it shouldn't be added, it should increase the questions of the existing tag by 1.

I think it will look something like

update tag set questions = questions + 1 where name = ? if exists
insert tag (name, questions) values (?, 1) if not exists

But the above gives me the error:

Conditional updates are not supported on counter tables

Solution

  • Updates in cassandra works as upsert.

    If same primary key exists it will be overwritten else it will create new.

    update tag set questions = questions + 1 where name = ?
    

    Only this will take care of requirements