Tuesday, November 17, 2015

Getting Started with Cassandra


  •            Download the Cassandra from apache website to C:\tools\apache-cassandra-2.2.3
  •            Download and Install Python7.0 and add C:\tools\Python7.0 to environment variable PATH
  •             In command prompt: cd C:\tools\apache-cassandra-2.0.16\pylib
python setup.py install


  • Starting Cassandra Server
        In command prompt: C:\tools\apache-cassandra-2.2.3\bin\cassandra.bat

  • Connect to Cassandra server
        In command prompt: C:\tools\apache-cassandra-2.2.3\bin\cqlsh


  • Creating keyspace
         cqlsh> CREATE KEYSPACE IF NOT EXISTS sample_keyspace WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 3} AND DURABLE_WRITES = true;


  • Verify the created keyspace
         cqlsh> SELECT * FROM system.schema_keyspaces;


  • Start using the keyspace, execute:
         cqlsh>use sample_keyspace;


  • Create the table with below command
         cqlsh:sample_keyspace> CREATE TABLE student ( id int, first_name varchar,  last_name varchar, PRIMARY KEY (id));


  • Java code to insert and query the data from Cassandra db:

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

public class TestCQL {

private static Session createConnection() {
Cluster cluster;
Session session;
cluster = Cluster.builder().addContactPoint("localhost").withPort(9042).build();
session = cluster.connect("sample_keyspace");
return session;
}

public static void main(String[] args) {
insertData();
queryData();
}

private static void insertData() {
Session session = createConnection();
String query = "INSERT INTO sample_keyspace.student (id, first_name, last_name) "
+ "VALUES (123,'First Name', 'Last Name' )";
ResultSet results = session.execute(query);
System.out.println("Row successfully inserted");
session.close();
}

private static void queryData() {
Session session = createConnection();
String query = "SELECT * FROM student where id=123";
ResultSet results = session.execute(query);
if (results == null) {
System.out.println("No rows in the database");
return;
}
System.out.println("The database records:");
for (Row row : results) {
System.out.println(row);
}

System.out.println("Row successfully inserted");
session.close();
}
}

No comments:

Post a Comment