Reading objects from Apache Cassandra using Hector API

We already learned the fundamentals of Apache Cassandra database.We learned the fundamental operations like :read , insert ,delete etc. In the just previous chapter we learned how to insert objects into Apache Cassandra database using Java.In this chapter we are retrieving the same object data inserted there in last chapter.

Reading objects from Apache Cassandra using Hector API

Before starting our application , Apache Cassandra should be installed ,started and key space should be configured as explained earlier. Also the Hector and Thrift libraries listed there should be in the project work space . Now lets look into the column family structure after the insertion of the two objects.


Now lets look into our Java application which retrieves the object data from the ‘myColumnFamily‘.

import me.prettyprint.cassandra.model.HColumnImpl;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.ColumnSliceIterator;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;
import me.prettyprint.hector.api.ddl.ComparatorType;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.query.SliceQuery;

public class ObjectReadSample {
Cluster cluster = null;
Keyspace keyspace = null;

public ObjectReadSample() {


public void getConfig() {
cluster = HFactory.getOrCreateCluster("Test Cluster", "localHost:9160");
keyspace = HFactory.createKeyspace("USERKEYSPACE", cluster);

public void readObject(String rowKey) {

if (null != cluster && null != keyspace) {
ColumnFamilyDefinition columnFamily = HFactory
"myColumnFamily", ComparatorType.UTF8TYPE);
SliceQuery query = HFactory
.createSliceQuery(keyspace, StringSerializer.get(),
StringSerializer.get(), StringSerializer.get())
ColumnSliceIterator iterator = new ColumnSliceIterator(
query, null, "\u00FFF", false);
while (iterator.hasNext()) {
HColumnImpl column = (HColumnImpl) iterator
.println(column.getName() + " = " + column.getValue());

public static void main(String[] args) {
ObjectReadSample sample = new ObjectReadSample();




Before running the application  , Cassandra database should be started. The libraries should be added as dependencies.

id = 1

name = Bijoy

id = 2

name = Karthik

See Related Posts:

Apache Cassandra overview

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