liveBook · Manning

Clustering key

As explained in ScyllaDB in Action

A clustering key is a primary-key component after the partition key that orders rows within a partition.

A clustering key is every primary-key column after the partition key. It orders rows inside one partition, while the partition key determines where that partition is stored. In PRIMARY KEY (restaurant, ordered_at, food), restaurant is the partition key; ordered_at and food are clustering keys. section 2.2.2 section 3.3.2

Rows follow clustering-key order in the sequence named. The default is ascending natural order: food reviews sort first by ordered_at, then alphabetically by food. Specify an order deliberately when query results need a different sequence, such as newest items first. section 2.2.2 section 3.3.2

Show recent article summaries first

An article-summary table partitions rows by author_id and uses id as its clustering key. WITH CLUSTERING ORDER BY (id DESC) puts the most recent article IDs first for each author. section 5.3.2

Listing 5.4 article_summaries_by_author stores summaries by author
cqlsh: reviews> CREATE TABLE article_summaries_by_author(
    author_id TIMEUUID,
    id TIMEUUID,
    title TEXT,
    author_name TEXT,
    score TINYINT,
    image image,
    PRIMARY KEY (author_id, id)
) WITH CLUSTERING ORDER BY (id DESC);

This CQL definition places author_id first as the partition key, then orders each author's article summaries by id descending. section 5.3.2

Clustering order also shapes valid reads. With a multi-column primary key, restrictions must begin with the partition key and continue through consecutive columns. Skipping an earlier clustering-key column prevents restricting a later one because the on-disk order cannot be used efficiently. section 7.1.1

How ScyllaDB in Action covers it

How deep it goes
Defines partition-local ordering, default directions, explicit CQL ordering, and the consecutive-column read rule.
Examples
Uses food reviews ordered by time and food, plus article summaries ordered by descending article ID.
What it assumes
Builds from primary keys and partition keys while introducing clustering keys as their non-partition portion.
What you can do after
Apply it via CQL to order partition-local results and write queries using consecutive primary-key columns.
How it connects
Connects primary keys, partition keys, CQL queries, denormalization, and table design.

Also explained in

Compare how 2 books explain clustering key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ScyllaDB in Action. The section links point to the parts of the book it draws on.