You can't explicitly create a primary key in Cassandra like you might in other databases. Instead, you define it when creating your table. Here's how:
-
Define the Primary Key in the CREATE TABLE Statement:
When you create a table, you specify the primary key as part of the table definition. This is done using the
PRIMARY KEY
clause.Example:
CREATE TABLE users ( user_id uuid PRIMARY KEY, username text, email text );
In this example,
user_id
is the primary key. -
Composite Primary Keys:
Cassandra supports composite primary keys, which consist of multiple columns. You need to define the clustering columns within the
PRIMARY KEY
clause.Example:
CREATE TABLE orders ( customer_id uuid, order_date timestamp, order_id int, product_name text, PRIMARY KEY (customer_id, order_date, order_id) );
Here, the primary key is composed of
customer_id
,order_date
, andorder_id
.customer_id
is the partition key, andorder_date
andorder_id
are the clustering columns.
Key Points:
- Partition Key: The first column in a composite primary key is the partition key. It determines which node in the Cassandra cluster will store the data.
- Clustering Columns: The remaining columns in a composite primary key are clustering columns. They define the order of data within a partition.
- Data Consistency: Cassandra guarantees that data within a partition is consistent.
Practical Insights:
- Choosing the Right Primary Key: Carefully consider the access patterns and querying needs of your application when designing your primary key.
- Performance Optimization: A well-designed primary key can significantly improve query performance.
Remember: Cassandra doesn't allow you to modify the primary key of a table after it's been created. You'll need to create a new table with the desired primary key structure and migrate your data.