invinc4u
invinc4u

Reputation: 1185

How to maintain the last N versions of primary key in Cassandra?

CREATE TABLE user_logins (
    user_id bigint PRIMARY KEY,
    login_time timestamp
)WITH CLUSTERING ORDER BY (login_time DESC);

Is there a way in which I can maintain the last 3 versions of a key in Cassandra ? If I add more rows with this primary key, it should automatically truncate delete the oldest row to ensure that only 3 rows are maintained at a time ? For example, for every user only maintain their last 3 login timestamps.

One way is I use collections like list to store the timestamp and then do a read-before-write to fetch the current value, modify it and persist it? Is there any other way I can have a TTL like functionality without the notion of time but maintaining last N versions ?

Upvotes: 3

Views: 156

Answers (1)

nevsv
nevsv

Reputation: 2466

There's no such functionality in Cassandra, you will need to work with workarounds.

One way, as you said, is to work with lists/maps/sets/UDTs and update( read-before-write) them all the time.

Another way is to have N tables, user_logins_N for example, and on the client/server side you will round robin on these tables. Each table will have only one version of the key with one login timestamp, and you will always save only N versions of logins.

Third way, is to do some background house keeping process, that will go through keys and delete old/irrelevant logins.

Upvotes: 2

Related Questions