Skip to content

Multi row uniqueness constraint

elandau edited this page May 22, 2012 · 2 revisions

The purpose of this recipe to optimize a uniqueness constraint check on multiple row keys in multiple column families within the same keyspace. The recipe works by first writing a unique column to ALL rows being checked. Each row is then read in sequence to verify if there is a collision. If no collisions are identified the unique lock columns are committed without a TTL or expiration date. Otherwise all columns are rolled back.

For example, let’s say you need to ensure that a both a username and email address are unique as part of a sign up operation.


MultiRowUniquenessConstraint unique = new MultiRowUniquenessConstraint(keyspace)
    .withRow(USERNAME_CF, "someusername")
    .withRow(EMAIL_CF, "[email protected]");

try {
    unique.acquire();
    String uniqueColumn = singleUnique.readUniqueColumn();
    Assert.assertEquals("abc", uniqueColumn);
    LOG.info("UniqueColumn: " + uniqueColumn);
}
catch (NotUniqueException e) {
    // At least one of the row keys is already taken
}
catch (Exception e) {
    // Exception such as a general failure talking to cassandra
}