Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cassandra CQL3 conditional insert/update

I have a list of unordered events and my task is to store first and last occurrences for them.

I have following column family in Cassandra:

CREATE TABLE events (
   event_name TEXT,
   first_occurrence BIGINT,
   last_occurrence BIGINT,
   PRIMARY KEY (event_name)
);

So if I have an event with the name "some_event" and occurrence with 123456, what I want to do is something which in MySQL terms would look like this:

INSERT INTO events (event_name, first_occurence, last_occurence)
VALUES ('some_event', 123456, 123456)
ON DUPLICATE KEY UPDATE 
     first_occurrence = LEAST(first_occurrence, 12345), 
     last_occurrence = GREATEST(last_occurrence, 123456)

I was going to use lightweight transactions in Cassandra to accomplish it, like this:

INSERT INTO events(event_name, first_occurrence, last_occurrence) VALUES ('some_event', 12345, 12345) IF NOT EXISTS;
UPDATE events SET first_occurrence = 123456 WHERE event_name='some_event' IF first_occurrence > 123456;
UPDATE events SET last_occurrence = 123456 WHERE event_name='some_event' IF last_occurrence < 123456;

But as it turns out, CQL3 does not allow < and > operators in lightweight transactions IF clause.

So my question is, what is the pattern for doing such conditional updates?

like image 941
board reader Avatar asked Feb 28 '15 07:02

board reader


People also ask

Can we update primary key value in Cassandra?

UPDATE cannot update the values of a row's primary key fields. To update a counter in a counter table, specify the increment or decrement to the counter column. Note: Unlike the INSERT command, the UPDATE command supports counters. Otherwise, the UPDATE and INSERT operations are identical.

How do you update multiple columns in Cassandra?

Now, to Update, several columns in a single row used the following CQL query. UPDATE User_data SET Name = 'Ashish Rana', Country = 'India' WHERE User_id = 04a5626c-c0d7-477c-521d-6c1b69a95d23; Now, to verify whether successfully updated or not.

How does update work in Cassandra?

Cassandra treats each new row as an upsert: if the new row has the same primary key as that of an existing row, Cassandra processes it as an update to the existing row. During a write, Cassandra adds each new row to the database without checking on whether a duplicate record exists.


1 Answers

What version of cassandra are you running? Support for non-equal conditions with LWTs was added in 2.1.1 via CASSANDRA-6839:

cqlsh:test> UPDATE events SET first_occurrence = 123456 WHERE event_name='some_event' IF first_occurrence > 1;

[applied]
-----------
  True
like image 194
Andy Tolbert Avatar answered Sep 28 '22 07:09

Andy Tolbert