cassandra The PRIMARY KEY syntax


Example

Declaring a key

The table creation statement should contain a PRIMARY KEY expression. The way you declare it is very important. In a nutshell:

PRIMARY KEY(partition key)
PRIMARY KEY(partition key, clustering key)

Additional parentheses group multiple fields into a composite partition key or declares a compound composite key.

Examples

Simple primary key:

PRIMARY KEY (key)

key is called the partition key.

(for simple primary key, it is also possible to put the PRIMARY KEY expression after the field, i.e. key int PRIMARY KEY, for example).

Compound primary key:

PRIMARY KEY (key_part_1, key_part_2)

Contrary to SQL, this does not exactly create a composite primary key. Instead, it declares key_part_1 as the partition key and key_part_2 as the clustering key. Any other field will also be considered part of the clustering key.

Composite+Compound primary keys:

PRIMARY KEY ((part_key_1, ..., part_key_n), (clust_key_1, ..., clust_key_n))

The first parenthese defines the compound partition key, the other columns are the clustering keys.

Syntax summary

  • (part_key)
  • (part_key, clust_key)
  • (part_key, clust_key_1, clust_key_2)
  • (part_key, (clust_key_1, clust_key_2))
  • ((part_key_1, part_key_2), clust_key)
  • ((part_key_1, part_key_2), (clust_key_1, clust_key_2))