Today I'm going to blog about "How to connect to Cassandra from Java using datastax driver."
You can download driver here and compile it.
In this post I used these jar files: cassandra-driver-core-2.1.8-SNAPSHOT.jar which was compiled from above step.
Next one is guava-18.0.jar , metrics-core-3.0.0.jar, netty-all-4.0.12.Final.jar and for logging purpose slf4j-*.jar are included.
In order to connect to cassandra cluster we will need two parameters
- contact point : list of ip address of your cluster's contact point.
- key space name: name of key space in cassandra cluster you want to connect.
Cluster cluster;
Session session;
String[] contactList= {"10.10.10.10","10.10.10.20"};
String keyspaceName = "test";
cluster = Cluster.builder().addContactPoints(contactPoints).build();
session = cluster.connect(keyspaceName);
After this step we will use session object to issue our queries.
For example I want to add a column into existing table:
String columnFamily = "test_table";
String colName = "new_column";
String dataType = "text";
String query = String.format("ALTER TABLE %s.%s ADD %s %s", keyspaceName,columnFamily,colName,dataType);
try {
session.execute(query);
}
catch (Exception e) {
slf4jLogger.error(e.toString());
}
Insert records into existing table in this case is users table:
session.execute(
"INSERT INTO users (
firstname, lastname, age, city, email ) VALUES ('Tin', 'Ho', 27, 'Sai Gon', 'imthientin@gmail.com')");
To acquire data from existing table:
ResultSet results = session.execute("SELECT * FROM users WHERE firstname='Tin'");
for (Row row : results) {
System.out.format("%s %d\n", row.getString("email"), row.getInt("age"));
}
Some other thing we can do:- Drop column : non primary key column
- Drop table/column family
- Drop keyspace
- Change column name: only primary key column
- etc ...
https://github.com/thientin/cassandra-utils