Database Reference
In-Depth Information
Conditional inserts and lightweight transactions
Version 3.1 of CQL introduced new support for lightweight transactions , which allow us
to modify data only if certain conditions are met. Unlike the application-level integrity
checks we discussed earlier, lightweight transactions are safe in concurrent environments:
if two processes attempt to conditionally create a row with the same key, lightweight trans-
actions guarantee that only one will succeed.
To perform a conditional insert, we simply add the clause, IF NOT EXISTS , to the end
of the INSERT statement. Let's start fresh with a new user account, frank :
INSERT INTO "users"
("username", "email", "encrypted_password", "location")
VALUES
('frank', 'frank@gmail.com',
0xa71451665e16d8c6e6edfd444c60156efc861432,
'Los Angeles, CA')
IF NOT EXISTS;
When we perform this insert, we'll immediately see something surprising. Cassandra has
feedback on the operation:
While normal write operations give no feedback on their outcome, lightweight transactions
do give feedback. After all, a conditional insert would only be applied if the row did not
exist prior to the write operation; we would like to know what the outcome was. To see
how conditional inserts behave with a key collision, we can attempt to insert another user
with the username frank :
INSERT INTO "users"
("username", "email", "encrypted_password")
VALUES
('frank', 'frank123@hotmail.com',
Search WWH ::




Custom Search