Open In App

Lightweight Transactions in Cassandra

Improve
Improve
Like Article
Like
Save
Share
Report

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,


Last Updated : 20 Nov, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads