Skip to content

Java driver clustering key

opuneet edited this page Jan 10, 2014 · 4 revisions

See Java-Driver-Rows-vs-Columns for more info on how clustering keys work and what rows and columns look like at the storage level vs CQL3.

Consider this schema.

And say that this is the data that we want to insert and query.

Here are some examples on how to write Astyanax queries for this use case.

Create table
ColumnFamily<Integer, Integer> CF_CLUSTERING_KEY = 
	new ColumnFamily<Integer, Integer>("cf",
					IntegerSerializer.get(),
				        IntegerSerializer.get(),
					StringSerializer.get());
	
keyspace.createColumnFamily(CF_CLUSTERING_KEY, null);
Insert Rows
MutationBatch m = keyspace.prepareMutationBatch();
// 1st row
m.withRow(CF_CLUSTERING_KEY, 1).putColumn(1, "a1").putColumn(2, "a2").putColumn(3, "a3");
m.withRow(CF_CLUSTERING_KEY, 1).putColumn(4, "a4").putColumn(5, "a5");
// 2nd row
m.withRow(CF_CLUSTERING_KEY, 2).putColumn(1, "b1").putColumn(2, "b2");
	
m.execute();
Single Row Query
ColumnList<Integer> columns = 
keyspace.prepareQuery(CF_CLUSTERING_KEY).getRow(1).execute().getResult();

for (Column<Integer> col : columns) {
	System.out.println(col.getName() + " " + col.getStringValue());
}
Single Row Query With Column Slice
columns = keyspace.prepareQuery(CF_CLUSTERING_KEY)
		.getRow(1)
		.withColumnSlice(1,3,5)
		.execute().getResult();
		
for (Column<Integer> col : columns) {
	System.out.println(col.getName() + " " + col.getStringValue());
}
Single Row Query With Column Range Specification
columns = keyspace.prepareQuery(CF_CLUSTERING_KEY)
		.getRow(1)
		.withColumnRange(2, 5, false, 10)
		.execute().getResult();
				
for (Column<Integer> col : columns) {
	System.out.println(col.getName() + " " + col.getStringValue());
}
Single Row Query and Single Column
Column<Integer> col = keyspace.prepareQuery(CF_CLUSTERING_KEY)
		.getRow(1)
		.getColumn(4)
		.execute().getResult();
System.out.println(col.getName() + " " + col.getStringValue());
Row Slice Query Using Row Keys
Rows<Integer, Integer> rows = keyspace.prepareQuery(CF_CLUSTERING_KEY)
		.getRowSlice(1,2)
		.execute().getResult();
		
for (Row<Integer, Integer> row : rows) {
	System.out.println("Row key: " + row.getKey());
	ColumnList<Integer> cols = row.getColumns();
	for (Column<Integer> col : cols) {
		System.out.println(col.getName() + " " + col.getStringValue());
	}
}
Row Slice Query Using Column Range Specification
rows = keyspace.prepareQuery(CF_CLUSTERING_KEY)
		.getRowSlice(1,2)
		.withColumnRange(2, 5, false, 10)
		.execute().getResult();
Clone this wiki locally