Apache Cassandra – Part 07 (Java API)

Throughout the last 6 posts we talked about different aspects of Apache Cassandra. But all those posts were related to working on the cqlsh. So from this post you can get an idea about the Java API for Apache Cassandra. After going through this post, you can get a clear idea about how to create a program in Java using the Apache Cassandra.

Here I’m using Intelij IDEA as my IDE, Cassandra 3.9 and JDK 8.

First of all let’s see about the dependencies need for the project. We can add those to the pom and make the environment ready for our program.

slf4j-api
slf4j-simple
cassandra-driver-core
guava
metrics-core
netty

Here is the pom.xml after adding those dependencies,

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>Cassandra</groupId>
    <artifactId>Example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>

        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-core</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>16.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.0.2</version>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty</artifactId>
            <version>3.9.0.Final</version>
        </dependency>
    </dependencies>

</project>

Now we are ready to work with the Cassandra Java API.

First of all we need to create a Cluster instance. We can do that by simply calling the Cluster class.

com.datastax.driver.core.Cluster

Lets’ see how to do that,

Cluster myCluster = Cluster.builder()
.addContactPoint("127.0.0.1")
.withPort(9042)
.withCredentials("ajuba","ajuba")
.build();

Using the .addContactPoint() we can connect to the relevant Cassandra server. Here I’m using the server on my local host, that’s why I put ‘127.0.0.1’. You can replace it with the relevant IP of the machine where the Cassandra Server is running. Next .withPort() will specify the port to connect. You can ignore that of the Cassandra is running on the default port, 9042. Third .withCredentials() specify the user name and the password for the Cassandra user. If we haven’t enable the authenticator on the cassandra.yaml, then this is no needed. Check previous posts for enabling authenticator and authorizor. Finally we are creating the cluster by calling the .build().

Now we have the Cluster instance. Next we need to create a session,

com.datastax.driver.core.Session

Let’s see how to do that,

Session mySession = myCluster.connect();

Here we are using the previously created Cluster instance and calling the connect() to create a session. Now we are all done and we simply can execute cql queries using the .execute().

mySession.execute(query);

Then the last thing to do is to close the connection we have created,

mySession.close();
myCluster.close();

Using the Java API for Apache Cassandra is very simple. Here is the full example classes,

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

/**
 * Created by vimukthi on 1/9/17.
 */
public class DBConnection {

    protected static Cluster myCluster;
    protected static Session mySession;

    public static void dbConnection(){
        try {
            //new instance of Cluster
            myCluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(9042).withCredentials("ajuba","ajuba").build();
            //new instance of Session
            mySession = myCluster.connect();
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
import com.datastax.driver.core.ResultSet;

/**
 * Created by vimukthi on 12/27/16.
 */
public class Test extends DBConnection {

    private static String db = "ajuba";
    private static String table = "employee";
    private static String query;

    public static void main(String[] args) {
        //create the data base connection
        dbConnection();
        //data definition language
        ddl();
        //data manipulation language
        dml();
        //close the db connection
        mySession.close();
        myCluster.close();
    }

    public static void ddl(){
        //create key space
        createKeySpace();
        //use key space
        useKeySpace();
        //alter keyspace
        alterKeySpace();
        //create table
        createTable();
        //select data
        select();
        //alter table
        alterTable();
        //select data
        select();
        //drop table
        dropTable();
        //drop keyspace
        dropKeySpace();
    }

    public static void dml(){
        //insert to table
        insert();
        //select data
        select();
        //update data
        update();
        //select data
        select();
        //delete data
        delete();
        //select data
        select();
        //truncate table
        truncateTable();
        //select data
        select();
    }

    public static void executeQuery(String query, String message){
        try {
            //execute the query
            mySession.execute(query);
            System.out.println(message);
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void executeQuery(String query){
        try {
            //execute the query and get the result set
            ResultSet result = mySession.execute(query);
            System.out.println(result.getColumnDefinitions());
            System.out.println(result.all());
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void createKeySpace(){
        //create key space
        query = "CREATE KEYSPACE IF NOT EXISTS " + db + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}";
        executeQuery(query, "Created Key Space " + db);
    }

    public static void useKeySpace(){
        //use key space
        query = "USE " + db;
        executeQuery(query, "Selected Key Space " + db);
    }

    public static void alterKeySpace(){
        //alter key space
        query = "ALTER KEYSPACE " + db + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1} AND durable_writes = 'true'";
        executeQuery(query, "Altered Key Space " + db);
    }

    public static void createTable(){
        //create table
        query = "CREATE TABLE " + table + "(emp_id int PRIMARY KEY, emp_name varchar, address varchar)";
        executeQuery(query, "Created Table " + table);
    }

    public static void alterTable(){
        //alter table
        query = "ALTER TABLE " + table + " ADD emp_email text";
        executeQuery(query, "Altered Table " + table);
    }

    public static void insert(){
        //insert to table
        query = "INSERT INTO " + table + "(emp_id, emp_name, address, emp_email) values (1,'vimukthi','piliyandala','vimukthis@hsenidmobile.com')";
        executeQuery(query, "Inserted Record 01 To Table " + table);
        query = "INSERT INTO " + table + "(emp_id, emp_name, address, emp_email) values (2,'saranga','moratuwa','saranga@hsenidmobile.com')";
        executeQuery(query, "Inserted Record 02 To Table " + table);
        query = "INSERT INTO " + table + "(emp_id, emp_name, address, emp_email) values (3,'hSenid','colombo','info@hsenidmobile.com')";
        executeQuery(query, "Inserted Record 03 To Table " + table);
    }

    public static void select(){
        //select data
        query = "SELECT * FROM " + table;
        executeQuery(query);
    }

    public static void update(){
        //update data
        query = "UPDATE " + table + " SET address = 'maharagama' WHERE emp_id =2";
        executeQuery(query, "Update Record 02 On Table " + table);
    }

    public static void delete(){
        //delete data
        query = "DELETE FROM " + table + " WHERE emp_id =3";
        executeQuery(query, "Deleted Record 03 From Table " + table);
    }

    public static void truncateTable(){
        //truncate table
        query = "TRUNCATE TABLE " + table;
        executeQuery(query, "Truncated Table " + table);
    }

    public static void dropTable(){
        //drop table
        query = "DROP TABLE " + table;
        executeQuery(query, "Dropped Table " + table);
    }

    public static void dropKeySpace(){
        //drop key space
        query = "DROP KEYSPACE " + db;
        executeQuery(query, "Dropped Key Space " + db);
    }
}

Hope now you have a clear idea about how to use the Cassandra Java API. Hopefully now we have covered almost all the areas of Apache Cassandra. Hope to see you soon with another interesting topic. Thank You!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s