Lightweight Transactions in Cassandra

In this article we will discuss Lightweight Transactions(LWT) in Cassandra which is also help to improve performance.

Sometimes insert or update operations must be unique which require a read-before-write. The read-before-write has performance implications – Use wisely! This type of problem solved by CQL Lightweight Transactions (LWT) by using an IF clause on inserts and updates.

For Example:
Creating a keyspace:



CREATE KEYSPACE IF NOT EXIST keyspace1 
WITH replication = {'class': 'SimpleStrategy', 
                    'replication_factor' : 2}; 

Creating a table:

CREATE TABLE User (
U_email text,
U_password int,      
U_id UUID,
PRIMARY KEY (email)
); 

To read used the following CQL query.

Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 

Output:

U_email U_password U_id

[0 rows]

To insert the data into table used the following CQL Query.

Insert into keyspace1.User (U_email, U_password, U_id) 
values (‘ashish@gmail.com’, ‘password_A’, uuid()) 
if not exists; 

Let’s have a look.


Figure – LWT in Cassandra

Now, LWT created the row.


Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 

Output:

U_email U_password U_id
ashish@gmail.com password_A 1a2b3c4d5e6789


[1 rows] LWT created the row

LWT on Existing Row:

Insert into keyspace1.User (U_email, U_password, U_id) 
values (‘ashish@gmail.com’, ‘password_XYZ’, uuid()) 
if not exists;  

Let’s have a look,


Figure – LWT on existing row

Here is the output of the above CQL query.

Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 

Output:


Figure – The row did not change

Lightweight Transactions(LWT) on Updating Row:
CQL query for updating an existing row and now we are applying LWT on this. CQL query for updating an existing row.

UPDATE keyspace1.User SET U_password = 'password_XYZ' 
WHERE U_email = 'ashish@gmail.com'
IF U_password = 'password_A' ; 

Operators can be used for UPDATE command:

=, <,, >=, != and IN 

Let’s have a look,



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.