Updating denormalized data in Cassandra - cassandra

I'm trying to build a news feed system using Cassandra, I was thinking of using a fan out approach wherein if a user posts a new post, I'll write a new record in all of his friends' feed table. The table structure looks like:
CREATE TABLE users (
user_name TEXT,
first_name TEXT,
last_name TEXT,
profile_pic TEXT,
PRIMARY KEY (user_name)
);
CREATE TABLE user_feed (
user_name TEXT,
posted_time TIMESTAMP,
post_id UUID,
posted_by TEXT, //posted by username
posted_by_profile_pic TEXT,
post_content TEXT,
PRIMARY KEY ((user_name), posted_time)
) WITH CLUSTERING ORDER BY(posted_time desc);
Now, I can get a feed for a particular user in a single query all fine. What if the user who has posted a feed updates his profile pic. How do I go about updating the data in user_feed table?

You can use batch statements to achieve atomicity at your updates. So in this case you can create a batch with the update on tables users and user_feed using the same user_name partition key:
BEGIN BATCH
UPDATE users SET profile_pic = ? WHERE user_name = ?;
UPDATE user_feed SET posted_by_profile_pic = ? WHERE user_name = ?;
APPLY BATCH;
Take a look at CQL Batch documentation

Related

Internal network application data model with Cassandra

I'm working on designing an application which will enable users to send requests to connect with each other, see their sent or received requests, make notes during their interactions for later reference if connected, and remove users from their contact lists.
In a RDBMS, the schema would be:
table User with column
uid (a unique string for each user)
table Request with columns:
from - user id
to - user id Primary Key (from, to)
created - timestamp
message - string
expiry - timestamp
table Connection with columns:
from - user id
to - user id
Primary Key (from, to)
notes - String
created - timestamp
modified - timestamp
isFavourite - to is a favourite of from user, value 0 or 1
isActive - soft delete, value 0 or 1
pairedConnection - shows whether the connection between to and from was deactivated (the to user removed the from user from its contact list), value 0 or 1
The queries I anticipate to be needed are:
find the sent requests for a user
find the received requests for a user
find all the active contacts of a given user
find all the favourites of a user
find all the users who deleted the given from user from their lists
update the notes taken by a user when meeting another user he is connected with
update user as favourite
mark connection for soft deletion
I'm trying to model this in Cassandra, but feel confused about the keys to choose for max efficiency.
So far, I have the following ideas, and would welcome feedback from more experienced Cassandra users:
create table users(
uid text PRIMARY KEY
);
create table requestsByFrom(
from text,
to text,
message text,
created timestamp,
expiry timestamp,
PRIMARY KEY (from,to)
create table requestsByTo(
from text,
to text,
message text,
created timestamp,
expiry timestamp,
PRIMARY KEY (to,from)
);
create table connections(
from text,
to text,
notes text,
created timestamp,
modified timestamp,
isFavourite boolean,
isActive boolean,
pairedConnection boolean,
PRIMARY KEY (from,to)
);
create table activeConnections(
from text,
to text,
isActive boolean,
PRIMARY KEY (from,isActive)
);
create table favouriteConnections(
from text,
to text,
isFavourite boolean,
PRIMARY KEY (from, isFavourite)
);
create table pairedConnection(
from text,
to text,
pairedConnection boolean,
PRIMARY KEY ((from,to), pairedConnection)
);
Cassandra has a different paradigm to RDBMS, and this is more evident with the way that the data modeling has to be done. You need to keep in mind that denormalization is preferred, and that you'll have repeated data.
The tables definition should be based on the queries to retrieve the data, this is partially stated in the definition of the problem, for instance:
find the sent requests for a user
Taking the initial design of the table requestsByFrom, an alternative will be
CREATE TABLE IF NOT EXISTS requests_sent_by_user(
requester_email TEXT,
recipient_email TEXT,
recipient_name TEXT,
message TEXT,
created TIMESTAMP
PRIMARY KEY (requester_email, recipient_email)
) WITH default_time_to_live = 864000;
Note that from is a restricted keyword, the expiry information can be set with the definition of the default_time_to_live clause (TTL) which will remove the record after the time defined; this value is the amount of seconds after the record is inserted, and the example is 10 days (864,000 seconds).
The primary key is suggested to be the email address, but it can also be an UUID, name is not recommended as there can be multiple persons sharing the same name (like James Smith) or the same person can have multiple ways to write the name (following the example Jim Smith, J. Smith and j smith may refer to the same person).
The name recipient_name is also added as it is most likely that you'll want to display it; any other information that will be displayed/used with the query should be added.
find the received requests for a user
CREATE TABLE IF NOT EXISTS requests_received_by_user(
recipient_email TEXT,
requester_email TEXT,
requester_name TEXT,
message TEXT,
created TIMESTAMP
PRIMARY KEY (recipient_email, requester_email)
) WITH default_time_to_live = 864000;
It will be preferred to add records to requests_sent_by_user and requests_received_by_user at the same time using a batch, which will ensure consistency in the information between both tables, also the TTL (expiration of the data) will be the same.
storing contacts
In the question there are 4 tables of connections: connections, active_connections, favourite_connections, paired_connections, what will be the difference between them? are they going to have different rules/use cases? if that is the case, it makes sense to have them as different tables:
CREATE TABLE IF NOT EXISTS connections(
requester_email TEXT,
recipient_email TEXT,
recipient_name TEXT,
notes TEXT,
created TIMESTAMP,
last_update TIMESTAMP,
is_favourite BOOLEAN,
is_active BOOLEAN,
is_paired BOOLEAN,
PRIMARY KEY (requester_email, recipient_email)
);
CREATE TABLE IF NOT EXISTS active_connections(
requester_email TEXT,
recipient_email TEXT,
recipient_name TEXT,
last_update TIMESTAMP,
PRIMARY KEY (requester_email, recipient_email)
);
CREATE TABLE IF NOT EXISTS favourite_connections(
requester_email TEXT,
recipient_email TEXT,
recipient_name TEXT,
last_update TIMESTAMP,
PRIMARY KEY (requester_email, recipient_email)
);
CREATE TABLE IF NOT EXISTS paired_connections(
requester_email TEXT,
recipient_email TEXT,
recipient_name TEXT,
last_update TIMESTAMP,
PRIMARY KEY (requester_email, recipient_email)
);
Note that the boolean flag is removed, the logic is that if the record exists in active_connections, it will be assumed that it is an active connection.
When a new connection is created, it may have several records in different tables; to bundle all those inserts or updates, it is preferred to use batch
find all the active contacts of a given user
Based on the proposed tables, if the requester's email is test#email.com:
SELECT * FROM active_connections WHERE requester_email = 'test#email.com'
update user as favourite
It will be a batch updating the record in connections and adding the new record to favourite_connections:
BEGIN BATCH
UPDATE connections
SET is_favourite = true, last_update = dateof(now())
WHERE requester_email ='test#email.com'
AND recipient_email = 'john.smith#test.com';
INSERT INTO favourite_connections (
requester_email, recipient_email, recipient_name, last_update
) VALUES (
'test#email.com', 'john.smith#test.com', 'John Smith', dateof(now())
);
APPLY BATCH;
mark connection for soft deletion
The information of the connection can be kept in connections with all the flags disabled, as well as the records removed from active_connections, favourite_connections and paired_connections
BEGIN BATCH
UPDATE connections
SET is_active = false, is_favourite = false,
is_paired = false, last_update = dateof(now())
WHERE requester_email ='test#email.com'
AND recipient_email = 'john.smith#test.com';
DELETE FROM active_connections
WHERE requester_email = 'test#email.com'
AND recipient_email = 'john.smith#test.com';
DELETE FROM favourite_connections
WHERE requester_email = 'test#email.com'
AND recipient_email = 'john.smith#test.com';
DELETE FROM paired_connections
WHERE requester_email = 'test#email.com'
AND recipient_email = 'john.smith#test.com';
APPLY BATCH;

Chat - app (data model) with cassandra

I need to create chat between users using cassandra.
I have created table chat_messages like this :
create table chat_messages(
user_name text,
to_user text,
content text,
content_id uuid,
created_at timestamp,
primary key((user_name,to_user),created_at)
);
I want with one select get messages between two users.
insert into chat_messages(user_name, to_user, content, content_id, created_at) values('u1','u2','hi u2',uuid(),toTimestamp(now()));
insert into chat_messages(user_name, to_user, content, content_id, created_at) values('u2','u1','hi u1',uuid(),toTimestamp(now()));
I want to get hi u1 hi u2.
With your actual table structure you can use :
SELECT content
FROM chat_messages
WHERE user_name IN ('u1', 'u2')
AND to_user IN ('u1', 'u2');
But be careful using IN in WHERE clause because multiple nodes will be query.

Cassandra - how to update a record with a compound key

In the process of learning Cassandra and using it on a small pilot project at work. I've got one table that is filtered by 3 fields:
CREATE TABLE webhook (
event_id text,
entity_type text,
entity_operation text,
callback_url text,
create_timestamp timestamp,
webhook_id text,
last_mod_timestamp timestamp,
app_key text,
status_flag int,
PRIMARY KEY ((event_id, entity_type, entity_operation))
);
Then I can pull records like so, which is exactly the query I need for this:
select * from webhook
where event_id = '11E7DEB1B162E780AD3894B2C0AB197A'
and entity_type = 'user'
and entity_operation = 'insert';
However, I have an update query to set the record inactive (soft delete), which would be most convenient by partition key in the same table. Of course, this isn't possible:
update webhook
set status_flag = 0
where webhook_id = '11e8765068f50730ac964b31be21d64e'
An example of why I'd want to do this, is a simple DELETE from an API endpoint:
http://myapi.com/webhooks/11e8765068f50730ac964b31be21d64e
Naturally, if I update based on the composite key, I'd potentially inactivate more records than I intend to.
Seems like my only choice, doing it the "Cassandra Way", is to use two tables; the one I already have and one to track status_flag by webhook_id, so I can update based on that id. I'd then have to select by webhook_id in the first table and disable it there as well? Otherwise, I'd have to force users to pass all the compound key values in the URL of the API's DELETE request.
Simple things you take for granted in relational data, seem to get complex very quickly in Cassandraland. Is this the case or am I making it more complicated than it really is?
You can add webhook to your primary key.
So your table defination becomes somethign like this.
CREATE TABLE webhook (
event_id text,
entity_type text,
entity_operation text,
callback_url text,
create_timestamp timestamp,
webhook_id text,
last_mod_timestamp timestamp,
app_key text,
status_flag int,
PRIMARY KEY ((event_id, entity_type, entity_operation),webhook_id)
Now lets say you insert 2 records.
INSERT INTO dev_cybs_rtd_search.webhook(event_id,entity_type,entity_operation,status_flag,webhook_id) VALUES('11E7DEB1B162E780AD3894B2C0AB197A','user','insert',1,'web_id');
INSERT INTO dev_cybs_rtd_search.webhook(event_id,entity_type,entity_operation,status_flag,webhook_id) VALUES('12313131312313','user','insert',1,'web_id_1');
And you can update like following
update webhook
set status_flag = 0
where webhook_id = 'web_id' AND event_id = '11E7DEB1B162E780AD3894B2C0AB197A' AND entity_type = 'user'
AND entity_operation = 'insert';
It will only update 1 record.
However you have to send all the things defined in your primary key.

Reference logical aggregates - CQL

I have a univerity assignment that consists in working with CQL and Cassandra.
In the first part of the assignment I have to "identify the
reference logical aggregates, thus providing a row-oriented view of schema information, and point out attributes which model relationships", but I don't understand what is a "reference logical aggregate".
The schema is the following (it's not created by me, I downloaded it with the assignment):
DROP KEYSPACE gameindustry;
CREATE KEYSPACE gameindustry WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
USE gameindustry;
CREATE TYPE fullname (
firstname text,
lastname text
);
CREATE TABLE games (
name text PRIMARY KEY,
description text,
tags set<text>
);
CREATE TABLE tags (
tag text PRIMARY KEY,
games set<text>
);
CREATE TABLE users (
email text PRIMARY KEY,
password text,
name fullname,
notes text,
games set<text>
);
CREATE TABLE user_games (
user text,
game text,
PRIMARY KEY (user, game)
);
CREATE TABLE friends (
user text,
friend text,
PRIMARY KEY (user, friend)
);
CREATE TABLE matches (
user text,
game text,
when timestamp,
score int,
PRIMARY KEY (game, when, user),
);

Suggestion for Cassandra Data Model for Chat application

I am currently developing a chat application on top of Cassandra.
A conversation
can happen between one or more users.
can have more than one message.
will be marked read if all the messages are read.
In an extreme case, conversation can have upto 100 users.
I want to solve the following query requirements.
Show top n recent conversations for a given user.
Show count of unread conversations (not messages) for a given user.
Any suggestions on Data Modelling?
You can start with this structure :
CREATE TABLE conversation (
conversation_id timeuuid,
user_from varchar,
user_to varchar,
message text,
message_read boolean,
message_date timestamp,
conversation_read boolean static,
PRIMARY KEY ((conversation_id, user_to), message_date)
)
WITH CLUSTERING ORDER BY (user_from ASC, message_date ASC);
All your queries will be base on conversation_id and user_to. Message will be ordered by creation date. I think this structure can support the main purpose of a chat.
For the two queries, you need to have other denormalized tables like :
1) Show top n recent conversations for a given user.
CREATE TABLE user_message (
user varchar,
message text,
message_date timestamp,,
PRIMARY KEY ((user), message_date)
)
WITH CLUSTERING ORDER BY (message_date DESC);
SELECT message
FROM user_message
WHERE user = 'some user'
LIMIT 10;
2) Show count of unread conversations (not messages) for a given user.
CREATE TABLE user_conversations (
user varchar,
conversation_id timeuuid,
conversation_read boolean,
PRIMARY KEY((user), conversation_read, conversation_id)
);
SELECT COUNT(1)
FROM user_conversations
WHERE user = 'some user'
AND conversation_read = false;
If you can use cassandra 3.X, you can use MATERIALIZED VIEW to manager data denormalization.
Hope this can help you.

Resources