Templates by BIGtheme NET

Spring Data Cassandra : Delete Operation

In this Article, I will show How to delete single and bulk data from
Cassandra Database with Spring Data Cassandra Template.
How to create a maven project and add required dependencies.

Tools Uses :

1) spring-data-cassandra-1.2.1.RELEASE
2) Apache-cassandra-2.1.6
3) eclipse version Luna 4.4.1.
4) Maven 3.3.3
5) JDK 1.6

Steps to be follow :

1) Create a simple maven project.

2) Add the dependencies and

3) Write a simple program to delete data using Spring Cassandra Template.

4) Start the Cassandra server.

5) Run the program and verify the data in cassandra.

Add the given dependency to spring-data-cassandra API,


	org.springframework.data
	spring-data-cassandra
	1.2.1.RELEASE

Complete pom.xml file code is Here,
pom.xml


  4.0.0

  com.devjavasource.cassandra
  SpringDataCassandraExample
  0.0.1-SNAPSHOT
  jar

  SpringDataCassandraExample
  http://maven.apache.org

  
    UTF-8
  

  
    
      junit
      junit
      3.8.1
      test
    
    
	  com.datastax.cassandra
	  cassandra-driver-core
	  2.1.6
	
	
    
        org.springframework.data
        spring-data-cassandra
        1.2.1.RELEASE
    
  

Write a simple program to delete data using Spring Cassandra Template :

This program will do the following,

1) Create a Cluster object.

Cluster cluster = null;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();

A cluster object maintains a permanent connection to one of
the cluster nodes. builder() is a static method of Cluster class.

2) Create a session object

private static Session session;
session = cluster.connect("devjavasource");

Here “devjavasource” is the existed keyspace, I am using the same.
we can create a session object by passing key space name as parameter
to connect() method of cluster class.

3) Create CassandraOperations :

CassandraOperations is interface that helps to do Operations like select, insert, delete…etc
for interacting with Cassandra.

CassandraOperations cassandraOps = new CassandraTemplate(session);

Using delete() method of CassandraTemplate class, we can delete single
or multiple records from Cassandra Database.

// To delete a single User information from Database
cassandraOps.delete(new Users(11104, "UK_updated", "Alex")); 
//To delete a single User information from Database, by Id
cassandraOps.deleteById(Users.class, 11104);

// To delete multiple User information at a time.
// Bulk delete operation
final Users user1 = new Users(11105, "Australia", "Mike_updated");
final Users user2 = new Users(11106, "India", "Ram_updated");
final List<Users> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);

cassandraOps.delete(userList);

Six different types of delete() methods are available in
Spring Data CassandraTemplate,

// Using this, we can delete single Object data from Cassandra database.
<T> T delete(T entity)

// Using this, we can delete bulk data from Cassandra database.
<T> List<T> delete(List<T> entities)

// We can delete, with QueryOptions
<T> void delete(T entity, QueryOptions options);
<T> T delete(T entity, QueryOptions options)

// Delete an entity by Id
void deleteById(Class<?> type, Object id);

// Deletes all entities of a given class.
<T> void deleteAll(Class<T> clazz);

// Delete the given entity asynchronously
<T> Cancellable deleteAsynchronously(T entity);
<T> Cancellable deleteAsynchronously(T entity, QueryOptions options);
// to receive notification upon completion
<T> Cancellable deleteAsynchronously(T entity, DeletionListener<T> listener);
<T> Cancellable deleteAsynchronously(T entity, DeletionListener<T> listener, QueryOptions options);

<T> Cancellable deleteAsynchronously(List<T> entities);
<T> Cancellable deleteAsynchronously(List<T> entities, DeletionListener<T> listener);
<T> Cancellable deleteAsynchronously(List<T> entities, QueryOptions options);
<T> Cancellable deleteAsynchronously(List<T> entities, DeletionListener<T> listener, QueryOptions options);

What is QueryOptions ?

Contains Query Options for Cassandra queries.
This controls the Consistency Tuning and Retry Policy for a Query.

we can create a QueryOptions instance with following constructor,

QueryOptions(ConsistencyLevel consistencyLevel, RetryPolicy retryPolicy) {
		setConsistencyLevel(consistencyLevel);
		setRetryPolicy(retryPolicy);
	}

(a) consistencyLevel – is the consistencyLevel associated
with Cassandra for this particular delete operation.

Possible values are
ANY, ONE, TWO, THREE, QUOROM, LOCAL_QUOROM, EACH_QUOROM,
ALL, LOCAL_ONE, SERIAL, LOCAL_SERIAL.

Suppose If we pass ONE as consistencyLevel, that means if cluseter is down.
Then Cassandra server returns server fault message only after try
with only one active cluser in ring.

(b) retryPolicy – is the retryPolicy associated
with Cassandra for this particular delete operation.

Possible values are
DEFAULT, DOWNGRADING_CONSISTENCY, FALLTHROUGH, LOGGING

Complete Source code is Here,
App.java

package com.devjavasource.cassandra.SpringDataCassandraExample;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.devjavasource.cassandra.dto.Users;

public class App {
	private static Cluster cluster;
	private static Session session;

	public static void main(String[] args) {

		try {

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

			session = cluster.connect("devjavasource");

			CassandraOperations cassandraOps = new CassandraTemplate(session);

			System.out.println("Spring Data Cassandra Single Delete Example");
			System.out.println("============================================");
			print(cassandraOps, 11104);
			// To delete a single User information in Database
			cassandraOps.delete(new Users(11104, "UK_updated", "Alex"));

			System.out.println("User information after deleted  ");
			System.out.println("============================================");

			print(cassandraOps, 11104);

			System.out.println("\nSpring Data Cassandra bulk Delete Example");
			System.out.println("============================================");
			printList(cassandraOps, Arrays.asList(11105, 11106));

			// To delete multiple User information at a time.
			// Bulk delete operation
			final Users user1 = new Users(11105, "Australia", "Mike_updated");
			final Users user2 = new Users(11106, "India", "Ram_updated");
			final List<Users> userList = new ArrayList<>();
			userList.add(user1);
			userList.add(user2);

			cassandraOps.delete(userList);
			System.out.println("\nUsers information after Deleted  ");
			System.out.println("============================================");
			printList(cassandraOps, Arrays.asList(11105, 11106));

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			cluster.close();
		}
	}

	private static void print(final CassandraOperations inCassandraOps,
			final int inId) {

		final String[] columns = new String[] { "id", "address", "name" };

		Select select = QueryBuilder.select(columns).from("users");
		select.where(QueryBuilder.eq("id", inId));

		final List<Users> results = inCassandraOps.select(select, Users.class);

		for (Users user : results) {
			System.out.println("User Id is: " + user.getId());
			System.out.println("User Address is: " + user.getAddress());
			System.out.println("User Name is: " + user.getName());
		}
	}

	private static void printList(final CassandraOperations inCassandraOps,
			final List<Integer> inIdList) {

		final String[] columns = new String[] { "id", "address", "name" };

		Select select = QueryBuilder.select(columns).from("users");
		select.where(QueryBuilder.in("id", inIdList));

		final List<Users> results = inCassandraOps.select(select, Users.class);

		for (Users user : results) {
			System.out.println("User Id is: " + user.getId());
			System.out.println("User Address is: " + user.getAddress());
			System.out.println("User Name is: " + user.getName());
		}
	}
}

User.java

package com.devjavasource.cassandra.dto;

import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;

@Table
public class User {
	@PrimaryKey
	private int id;

	private String address;
	private String name;

	public User(int id, String address, String name) {
		this.id = id;
		this.address = address;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public String getAddress() {
		return address;
	}

	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", address=" + address + ", name=" + name
				+ "]";
	}
}

4) Start the Cassandra server :

Cassandra server should be up and running.
If the server is not running, run the server using following command.

Command to start Casandra server is,
C:\apache-cassandra-2.1.6\bin>cassandra.bat -f

5) Run Maven project :

Select and Run As -> Java Application.

Out Put :

Spring Data Cassandra Single Delete Example
============================================
User Id is: 11104
User Address is: UK_updated
User Name is: Alex
User information after deleted  
============================================

Spring Data Cassandra bulk Delete Example
============================================
User Id is: 11105
User Address is: Australia
User Name is: Mike_updated
User Id is: 11106
User Address is: India
User Name is: Ram_updated

Users information after Deleted  
============================================

Verify the data in cassandra :

Start cqlsh shell and use key space “devjavasource” and query
for the table Users.

4

You can download complete project, Here

SpringDataCassandraExample

*** Venkat – Happy leaning ****