We already discussed the fundamentals of Apache Cassandra . We also discussed the fundamental operations like insert , read and delete with Apache Cassandra using Apache Hector as the client.In this chapter we are discussing how a CQL Select Query is working with Apache Cassandra with Hector API as the high level client.
CQL Select Query example in Java
We already created a key space ‘USERKEYSPACE‘ earlier.And we created a column family ‘userColumnFamily‘ and we inserted few data into it .(Explained in a previous post). In this chapter we are retrieving the same piece of data we inserted there by running a CQL select query from our Java application.
Before starting the coding , the Apache Cassandra should be started and the necessary libraries should be put in the work space as explained in the previous discussion.Now the ‘userColumnFamily‘ contains the following data(After insertion).
CqlReadSample.java
import me.prettyprint.cassandra.model.CqlQuery;
import me.prettyprint.cassandra.model.CqlRows;
import me.prettyprint.cassandra.model.RowImpl;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.query.QueryResult;
public class CqlReadSample {
Cluster cluster = null;
Keyspace keySpace = null;
public CqlReadSample() {
}
public void getConfig() {
cluster = HFactory.getOrCreateCluster("Test Cluster", "localHost:9160");
keySpace = HFactory.createKeyspace("USERKEYSPACE", cluster);
}
public void read() {
if (null != cluster && null != keySpace) {
CqlQuery
keySpace, StringSerializer.get(), StringSerializer.get(),
StringSerializer.get());
cqlQuery.setQuery("select * from userColumnFamily");
QueryResult
.execute();
CqlRows rows = result.get();
for (int i = 0; i < rows.getCount(); i++) {
RowImpl
.getList().get(i);
System.out.println("Row key = " + row.getKey());
for (HColumn
.getColumns()) {
System.out.println("Column name = "
+ column.getName().toString());
System.out.println("Colmn value = "
+ column.getValue().toString());
}
}
}
}
public static void main(String[] args) {
CqlReadSample sample = new CqlReadSample();
sample.getConfig();
sample.read();
}
}
Output
Row key = names
Column name = KEY
Colmn value = names
Column name = 1
Colmn value = Bijoy
Column name = 2
Colmn value = Karthik
Column name = 3
Colmn value = JayaKrishnan
See Related Posts:
Configuring Apache Cassandra in local machine
Inserting data into Apache Cassandra using Java
Reading data from Apache Cassandra using Java
Listing columns in Apache Cassandra using Java
Deleting columns from Apache Cassandra using Java
Inserting object data into Apache Cassandra database