2

Considere the following case regarding Cassandra database: I must perform a batch statement with some related data, e.g: table users and table users_by_username. I want to insert on user creation data on both tables. It's a transaction. In Cassandra documentation says the batch statement cannot reach multiple partitions. If I model the primary key as a composite key like following :

CREATE TABLE IF NOT EXISTS user(
  id text,
  tpe text,
  username text,
  PRIMARY KEY((tpe, id))
);

CREATE TABLE IF NOT EXISTS user_by_username(
  username text,
  tpe text,
  id text,
  PRIMARY KEY((tpe, username))
);

Example of rows:

user: ('1', 'users', 'lucasrpb') user_by_username: ('lucasrpb', 'users', '1')

My doubt: will data be on the same partition to be able to do the batch?

1 Answer 1

2

Partitions are within a table, not across tables. However, the token for data, which is used to identify which replicas will host the data, is based on the partition key (the first column in the primary key, or the first column(s) surrounded in parenthesis).

In your case, the partition key for 'user' is (tpe, id) and user_by_username is (tpe, username). Because of this, the token for the data will likely not be the same.

If the primary key for user was (tpe, id), user_by_username (tpe, username), the partition key for each case would be tpe, therefore granted tpe was the same, the token would be the same and therefore the data would be stored on the same replicas.

In any case, I would not recommend batching operations to update user_by_username and user together, but it'd be better in the case where the partition key was the same as less C* nodes need to be written to in the batch.

Since the only difference between your tables is your primary key, I think a good candidate for you if you are on a 3.0+ version would be to look into materialized views which were introduced in 3.0. With this you could set up a user_by_username view off of the user table like:

CREATE MATERIALIZED VIEW user_by_username AS 
SELECT * FROM users 
WHERE username IS NOT NULL
PRIMARY KEY ((tpe, username));

This way you only have to make changes to user, which will then be propagated to user_by_username for you.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.