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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With