Running Cassandra Batch Processing with CQL and Java

06 May 2023 Balmiki Mandal 0 Core Java

Cassandra Batch Queries in Cassandra Query Language

Batches are an important part of working with Apache Cassandra, allowing you to execute multiple CQL commands in a single transaction. This helps to improve performance while ensuring atomicity and consistency when working with data stored in Cassandra.

To create a batch in Cassandra, the CQL syntax is very simple. The BEGIN BATCH command starts the batch, followed by any number of CQL queries. Finally, the transaction is ended with the APPLY BATCH command.

BEGIN BATCH
[CQL Statements]
APPLY BATCH

In this example, we’ll create a table called ‘person’ and insert a few records into it with a CQL batch.

BEGIN BATCH  
CREATE TABLE IF NOT EXISTS person (id int PRIMARY KEY, name text);  
INSERT INTO person (id, name) VALUES (1, 'John');  
INSERT INTO person (id, name) VALUES (2, 'Beth');  
APPLY BATCH; 

Cassandra Batch Queries in Java

In Java, you can use the Session class provided by the Cassandra driver to execute batches. Before you can begin creating batches, you’ll need to create a session object.

Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect();

Once you have a Session instance, you can call the execute() method and pass it a BatchStatement object. A BatchStatement is created by adding one or more Statement objects to it.

String query1 = "CREATE TABLE IF NOT EXISTS person (id int PRIMARY KEY, name text)";
String query2 = "INSERT INTO person (id, name) VALUES (1, 'John')";
String query3 = "INSERT INTO person (id, name) VALUES (2, 'Beth')";

Statement stmt1 = new SimpleStatement(query1);
Statement stmt2 = new SimpleStatement(query2);
Statement stmt3 = new SimpleStatement(query3);

BatchStatement batchStatement = new BatchStatement();
batchStatement.add(stmt1);
batchStatement.add(stmt2);
batchStatement.add(stmt3);

session.execute(batchStatement);

The batch will then be executed, and any errors or warnings will be returned as part of the ResultSet object.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.