Uniqueness Constraint

elandau edited this page May 1, 2012 · 1 revision
Clone this wiki locally

Cassandra does not provide built in uniqueness constraint on row keys. Astyanax provides a recipe which follows a write/read sequence that guarantees uniqueness constraint.

The following example shows how to set up a uniqueness constraint on a column family that has long key type and String columns name type. The assumption here is that the same CF is used to store data as well as the columns used to guarantee uniqueness.

UniquenessConstraintWithPrefix<Long> unique = new UniquenessConstraintWithPrefix<Long>(keyspace, CF_DATA)
    .setPrefix("unique_") // This is optional and can be used to distinguish between the unique column name and real columns
    .setTtl(60);  // This is optional
 
 try {
    String column = unique.isUnique(someRowKey);
    if (column == null) {
        // Not unique
    }
    else {
        // Is unique.
        // Make sure to store the returned column with your data otherwise it will TTL and uniquess will be lost
    }
} catch (ConnectionException e) {
}

QUORUM consistency level is used by default but can be changed by calling .setConsistencyLevel(ConsistencyLevel.CL_QUORUM_EACH)