Skip to content

Instantly share code, notes, and snippets.

@jasobrown
Created February 14, 2012 22:58
Show Gist options
  • Select an option

  • Save jasobrown/1831396 to your computer and use it in GitHub Desktop.

Select an option

Save jasobrown/1831396 to your computer and use it in GitHub Desktop.
An example of using astyanax, a Java client for Cassandra (excerpt from http://slidesha.re/wkf57g)
public class AstyanaxSample {
/** entry point for the cluster; read the docs at https://github.com/Netflix/astyanax/wiki/Getting-Started */
private static final Keyspace keyspace = null; //null used for compilation; don't try this at home
/** declare/define the column family object */
private static final ColumnFamily<String, MyCompositeColumn> ALLOCS_COLUMN_FAMILY =
new ColumnFamily<String, MyCompositeColumn>("cust_allocs", StringSerializer.get(),
new AnnotatedCompositeSerializer<MyCompositeColumn>(MyCompositeColumn.class));
/** annotated class to represent the composite column type for an allocation */
private static class MyCompositeColumn {
@Component(ordinal = 0)
private Integer testId;
@Component(ordinal = 1)
private String field;
public MyCompositeColumn() { }
public Integer getTestId() { return testId; }
public void setTestId(Integer testId) { this.testId = testId; }
public String getField() { return field; }
public void setField(String field) { this.field = field; }
}
/* get all allocations for a customer */
public List<Allocation> get(Long customerId){
try{
/* construct the query and send it to cassandra */
ColumnList<MyCompositeColumn> columns = keyspace
.prepareQuery(ALLOCS_COLUMN_FAMILY)
.getKey(custIdToKey(customerId))
.execute()
.getResult();
return readColumns(columns);
} catch (Exception e){
// don't do this at home
return null;
}
/* pull data out of the columns and instantiate/populate the Allocation list */
private List<Allocation> readColumns(ColumnList<MyCompositeColumn> columns){
List<Allocation> list = new ArrayList<Allocation>();
Allocation cur = null;
for(Column<MyCompositeColumn> column : columns){
Integer testId = column.getName().testId;
if(cur == null || !cur.getTestID().equals(testId)){
cur = new Allocation();
cur.setTestID(testId);
list.add(cur);
}
String field = column.getName().field;
if(field.equals("cell"))
cur.setCell(Integer.valueOf(column.getIntegerValue()));
else if(field.equals("enabled"))
cur.setEnabled(column.getStringValue());
}
return list;
}
}
@jasobrown
Copy link
Copy Markdown
Author

Comments intentionally short to not get in the way of the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment