Listing columns from Apache Cassandra using Java

We already discussed the fundamentals of Apache Cassandra. We discussed about configuring Apache Cassandra in local machine and to start/stop Cassandra database . In the previous coding example we learned  to insert data into Apache Cassandra and read data from Cassandra. In this chapter we are discussing how the list of columns from a column family is fetching from Cassandra and how those are iterating .

Listing columns from Apache Cassandra using Java

We already created a key space ‘USERKEYSPACE‘ using the command line client as explained earlier.We already created a column family ‘userColumnFamily‘ in the key space. In the data inserting sample we discussed earlier , we inserted 3 columns . In this chapter we are retrieving the same set of columns using a ‘SliceQuery‘ object.After inserting data , the column family data arrangement will be like this:

Now lets see the java code to retrieve the existing data.

FetchListSample.java

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.factory.HFactory;
import me.prettyprint.hector.api.query.SliceQuery;

public class FetchListSample {
Cluster cluster = null;
Keyspace keySpace = null;

public FetchListSample() {

}

public void getList() {
cluster = HFactory.getOrCreateCluster("Test Cluster", "localHost:9160");
keySpace = HFactory.createKeyspace("USERKEYSPACE", cluster);
SliceQuery query = HFactory
.createSliceQuery(keySpace, StringSerializer.get(),
StringSerializer.get(), StringSerializer.get())
.setKey("names").setColumnFamily("userColumnFamily");
ColumnSliceIterator iterator = new ColumnSliceIterator(
query, null, "\u00FFF", false);
while (iterator.hasNext()) {
HColumnImpl column = (HColumnImpl) iterator
.next();
System.out.println("Column name = " + column.getName()
+ "; Column value = " + column.getValue());
}

}

public static void main(String[] args) {
FetchListSample sample = new FetchListSample();
sample.getList();
}

}

Output

To  run this application  Apache Cassandra should be configured and started in local machine as discussed in: Configuring Apache Cassandra.  Also the libraries listed there should be added to the workspace . The output will be:

Column name = 1; Column value = Bijoy

Column name = 2; Column value = Karthik

Column name = 3; Column value = JayaKrishnan

See Related:

Apache Cassandra overview

Configuring Apache Cassandra in local machine

Inserting data to Apache Cassandra using Java

Reading data from Apache Cassandra using Java

Deleting column from Apache Cassandra using Java

Inserting objects into Apache Cassandra using Hector API

Reading object data from Apache Cassandra using Hector API