Within storm-cassandra-cql, I'm building out a state implementation that is capable of making incremental state changes. (Read-Modify-Write) It leverages Cassandra 2.0's lightweight transactions, and the ability to perform a conditional update. (more on the rationale for incremental state changes later)
As I was implementing it, I couldn't find any good examples that showed how to implement conditional updates using the QueryBuilder in the CQL3 java driver.
So, here you go:
// Now let's conditionally update where it is true Update updateStatement = QueryBuilder.update(SalesAnalyticsMapper.KEYSPACE_NAME,
SalesAnalyticsMapper.TABLE_NAME);
updateStatement.with(QueryBuilder.set(VALUE_NAME, 15));
Clause clause = QueryBuilder.eq(KEY_NAME, "DE");
updateStatement.where(clause);
Clause conditionalClause = QueryBuilder.eq(VALUE_NAME, 10);
updateStatement.onlyIf(conditionalClause);
this.executeAndAssert(updateStatement, "DE", 15);
The key clause is the conditionalClause
which is appended to the statement by calling the
onlyIf
method on the Update
object.
The above code will set the value of v=15, where k='DE', but only if the current value of v is still 10. In the storm-cassandra-cql use case, this will cause the state to increment only if the value that was read hasn't changed underneath of it.I've encapsulated a couple conditional updates in a unit test within storm-cassandra-cql. Have a look to see a more complete set of calls (with comments and assertions).
No comments:
Post a Comment