Skip to content

Instantly share code, notes, and snippets.

@nikhilm
Created April 1, 2012 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikhilm/2270971 to your computer and use it in GitHub Desktop.
Save nikhilm/2270971 to your computer and use it in GitHub Desktop.
Apache Cassandra: Iterate over all columns of a row in batches of count rows.
// Made by Nikhil Marathe <nsm.nikhil@gmail.com>
// This code is in the public domain.
import java.util.Iterator;
import java.util.List;
import me.prettyprint.hector.api.beans.ColumnSlice;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.query.SliceQuery;
public class AllColumnsIterator<N, V> implements Iterator<HColumn<N, V>> {
private N start;
private int count;
Iterator<HColumn<N, V>> columnsIterator;
SliceQuery<?, N, V> query;
private boolean isLastIteration;
public AllColumnsIterator(SliceQuery<?, N, V> query) {
start = null;
count = 100;
columnsIterator = null;
this.query = query;
isLastIteration = false;
}
public Iterator<HColumn<N, V>> iterator() {
return this;
}
public boolean hasNext() {
if (columnsIterator == null || !columnsIterator.hasNext()) {
if (isLastIteration)
return false;
if (!fetchMore())
return false;
}
return true;
}
public HColumn<N, V> next() {
return columnsIterator.next();
}
private boolean fetchMore() {
try {
query.setRange(start, null, false, count);
ColumnSlice<N, V> slice = query.execute().get();
List<HColumn<N, V>> columns = slice.getColumns();
int origSize = columns.size();
if (origSize == 0) {
return false;
}
if (origSize >= count)
start = columns.remove(columns.size()-1).getName();
columnsIterator = columns.iterator();
if (origSize < count)
isLastIteration = true;
return true;
} catch (HectorException e) {
return false;
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
SliceQuery<String, String, String> query = HFactory.createSliceQuery(keyspace, StringSerializer.get(),
StringSerializer.get(), StringSerializer.get());
query.setKey("all-monkeys");
query.setColumnFamily("Animals");
AllColumnsIterator<String, String> it = new AllColumnsIterator<String, String>(query);
while (it.hasNext()) {
HColumn<String, String> column = it.next();
logger.warn(column.getName() + ": " + column.getValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment