Friday 10 April 2020

How To Use Cassandra 3.3.0 with Java Application .

What is Cassandra ?


Cassandra is a NoSQL database which is distributed and scalable. It is provided by Apache. Apache Cassandra is highly scalable, high performance, distributed NoSQL database. Cassandra is designed to handle huge amount of data across many commodity servers,  providing high availability without a single point of failure.

The following points specify the most important happenings in Cassandra history:
Cassandra was developed at Facebook by Avinash Lakshman and Prashant Malik.
It was open sourced by Facebook in July 2008.
It was accepted by Apache Incubator in March 2009.
Cassandra is a top level project of Apache since February 2010.

What is Keyspace?
A keyspace is an object that is used to hold column families, user defined types. A keyspace is like RDBMS database which contains column families, indexes, user defined types, data center awareness, strategy used in keyspace, replication factor, etc.

In Cassandra, "Create Keyspace" command is used to create keyspace.

CQL Synatx for create keysapce :
Create keyspace KeyspaceName with replicaton={'class':strategy name, 
'replication_factor': No of replications on different nodes}

Create table Syantax in CQL

CREATE TABLE student(
   student_id int PRIMARY KEY,
   student_name text,
   student_city text,
   student_fees varint,
   student_phone varint
   );


To Use Cassandra First install the Cassandra Server on your machine After install start Cassandra server
go to bin directory of your Cassandra type following command

E:\jk\software\apache-cassandra-3.0.20-bin\apache-cassandra-3.0.20\bin> cassandra.bat -f

To Use Cassandra with Java Application First Download Cassandra Server Driver jar for Java Apllication

Add following jar file on classpath

cassandra-driver-core-3.0.1.jar
guava-16.0.1.jar
metrics-core-3.1.2.jar
netty-buffer-4.0.33.Final.jar
netty-codec-4.0.33.Final.jar
netty-common-4.0.33.Final.jar
netty-handler-4.0.33.Final.jar
netty-transport-4.0.33.Final.jar
slf4j-api-1.7.7.jar


Java Application With Cassandra 

CassandraConnector.java  :- This Connector class use to connect java application with

Cassandra server and get a session object .

package in.jk.cassandra;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;

public class CassandraConnector {

private Cluster cluster;
private Session session;
private String node ="127.0.0.1"; //local host Node IP
private int port =9042; // Default port of Cassandra

public Cluster connect(String node, int port) {

SocketOptions options = new SocketOptions();
        options.setConnectTimeoutMillis(300000);
        options.setReadTimeoutMillis(3000000);
options.setTcpNoDelay(true);

        return this.cluster = Cluster.builder()
                            .addContactPoint(node)
                            .withPort(port)
                            .withSocketOptions(options)
                            .build();

}

public Session openSession() {

String localhostNode = this.node;
int port =this.port;

               // provide cluster IP address and port no for   getting cluster
this.cluster = connect(localhostNode, port);
session = cluster.connect();
return session;

}

public void close() {

session.close();
}

}

CassandraApplication .java :-CassandraApplication  java class responsible for getting session object from connector  class , create keyspace and table  and insert , retrieve and delete data from data from table .

package in.jk.cassandra;

import java.util.List;

import com.datastax.driver.core.ExecutionInfo;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;

public class CassandraApplication {

public static void main(String[] args) {

CassandraConnector cassandraConnector = new CassandraConnector();
Session session = cassandraConnector.openSession();
System.out.println("Session :: " + session);


// CQL Query to create Keyspace
String keyspacequery = "CREATE KEYSPACE google_employee WITH replication "
+ "= {'class':'SimpleStrategy', 'replication_factor':1};";
session.execute(keyspacequery);
               System.out.println("google_employee Keyspace is created  ");
session.execute("USE google_employee");
// CQL Query for creating table
String createquery = "Create table employee ( empId int PRIMARY Key,
                name varchar   , company varchar ,adddress varchar)";
session.execute(createquery);

// CQL Query for adding data in employee table
int empId = 3;
String name = "JK";
String company = "Google";
String address = "India";
String query = "Insert into employee (empId,name,company,adddress) values(" + empId +                   ",'" + name + "','"+ company + "','" + address + "')";

ResultSet resultSet0 = session.execute(query);
Row row0 = resultSet0.one();
System.out.println("Employee Record Added");
System.out.println(row0);
System.out.println();

String selectQuery = "Select * from employee";
String queryWithWhere = "Select * from employee  where empId=?";

ResultSet resultSet = session.execute(selectQuery);
Row row = resultSet.one();

System.out.println("Employee Id   :" + row.getInt("empId"));
System.out.println("Employee Name :" + row.getString("name"));
System.out.println("Company       :" + row.getString("company"));
System.out.println("Address       :" + row.getString("adddress"));

System.out.println();

ResultSet resultSet1 = session.execute(queryWithWhere, empId);
Row row1 = resultSet1.one();

System.out.println("Employee Id   :" + row1.getInt("empId"));
System.out.println("Employee Name :" + row1.getString("name"));
System.out.println("Company       :" + row1.getString("company"));
System.out.println("Address       :" + row1.getString("adddress"));

System.out.println();

String deleteQuery = "Delete from employee  where empId=?";

ResultSet resultSet2 = session.execute(deleteQuery, empId);

List<ExecutionInfo> list = resultSet2.getAllExecutionInfo();
System.out.println("Record Deleted :: " + list.size());
System.out.println("Record Deleted Succussfully ..");
System.out.println("Query Executed Succussfully . ");

session.close();

}

}

Output of Above Code :-










No comments:

Post a Comment