1
votes

I want to know where and when to use composite column and composite key in Cassandr

1

1 Answers

2
votes

Composite-key usage can be useful in many scenario.

Imagine a table users in which you have a user id (uuid) as primary key (single-key) You can't query this table unless you know the id of the user (ignore secondary indexes at the moment).

Now let's consider a table in which you doesn't use anymore the id as primary key, but you use a composite key made of (name, surname, email)

Now you can query your users by knowing

name
name - surname
name - surname - emails

primary key must be unique and in this scenario the email should guarantee that the user is unique. Take care, to query by email you must know both name and surname, to query for the surname you must know the name (this is true unless you don't use a particular way to model yours data).

CREATE TABLE users (
  name text,
  surname text,
  email text,
  age int,
  address text,
  id uuid,
  PRIMARY KEY (name, surname, email)
)

Another useful scenario can be for data-sorting. Imagine you have a table in which you keep tweets (identified by a time uuid) made from a tweeter (identified by a uuid).

In cassandra the first part of the key is known as Partition key, the remaining is known as clustering key. For the same partition key data can be sorted by a clustering key

CREATE TABLE tweets (
  tweeter_id uuid,
  tweet_id timeuuid,
  content text,
  PRIMARY KEY (tweeter_id, tweet_id)
) WITH CLUSTERING ORDER BY (tweet_id DESC)

In this scenario once you ask cassandra the tweets made by a tweeter they will be time-sorted for free.

Cheers, Carlo