A clustering key is the part of a Cassandra primary key that orders rows inside a partition. It controls storage order within that partition, not necessarily the order returned by a query. section 4.1.2
Use a partition key to choose where rows belong, then use a clustering key to arrange related rows there. This supports Cassandra’s read-oriented, denormalized data model. section 4.1.2
Putting newest tacos first
A Taco entity can use its UUID id as a partition key and its createdAt property as a clustered primary-key column. Setting descending ordering makes newer tacos appear first within that partition. section 4.1.3
When mapping a clustering key with Spring Data Cassandra:
- Mark the property with @PrimaryKeyColumn and set its type to PrimaryKeyType.CLUSTERED. section 4.1.3
- Choose an ordering direction when the application needs rows arranged chronologically or in reverse chronological order. section 4.1.3
- Model the partition and clustering keys together rather than treating Cassandra persistence as a simple replacement of JPA annotations. section 4.1.2
Listing 4.1 Annotating the Taco class for Cassandra persistence
package tacos;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.data.cassandra.core.cql.Ordering;
import org.springframework.data.cassandra.core.cql.PrimaryKeyType;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.core.mapping.Table;
import com.datastax.oss.driver.api.core.uuid.Uuids;
import lombok.Data;
@Data
@Table("tacos") #1
public class Taco {
@PrimaryKeyColumn(type=PrimaryKeyType.PARTITIONED) #2
private UUID id = Uuids.timeBased();
@NotNull
@Size(min = 5, message = "Name must be at least 5 characters long")
private String name;
@PrimaryKeyColumn(type=PrimaryKeyType.CLUSTERED, #3
ordering=Ordering.DESCENDING)
private Date createdAt = new Date();
@Size(min=1, message="You must choose at least 1 ingredient")
@Column("ingredients") #4
private List<IngredientUDT> ingredients = new ArrayList<>();
public void addIngredient(Ingredient ingredient) {
this.ingredients.add(TacoUDRUtils.toIngredientUDT(ingredient));
}
}
Inspect the Taco Cassandra mapping to see how partitioned and clustered primary-key annotations fit into a realistic domain class. section 4.1.3

