Templates by BIGtheme NET

Cassandra Map Datatype Java Example

In this Article, I will show How to work with Cassandra map datatype.
How to retrieve, insert, delete and update data.

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

When do we use map data type?
A map is a name and a pair of typed values.
Each element of the map is internally stored as one Cassandra column
that you can modify, replace, delete, and query

Setup required data :

Start Cassandra server and CQL prompt.

Create a table with name UserOrders.
Syntax is,

CREATE TABLE UserOrders (
  user_id text PRIMARY KEY,
  first_name text,
  last_name text,
  dispatchAddress text,
  amount int,
  order_ids set<text>
);

ALTER TABLE UserOrders ADD orders list<Order>;
ALTER TABLE UserOrders ADD order_history map<text, timestamp>;

Steps to be follow :

1) Create a simple maven project.

2) Add the dependencies.

3) Write a simple program to retrieve, insert, delete and update Map 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
    
    
        org.springframework.data
        spring-data-cassandra
        1.2.1.RELEASE
    
  

Write a simple program to work with Cassandra Map datatype :

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);

Retrieve Data :

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

// To select a single User information from Database
final String[] columns = new String[] { "user_id", "first_name",
		"last_name", "dispatchAddress", "amount", "order_ids",
		"routing_point", "order_history" };

Select select = QueryBuilder.select(columns).from("UserOrders");
select.where(QueryBuilder.eq("user_id", "User_1101"));
final List<UserOrders> results = cassandraOps.select(select,
		UserOrders.class);

Insert Data :

Insert into UserOrders table,

// To insert into UserOrders table
Map<String, Date> order_history = new HashMap<>();
order_history.put("ORDERED", dateStringToDate("2015-08-14 12:13"));
order_history.put("ACCEPTED", dateStringToDate("2015-08-14 13:10"));
order_history.put("PARTIALLYEXECUTED",
		dateStringToDate("2015-08-14 13:20"));
order_history.put("EXECUTED", dateStringToDate("2015-08-14 14:00"));
order_history
		.put("DELIVERED", dateStringToDate("2015-08-15 12:10"));
order_history.put("RETIERED", dateStringToDate("2015-08-16 12:30"));

UserOrders userOrders = new UserOrders("User_1102", "Mike", "Wen",
		"21/4 11 L 12 St Downtown OAK", 200, orderSet,
		routing_points, order_history);

cassandraOps.insert(userOrders);

Delete Data :

Delete entire UserOrders object or only orders set from UserOrders table

// This is to delete entire UserOrders object
cassandraOps.delete(userOrders);

// This is to delete Orders from UserOrders tables
userOrders.setOrder_history(new HashMap<String, Date>());
cassandraOps.update(userOrders);

Update Data :
Update Only order history map of UserOrders table,

order_history.put("EXECUTED", dateStringToDate("2015-08-16 12:00"));
order_history
		.put("DELIVERED", dateStringToDate("2015-08-17 13:10"));
order_history.put("RETIERED", dateStringToDate("2015-08-20 10:30"));
userOrders.setOrder_history(order_history);

cassandraOps.update(userOrders);

Complete Source code is Here,
App.java

package com.devjavasource.cassandra.SpringDataCassandraExample;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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.UserOrders;

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

	@SuppressWarnings("deprecation")
	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);

			// To select a single User information from Database
			final String[] columns = new String[] { "user_id", "first_name",
					"last_name", "dispatchAddress", "amount", "order_ids",
					"routing_point", "order_history" };

			Select select = QueryBuilder.select(columns).from("UserOrders");
			select.where(QueryBuilder.eq("user_id", "User_1101"));
			final List<UserOrders> results = cassandraOps.select(select,
					UserOrders.class);
			System.out.println("***********RETRIEVE OPERATION DEMO*******");
			printList(results);

			// To insert into UserOrders table
			@SuppressWarnings({ "rawtypes", "unchecked" })
			Set<String> orderSet = new HashSet(Arrays.asList("order_id101",
					"order_id102", "order_id103"));
			List<String> routing_points = Arrays.asList("AUE", "SAN", "UK",
					"LON");
			Map<String, Date> order_history = new HashMap<>();
			order_history.put("ORDERED", dateStringToDate("2015-08-14 12:13"));
			order_history.put("ACCEPTED", dateStringToDate("2015-08-14 13:10"));
			order_history.put("PARTIALLYEXECUTED",
					dateStringToDate("2015-08-14 13:20"));
			order_history.put("EXECUTED", dateStringToDate("2015-08-14 14:00"));
			order_history
					.put("DELIVERED", dateStringToDate("2015-08-15 12:10"));
			order_history.put("RETIERED", dateStringToDate("2015-08-16 12:30"));

			UserOrders userOrders = new UserOrders("User_1102", "Mike", "Wen",
					"21/4 11 L 12 St Downtown OAK", 200, orderSet,
					routing_points, order_history);
			// System.out.println(dateStringToDate("2015-08-14 12:13"));
			cassandraOps.insert(userOrders);
			System.out.println("\n***********INSERT OPERATION DEMO*******");
			printit(columns, cassandraOps);

			order_history.put("EXECUTED", dateStringToDate("2015-08-16 12:00"));
			order_history
					.put("DELIVERED", dateStringToDate("2015-08-17 13:10"));
			order_history.put("RETIERED", dateStringToDate("2015-08-20 10:30"));
			userOrders.setOrder_history(order_history);
			cassandraOps.update(userOrders);
			System.out.println("***********UPDATE OPERATION DEMO*******");
			printit(columns, cassandraOps);

			userOrders.setOrder_history(new HashMap<String, Date>());
			cassandraOps.update(userOrders);
			System.out
					.println("***********DELETE OPERATION DEMO - To Null Set*******");
			printit(columns, cassandraOps);

			cassandraOps.delete(userOrders);
			System.out.println("\n***********DELETE OPERATION DEMO*******");
			printit(columns, cassandraOps);

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

	private static void printit(final String[] columns,
			final CassandraOperations cassandraOps) {
		// To select multiple User information at a time.
		// Bulk select operation
		Select allUserSelect = QueryBuilder.select(columns).from("UserOrders");
		final List<UserOrders> allUsers = cassandraOps.select(allUserSelect,
				UserOrders.class);
		printList(allUsers);
	}

	private static void printList(final List<UserOrders> inResults) {

		for (UserOrders userOrders : inResults) {
			System.out.println("User Id is: " + userOrders.getUser_id());
			System.out.println("First Name is: " + userOrders.getFirst_name());
			System.out.println("Last Name is: " + userOrders.getLast_name());
			System.out.println("User Dispatch Address is: "
					+ userOrders.getDispatchAddress());
			System.out.println("Total Amount is: " + userOrders.getAmount());
			System.out.println("Ordered Ids is: " + userOrders.getOrder_ids());
			System.out.println("Routing Points is: "
					+ userOrders.getrouting_point());
			printOderHistory(userOrders.getOrder_history());
		}
	}

	public static void printOderHistory(final Map<String, Date> order_history) {
		if (order_history == null) {
			System.out.println("Order History is: " + null);
			return;
		}
		final Set<String> keys = order_history.keySet();
		final Iterator<String> keysItr = keys.iterator();
		while (keysItr.hasNext()) {
			String key = keysItr.next();
			Date val = order_history.get(key);
			System.out.println("Order Status: " + key + " Time is:"
					+ new SimpleDateFormat(DATE_TIME_FORMAT).format(val));
		}
		System.out.println();
	}

	public static Date dateStringToDate(final String inDateStr)
			throws ParseException {
		return new SimpleDateFormat(DATE_TIME_FORMAT).parse(inDateStr);
	}

	public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
}

UserOrders.java

package com.devjavasource.cassandra.dto;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

@Table
public class UserOrders {

	@PrimaryKey
	private String user_id;
	private String first_name;
	private String last_name;
	private String dispatchAddress;
	private int amount;
	private Set<String> order_ids;
	private List<String> routing_point;
	private Map<String, Date> order_history;

	public UserOrders(String user_id, String first_name, String last_name,
			String dispatchAddress, int amount, Set<String> order_ids,
			List<String> routing_point, Map<String, Date> order_history) {
		this.user_id = user_id;
		this.first_name = first_name;
		this.last_name = last_name;
		this.dispatchAddress = dispatchAddress;
		this.amount = amount;
		this.order_ids = order_ids;
		this.routing_point = routing_point;
		this.order_history = order_history;
	}

	public String getUser_id() {
		return user_id;
	}

	public String getFirst_name() {
		return first_name;
	}

	public void setFirst_name(String first_name) {
		this.first_name = first_name;
	}

	public String getLast_name() {
		return last_name;
	}

	public void setLast_name(String last_name) {
		this.last_name = last_name;
	}

	public String getDispatchAddress() {
		return dispatchAddress;
	}

	public void setDispatchAddress(String dispatchAddress) {
		this.dispatchAddress = dispatchAddress;
	}

	public int getAmount() {
		return amount;
	}

	public void setAmount(int amount) {
		this.amount = amount;
	}

	public Set<String> getOrder_ids() {
		return order_ids;
	}

	public void setOrder_ids(Set<String> order_ids) {
		this.order_ids = order_ids;
	}

	public List<String> getrouting_point() {
		return routing_point;
	}

	public void setrouting_point(List<String> routing_point) {
		this.routing_point = routing_point;
	}

	public void setUser_id(String user_id) {
		this.user_id = user_id;
	}

	public Map<String, Date> getOrder_history() {
		return order_history;
	}

	public void setOrder_history(Map<String, Date> order_history) {
		this.order_history = order_history;
	}
}

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 :

***********RETRIEVE OPERATION DEMO*******
User Id is: User_1101
First Name is: Bob
Last Name is: Wigins
User Dispatch Address is: 22/4 11 L 12 St Downtown OAK
Total Amount is: 100
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [SIN, AUS, SAN]
Order History is: null

***********INSERT OPERATION DEMO*******
User Id is: User_1101
First Name is: Bob
Last Name is: Wigins
User Dispatch Address is: 22/4 11 L 12 St Downtown OAK
Total Amount is: 100
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [SIN, AUS, SAN]
Order History is: null
User Id is: User_1102
First Name is: Mike
Last Name is: Wen
User Dispatch Address is: 21/4 11 L 12 St Downtown OAK
Total Amount is: 200
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [AUE, SAN, UK, LON]
Order Status: ACCEPTED Time is:2015-08-14 13:10
Order Status: DELIVERED Time is:2015-08-15 12:10
Order Status: EXECUTED Time is:2015-08-14 14:00
Order Status: ORDERED Time is:2015-08-14 12:13
Order Status: PARTIALLYEXECUTED Time is:2015-08-14 13:20
Order Status: RETIERED Time is:2015-08-16 12:30

***********UPDATE OPERATION DEMO*******
User Id is: User_1101
First Name is: Bob
Last Name is: Wigins
User Dispatch Address is: 22/4 11 L 12 St Downtown OAK
Total Amount is: 100
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [SIN, AUS, SAN]
Order History is: null
User Id is: User_1102
First Name is: Mike
Last Name is: Wen
User Dispatch Address is: 21/4 11 L 12 St Downtown OAK
Total Amount is: 200
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [AUE, SAN, UK, LON]
Order Status: ACCEPTED Time is:2015-08-14 13:10
Order Status: DELIVERED Time is:2015-08-17 13:10
Order Status: EXECUTED Time is:2015-08-16 12:00
Order Status: ORDERED Time is:2015-08-14 12:13
Order Status: PARTIALLYEXECUTED Time is:2015-08-14 13:20
Order Status: RETIERED Time is:2015-08-20 10:30

***********DELETE OPERATION DEMO - To Null Set*******
User Id is: User_1101
First Name is: Bob
Last Name is: Wigins
User Dispatch Address is: 22/4 11 L 12 St Downtown OAK
Total Amount is: 100
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [SIN, AUS, SAN]
Order History is: null
User Id is: User_1102
First Name is: Mike
Last Name is: Wen
User Dispatch Address is: 21/4 11 L 12 St Downtown OAK
Total Amount is: 200
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [AUE, SAN, UK, LON]
Order History is: null

***********DELETE OPERATION DEMO*******
User Id is: User_1101
First Name is: Bob
Last Name is: Wigins
User Dispatch Address is: 22/4 11 L 12 St Downtown OAK
Total Amount is: 100
Ordered Ids is: [order_id101, order_id102, order_id103]
Routing Points is: [SIN, AUS, SAN]
Order History is: null

You can download complete project, Here

SpringDataCassandraExample

*** Venkat – Happy leaning ****