This are the slides from the intensive Cassandra Workshop I held in Madrid as a Meetup: http://www.meetup.com/Madrid-Cassandra-Users/events/225944063/ They cover all the Cassandra core concepts, and data modelling basic ones to get up and running with Cassandra.
4. @calonso
MYDRIVE SOLUTIONS
• World leading driver profiling company
• Using technology and data to understand
how to improve driving behaviour
• Recently acquired by the Generali Group
• @_MyDrive / http://mydrivesolutions.com
• We are hiring!!
7. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’m rolling in production with Cassandra
8. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’m rolling in production with Cassandra
9. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’ve heard about Cassandra and
want to get my hands on it
I’m rolling in production with Cassandra
10. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’ve never heard about SQL
I’ve heard about Cassandra and
want to get my hands on it
I’m rolling in production with Cassandra
11. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’ve never heard about SQL
I don’t know what I’m doing here
I’ve heard about Cassandra and
want to get my hands on it
I’m rolling in production with Cassandra
12. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’ve never heard about SQL
I don’t know what I’m doing here
I’ve heard about Cassandra and
want to get my hands on it
I’m evaluating Cassandra as
a potential solution
I’m rolling in production with Cassandra
13. @calonso
ANDYOU?
I’m a Db admin (ORACLE?) and I want to learn Cassandra
I’ve never heard about NoSQL
I’ve never heard about SQL
I don’t know what I’m doing here
I’ve heard about Cassandra and
want to get my hands on it
I’ve using Cassandra for some
tests and want to go deeper
I’m evaluating Cassandra as
a potential solution
I’m rolling in production with Cassandra
14. @calonso
CASSANDRA
• A.k.a Alexandra or Kassandra
• Daughter of King Priam and Queen Hecuba
ofTroy.
• Apollo gave her the power of prophecy to
seduce her. She refused and then Apollo spat
on her mouth cursing her never to be
believed.
• https://en.wikipedia.org/wiki/Cassandra
15. @calonso
CASSANDRA
• Open Source distributed database
management system
• Initially developed at Facebook
• Inspired by Amazon’s Dynamo and Google
BigTable papers
• Became Apache top-level project in Feb, 2010
• Nowadays developed by DataStax
24. @calonso
CASSANDRA
• Fast Distributed NoSQL Database
• High Availability
• Linear Scalability => Predictability
• No SPOF
• Multi-DC
• Horizontally scalable => $$$
• Not a drop in replacement for RDBMS
31. @calonso
DISTRIBUTIONS
• Integrated Solr for Multi-DC Search
• Integrated Spark for Analytics
• Free Startup Program
• Expert support
• Focused on stable releases for enterprises
• http://www.datastax.com/products/datastax-enterprise
32. @calonso
CASSANDRA:YES
• If you need:
• No SPOF
• Linear horizontal scalability in commodity hardware
• Real-time writes
• Reliable data replication across distributed data centres
• Clearly defined schema in a NoSQL environment
33. @calonso
CASSANDRA: NO
• If you need:
• ACID transactions with rollback
• Justification for high-end software
35. @calonso
REVIEW QUESTIONS
What do consistency, availability and partition tolerance mean?
Consistency:All clients have the exact same value for the whole data set at any given point.
36. @calonso
REVIEW QUESTIONS
What do consistency, availability and partition tolerance mean?
Consistency:All clients have the exact same value for the whole data set at any given point.
Availability:All clients can read and write to the system at any given point.
37. @calonso
REVIEW QUESTIONS
What do consistency, availability and partition tolerance mean?
Consistency:All clients have the exact same value for the whole data set at any given point.
Availability:All clients can read and write to the system at any given point.
Partition tolerance: Whether or not the system tolerates a node being
disconnected from the system.
39. @calonso
REVIEW QUESTIONS
Where does Cassandra fit within the CAP Theorem?
AP: Cassandra trades off consistency in order to guarantee
availability and partition tolerance, but in a configurable way, so it’s
up to the developer where to sit for each query.
41. @calonso
REVIEW QUESTIONS
Which are the technological roots of Cassandra?
Google BigTable and Amazon Dynamo pulled together
by developers at Facebook
48. @calonso
CONFIGURATION
• MAX_HEAP_SIZE
• if system memory < 2G => 1/2 of it
• if between 2G and 4G => 1G
• if > 4G => 1/4 of it but no more than 8G
• HEAP_NEWSIZE
• 1/4 of MAX_HEAP_SIZE
conf/cassandra-env.sh
54. @calonso
REVIEW QUESTIONS
How would you stop a Cassandra instance running
in background in an Unix based machine?
1. Get the PID: ps aux | grep cassandra
2. Kill the process: kill <pid>
59. @calonso
NODETOOL
status: displays cluster state, load, host ID and token
info: displays node memory use, disk load, uptime …
ring: displays node status and cluster ring state
help: displays all possible commands and description
63. @calonso
CASSANDRA-STRESS
read: to execute a read-only workload
mixed: executes mixed workload
user: user defined schema and workloads
write: to execute a write-only workload
70. @calonso
REVIEW QUESTIONS
Name and describe two non CQL commands
allowed in cqlsh.
CAPTURE COPY DESCRIBE EXPAND PAGING SOURCE
CONSISTENCY DESC EXIT HELP SHOW TRACING
76. @calonso
CLUSTER COMPONENTS
• Column:The smallest key-value pair.
• Row: Collection of columns. Identified by a row key.
• Partition: Bucket containing several rows. Identified by
a token.
• Node: a Cassandra instance. Contains a token range.
• Rack: a logical set of nodes
• Data Center: a logical set of racks.
• Cluster:The full set of nodes. Covers a whole token
ring.
78. – Wikipedia
“Hashing is the transformation of a string of characters into a usually
shorter fixed-length value or key that represents the original string.
Hashing is used to index and retrieve items in a database because it is
faster to find the item using the shorter hashed key than to find it using
the original value.”
79. @calonso
CONSISTENT HASHING
• Data is stored in partitions, identified by a
unique token within the range
(-2^63 - 2^63)
• Nodes contain partition ranges.
80. @calonso
THE PARTITIONER
• System running on each node that
computes hashes through a hash function.
• Various partitioners available.
• Default is murmur3
• All nodes MUST use the same!!!!
Hash function
“Carlos” 185664
1773456738847666528349
-894763734895827651234
85. @calonso
THE COORDINATOR
• The node designated to coordinate a particular query.
• ANY node can coordinate ANY request.
• No SPOF: One of the main Cassandra’s principles.
• The driver chooses which node will coordinate
86. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
87. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
88. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
f81d4fae-…
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
89. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
f81d4fae-…
834
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
90. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
f81d4fae-…
834
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
91. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
f81d4fae-…
834
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
92. @calonso
A FULL EXAMPLE
CREATETABLE users (
id UUID,
nameVARCHAR,
surnameVARCHAR,
birthdateTIMESTAMP,
PRIMARY KEY(id)
);
SELECT * FROM users WHERE
id = ‘f81d4fae-7dec-11d0-a765-00a0c91e6bf6’;
DriverClient
DriverPartitioner
f81d4fae-…
834
CREATE KEYSPACE test WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3 };
CONSISTENCY QUORUM;
117. @calonso
CONSISTENCY LEVEL
How many nodes must to successfully
write for the write to be success?
How many nodes must send their data
for the read to be success?
131. @calonso
READ REPAIR
What if nodes disagree?
DriverClient
CL >= QUORUM
Madrid: 123
Salamanca: 125
SELECT city FROM …
132. @calonso
READ REPAIR
What if nodes disagree?
DriverClient
CL >= QUORUM
Madrid: 123
Salamanca: 125
London: 150
SELECT city FROM …
133. @calonso
READ REPAIR
What if nodes disagree?
DriverClient
CL >= QUORUM
Madrid: 123
Salamanca: 125
London: 150London
SELECT city FROM …
134. @calonso
READ REPAIR
And if CL < QUORUM?
The coordinator will issue a read_repair based on
read_repair_chance table property.
CREATETABLE users (
…
) WITH read_repair_chance = 0.1;
135. @calonso
MANUAL REPAIR
Last defense against data entropy.
The nodetool repair command makes all data on a node
consistent with the latest replicas in the cluster.
—partitioner-range: option to restrict repair to node’s primary range only
136. @calonso
MANUAL REPAIR
• Run nodetool repair:
• Recovering a failed node
• Increasing RF
• Periodically on every node
• Sequentially
• Once a week
140. @calonso
SNITCH
• Allows the node to know its rack and data center topology.
• Enables replication in different racks
141. @calonso
SNITCH
• GossipingPropertyFileSnitch: config from cassandra-rackdc.properties and
propagated by gossiping
• Ec2Snitch:Amazon EC2 aware. Single region. Single DC.Availability zone = Rack
• Ec2MultiRegionSnitch: Multiple regions. Region = DC.
• …
145. @calonso
REVIEW QUESTIONS
What is the function of the partitioner?
The partitioner’s function is to hash keys.Then the rest of the
cluster uses that output to determine where the data should live.
147. @calonso
REVIEW QUESTIONS
Can a node hold a partition with a token outside
its primary range?
Yes, if it’s replicating data for some other node, or if it’s holding a hint.
151. @calonso
REVIEW QUESTIONS
What is the function of the nodetool repair
operation?
Synchronising replicas.
Ensuring the node’s data is the most recent.
153. @calonso
REVIEW QUESTIONS
What is a remote coordinator?
When using multiple DCs and NetworkTopologyStrategy, at the point
of replicating in the second DC, the only node that receives the data in
that DC will coordinate the request there. Is the remote coordinator.
This is to avoid transmitting all data to all nodes from DC to DC.
155. @calonso
REVIEW QUESTIONS
How could RF and CL be tuned to ensure
immediate consistency?
• RF >= 3
• CL Write = ONE and CL Read = ALL
• CL Write = ALL and CL Read = ONE
• CL Write = QUORUM and CL Read = Quorum
162. @calonso
PRACTICETIME!
We need to build a system for an online electronic books reading site.
CREATE KEYSPACE e_library WITH REPLICATION =
{ “class”:“SimpleStrategy”,“replication_factor”: 3};
167. CQLTYPE Constants Description
ASCII strings US-ASCII character strings
BIGINT integers 64-bit signed long
BLOB blobs Arbitrary bytes (no validation), as hexadecimal
BOOLEAN booleans true or false
COUNTER integers Distributed counter value (64 bit long)
DECIMAL integers or floats Variable precision decimal
DOUBLE integers 64-bit IEEE-754 floating point
FLOAT integers, floats 32-bit IEEE-754 floating point
INET strings IP address string in IPV4 or IPV6 format
INT integers 32-bit signed integer
LIST n/a A collection of one or more ordered elements
MAP n/a A JSON style array of literals { literal: literal, literal: literal, …}
SET n/a A collection of one or more elements
TEXT strings UTF-8 encoded text
TIMESTAMP integers, strings Date + time as mills since EPOCH
TUPLE n/a Up to 32k fields
UUID uuids Standard UUID
VARCHAR strings UTF-8 encoded string
VARINT integers Arbitrary precision integer
TIMEUUID uuids Type I UUID
168. @calonso
INSERT
• CQL INSERTS are:
• Atomic: Either all the values are inserted or none
• Isolated:Two inserts on the exact same PK happen one after the other, no
mixed values.
INSERT INTO albums_by_performer (performer, year, title, genre)
VALUES (‘The Beatles’, 1966,‘Revolver’,‘Rock’);
169. @calonso
UPDATE
• Primary Key columns cannot be changed.
• Full Primary key is required as predicate.
• CQL UPDATES are:
• Atomic: Either all the values are inserted or none
• Isolated:Two inserts on the exact same PK happen one after the other, no mixed values.
UPDATE albums_by_performer
SET genre = ‘Rock’
WHERE performer = ‘The Beatles’AND
year = 1966 AND
title = ‘Revolver’;
170. @calonso
UPSERT
INSERT INTO albums_by_performer (performer, year, title, genre)
VALUES (‘The Beatles’, 1966,‘Revolver’,‘Rock’);
UPDATE albums_by_performer
SET genre = ‘Rock’
WHERE performer = ‘The Beatles’AND
year = 1966 AND
title = ‘Revolver’;
==
171. @calonso
LWT
• Use at your own discretion:
• Cassandra uses Paxos algorithm to determine if the record exists or not.
• In total 6x performance penalty.
INSERT INTO albums_by_performer (performer, year, title, genre)
VALUES (‘The Beatles’, 1966,‘Revolver’,‘Rock’) IF NOT EXISTS;
172. @calonso
PRACTICETIME!
We need to design a system that holds users. Users will have name, ID card (unique),
a phones list (home, mobile and work), birth date and an email address.
NOTE:As we haven’t studied SELECT, use
SELECT * FROM <table name>; to inspect your data.
174. @calonso
MORE DDL
ALTERTABLE album ADD cover_imageVARCHAR;
ALTERTABLE album DROP cover_image;
ALTERTABLE album ALTER cover_imageTYPE BLOB;
175. @calonso
MORE DDL
CREATETABLE albums_by_genre (
genreVARCHAR,
performerVARCHAR,
year INT,
album_titleVARCHAR,
PRIMARY KEY (
genre, performer, year, album_title)
) WITH CLUSTERING ORDER BY
(performer ASC, year DESC, title ASC);
176. @calonso
SECONDARY INDEXES
• Tables are indexed on columns in a PK
• Search on a partition key is very efficient
• Search on a PK and Clustering column is very efficient
• Search on other things is not supported
• Secondary indexes allow indexing other columns to be queried.
• One index per column
177. @calonso
SECONDARY INDEXES
CREATETABLE performer (
nameVARCHAR,
typeVARCHAR,
countryVARCHAR,
styleVARCHAR,
founded INT,
bornTIMESTAMP,
diedTIMESTAMP,
PRIMARY KEY (name)
);
DROP INDEX performers_by_style;
CREATE INDEX performers_by_style
ON perfomer (style);
178. @calonso
SECONDARY INDEXES
• Same recommendations for RDBMS
• Use indexes on low cardinality fields
• Beware of the write overhead
• Every node indexes it local data therefore => a read hits all nodes!!
• Don’t use them. Use lookup tables instead.
181. @calonso
UUID
• Type 4 UUID
• Our way to ensure uniqueness in a distributed system.
7ffa4040-9132-4e0b-b04f-610e869d8717
182. @calonso
UUID
• Type 4 UUID
• Our way to ensure uniqueness in a distributed system.
7ffa4040-9132-4e0b-b04f-610e869d8717
183. @calonso
PRACTICETIME!
Our system has another entity: Books. Books have a title and an author.
We have no guarantee of any of them or even their combination to be unique.
184. @calonso
PRACTICETIME!
Our system has another entity: Books. Books have a title and an author.
We have no guarantee of any of them or even their combination to be unique.
CREATETABLE books (
uidTIMEUUID PRIMARY KEY,
titleVARCHAR,
authorVARCHAR
);
185. @calonso
TIMEUUID
• Timestamp + UUID
• Type 1 UUID
• Generated with CQL now() function
• Can extract theTimestamp with CQL dateof() function
c9cc9e60-711c-11e5-9d70-feff819cdc9f
186. @calonso
TIMEUUID
• Timestamp + UUID
• Type 1 UUID
• Generated with CQL now() function
• Can extract theTimestamp with CQL dateof() function
c9cc9e60-711c-11e5-9d70-feff819cdc9f
188. @calonso
TTL
• TimeTo Live for columns specified in seconds.
• AfterTTL expires, column is marked with aTombstone.
INSERT INTO albums_by_performer (performer, year, title, genre)
VALUES (‘The Beatles’, 1966,‘Revolver’,‘Rock’) USING TTL 30;
189. @calonso
PRACTICETIME!
We are in the BigData era and therefore we want to measure absolutely
everything our users do in our portal.Actions will be defined by a type (string)
and a receiver (int).
190. @calonso
PRACTICETIME!
We are in the BigData era and therefore we want to measure absolutely
everything our users do in our portal.Actions will be defined by a type (string)
and a receiver (int).
CREATETABLE user_action (
user_IDVARCHAR,
timeTIMESTAMP,
typeVARCHAR,
receiver INT,
PRIMARY KEY(user_ID, time)
);
191. @calonso
DELETE
• A whole partition:
• DELETE FROM <table> WHERE <partition_key> = value;
• A row:
• DELETE FROM <table> WHERE <primary key> = value;
• A column:
• DELETE <column name> FROM <table> WHERE <primary key> = value;
• Deleted things are marked with a tombstone, not actually removed.
193. @calonso
COUNTERS
• Implements distributed counters
• The value can only be updated, never
set
• Cannot be part of the PK
• If present on a table, all non counter
columns in the same table must be part
of the PK
CREATETABLE ratings_by_track (
album_titleVARCHAR,
album_year INT,
track_titleVARCHAR,
num_ratings COUNTER,
sum_ratings COUNTER
PRIMARY KEY
(album_title, album_year, track_title)
);
195. @calonso
COUNTERS
• No INSERT
• No value set, only update.
CREATETABLE stats (
performerVARCHAR
albums COUNTER,
concerts COUNTER,
PRIMARY KEY (performer)
);
UPDATE stats
SET albums = albums + 1, concerts = concerts + 10
WHERE performer = ‘The Beatles’;
197. @calonso
PRACTICETIME!
We need to keep track of the number of times a specific book has been read
by a specific user.
CREATETABLE books_read_by_user (
book_uid UUID,
user_IDVARCHAR,
times COUNTER,
PRIMARY_KEY(book_uid, user_ID)
);
198. @calonso
COLLECTIONS
• Set: Uniqueness
• email_addresses SET<VARCHAR>
• List: Order
• email_addresses LIST<VARCHAR>
• Map: Key-Value pairs
• email_addresses MAP<VARCHAR, VARCHAR>
Our users can have several email addresses…
199. @calonso
SETS
• Insert:
• INSERT INTO band (name, members) VALUES (‘The Beatles’, {‘John’, ’Paul’,
‘George’});
• Union (duplicates deletion managed transparently):
• UPDATE band SET members = members + {‘John’, ’Ringo’} WHERE name = ‘The
Beatles’;
• Difference:
• UPDATE band SET members = members - {‘Ringo’} WHERE name = ‘The Beatles’;
• Deletion:
• DELETE members FROM band WHERE name = ‘The Beatles’;
200. @calonso
LISTS
• Insert:
• INSERT INTO song (name, songwriters) VALUES (‘Hold your hand’, [‘John’,
’Paul’]);
• Append:
• UPDATE song SET songwriters = songwriters +[‘Paul’] WHERE name = …;
CREATETABLE song (
nameVARCHAR
songwriters LIST<VARCHAR>,
PRIMARY KEY (name)
);
201. @calonso
LISTS
• Prepend:
• UPDATE song SET songwriters = [‘Paul’] + songwriters WHERE name = …;;
• Update:
• UPDATE song SET songwriters[1] = ‘Jonathan’ WHERE name = …;
• Subtract
• UPDATE song SET songwriters = songwriters - [‘Jonathan’] WHERE name = …;
• Delete
• DELETE songwriters[0] FROM song WHERE name = …;
202. @calonso
MAPS
• Insert:
• INSERT INTO album (title, tracks) VALUES (‘Revolver’,
{ 1: ’Taxman’, 2: ‘Eleanor’});
• Update:
• UPDATE album SET tracks[3] = ‘Yellow Submarine’ WHERE
title = …;
• Delete:
• DELETE tracks[3] FROM album WHERE title = …;
CREATETABLE album (
titleVARCHAR,
tracks MAP<INT,VARCHAR>,
PRIMARY KEY (title)
);
204. @calonso
PRACTICETIME!
Our users can define a set of preferences in the portal:
TimeZone, Language and Currency
ALTERTABLE users ADD preferences MAP<VARCHAR,VARCHAR>;
205. @calonso
USER DEFINEDTYPES
CREATETABLE track_ratings_by_user (
user UUID,
activityTIMEUUID,
rating INT,
song FROZEN <track>,
PRIMARY KEY (user, activity)
) WITH CLUSTERING ORDER BY (activity DESC);
CREATETYPE track (
album_titleVARCHAR,
album_year INT,
track_titleVARCHAR
);
FROZEN: the value has to be fully written, cannot update a single field (i.e: album_year)
206. @calonso
USER DEFINEDTYPES
CREATETABLE track_ratings_by_user (
user UUID,
activityTIMEUUID,
rating INT,
song FROZEN <track>,
PRIMARY KEY (user, activity)
) WITH CLUSTERING ORDER BY (activity DESC);
CREATETYPE track (
album_titleVARCHAR,
album_year INT,
track_titleVARCHAR
);
INSERT INTO track_ratings_by_user (user, activity, rating, song)VALUES
(6ed4f220…, now(), 10,
{ album_title:‘Let it be’, album_year: 1970, track_title:‘Let it be’ });
207. @calonso
USER DEFINEDTYPES
• Update:
• UPDATE track_ratings_by_user SET song = { album_title:
‘Let it be’, album_year: 1970, track_title: ‘Two of
us’} WHERE user = … AND activity = …;
• Delete:
• DELETE song FROM track_ratings_by_user WHERE user = …
AND activity = …;
208. @calonso
TUPLES
CREATETABLE user (
id UUID PRIMARY KEY,
emailTEXT,
nameTEXT,
preferences SET<TEXT>,
equalizer FROZEN<TUPLE<FLOAT, FLOAT, FLOAT, INT,VARCHAR>>
);
INSERT INTO user (id, equalizer)VALUES
(6ed4f220…, (3.0, 1.1, 5.1, 3,“Pop-Rock”));
212. @calonso
BATCH
• Combines multiple INSERT, UPDATE and DELETE operations into a
single logical operation:
• Saves on client - coordinator communication
• Atomic: if one succeeds, all will
• No isolation: other transactions can read/write data affected by
partial batch.
213. @calonso
BATCH
• All modified cells will share same timestamp, so when read, will look
as atomic => No order guarantee!!
• Don’t use BATCHES with operations on the same PK.
BEGIN BATCH
DELETE FROM albums WHERE name = ‘Let it be’;
INSERT INTO albums WHERE name = ‘Let it be’;
APPLY BATCH;
214. @calonso
BATCH + LWT
• The whole BATCH will only run if conditions for all LWT are met.
• All operations in the BATCH will run sequentially.
BEGIN BATCH
UPDATE user SET lock = true IF lock = false;
DELETE FROM albums WHERE name = ‘Let it be’;
INSERT INTO albums WHERE name = ‘Let it be’;
UPDATE user SET lock = false;
APPLY BATCH;
215.
216. @calonso
ROLLBACK
• Not necessary
• RDBMS cannot know, at the beginning of a transaction, if all queries
will be able to succeed
• Cassandra can, so if they won’t doesn’t even start
218. @calonso
SELECT
• All rows:
• SELECT * FROM album;
• Specific columns:
• SELECT performer, title, year FROM album;
• Specific field from a UDT:
• SELECT performer.lastname FROM album;
• Count:
• SELECT COUNT(*) FROM album;
219. @calonso
WHERE
• Equality matches:
• SELECT * FROM tracks_by_album WHERE album_title = ‘Revolver’ AND
year = 1966;
• SELECT * FROM tracks_by_album WHERE album_title = ‘Revolver’ AND
year = 1966 AND number = 6;
• IN:
• Only applicable in the last WHERE clause
• SELECT * FROM tracks_by_album WHERE album_title = ‘Revolver’ AND
year = 1966 AND number IN (2, 3, 4);
220. @calonso
WHERE
• Range search:
• Only on clustering columns.
• SELECT * FROM tracks_by_album WHERE album_title = ‘Revolver’
AND year = 1966 AND number >= 6 AND number < 2;
• ALLOW FILTERING:
• Allows scanning through all partitions => potentially very time consuming
• SELECT * FROM tracks_by_album WHERE number = 2 ALLOW
FILTERING;
222. @calonso
DATA MODELLING
• Understand your data
• Decide how you’ll query the data
• Define column families to satisfy those queries
• Implement and optimize
226. @calonso
QUERY DRIVEN METHODOLOGY
• Spread data evenly around the cluster
• Minimize the number of partitions read
• Follow the mapping rules:
• Entities and relationships: map to tables
• Equality search attributes: must be at the beginning of the primary key
• Inequality search attributes: become clustering columns
• Ordering attributes: become clustering columns
• Key attributes: map to primary key columns
228. @calonso
ANALYSIS &VALIDATION
• Are write conflicts (overwrites) possible?
• How large are partitions?
• Ncells = Nrow X ( Ncols – Npk – Nstatic ) + Nstatic < 1M
• How much data duplication? (batches)
• Client side joins or new table?
231. @calonso
REVIEW QUESTIONS
What is the relationship between a column family
and a CQL table?
Terminologically they’re the same, but technically a
column family refers to the physical representation while
table refers to the logical tabular representation when
queried from CQL.
233. @calonso
REVIEW QUESTIONS
How are clustering columns ordered by default?
How can we modify it?
Ascending by default.
We can modify it by adding WITH CLUSTERING
ORDER BY… in CQL table definition.
235. @calonso
REVIEW QUESTIONS
Which is the biggest reason for using UUIDs in
Cassandra?
Distributed uniqueness. UUIDs guarantee almost 100%
uniqueness in distributed systems.
239. @calonso
REVIEW QUESTIONS
When should secondary indexes be used?
Very rarely. Only when it’s holding values with very low
cardinality and a lookup table is truly inconvenient.
241. @calonso
REVIEW QUESTIONS
Are CQL COUNTERS 100% accurate?
No, not 100%, because its update operations are not
idempotent and a wrong will assign a wrong value.
249. @calonso
REVIEW QUESTIONS
How can data from two tables be combined in a
CQL query?
Cassandra doesn’t support JOIN statements, so we can:
• Nest dependent data in the same table.
• JOIN at application level.
251. @calonso
REVIEW QUESTIONS
How can data from two tables be combined in a
CQL query?
Cassandra doesn’t support JOIN statements, so we can:
• Nest dependent data in the same table.
• JOIN at application level.
253. @calonso
REVIEW QUESTIONS
What is the purpose of Chebotko Diagrams?
Capture our entities and properties as tables along with the query
access patterns expected on them.
255. @calonso
REVIEW QUESTIONS
Which is the most important thing to keep in
mind when designing our data models?
Minimize the number of accessed partitions.
259. @calonso
WRITE PATH
• Memtable: in-memory tables corresponding to CQL tables.
• CommitLog: append-only log to make writes durable.
• SSTables: Memtable snapshots periodically flushed to disk. Never
updated.
• Compaction: Periodic process to merge and streamline SSTables.
260.
261. @calonso
FLUSH PROCESS
• Dumps a Memtable to a new SSTable on disk and its summary index.
• Marks associated commit log entries as flushed
• Triggered by:
• memtable_total_space_in_mb reached
• commitlog_total_space_in_mb reached
• nodetool flush
263. @calonso
READ PATH
• Memtable: in memory table. Serves data as part of the merge process
• RowCache: in memory cache. Stores recently read columns
• BloomFilter: predicts wether a partition key may be in its corresponding SSTable
• KeyCaches: maps recently read partition keys to specific SSTable offsets
• Partition summaries: indexes the partition indexes.
• Partition indexes: Sorted partition keys mapped to their SSTables offsets
• SSTables: static files containing data.
267. @calonso
DELETES
• When a column is deleted aTombstone is applied to the column in
its Memtable
• Tombstoned read columns are ignored
• Tombstoned columns are around for gc_grace_seconds time.
• gc_grace_seconds time is configurable, but beware “Zombies”
268. @calonso
COMPACTIONS
• Merges most recent partition keys and columns
• Evicts tombstoned columns
• Creates new SSTable
• Rebuilds partition indexes and summaries
• Deletes old SSTables
272. @calonso
SIZETIERED COMPACTION
• Fast to complete
• Tables size endlessly increasing
• Potentially inconsistent read latency for updated data
• May waste disk as we don’t know when deleted data will
be merged away
• Requires 2x free disk space as largest table
• Recommended for write-once, read-many use cases
274. @calonso
LEVELED COMPACTION
• Continuously compacting (more I/O)
• 10 x stable_size_in_mb (160Mb) as max required disk space
• Ensures low read latency
• Recommended with overwrites (updates) and tombstones
277. @calonso
REVIEW QUESTIONS
What happens when a Memtable is flushed?
We create a new SSTable on disk.Also the corresponding
CommitLog entries are marked as flushed.
281. @calonso
REVIEW QUESTIONS
Do disk seeks happen during writes?
No, during writes we only write to the commit log that is an
append-ahead log type.That means that writes happen
sequentially on disk.
283. @calonso
REVIEW QUESTIONS
What benefit do Bloom Filters provide to the read
process?
It allows to skip reading SSTables that do not have the data we’re
looking for.
285. @calonso
REVIEW QUESTIONS
Is the partition summary read for partition keys
found in the key cache?
No.The key cache allows us to skip the partition summary and
partition index and go straight to the SSTable.
287. @calonso
REVIEW QUESTIONS
What is the relationship between the partition
summary and the partition index?
The partition summary is an index on the partition index.
289. @calonso
REVIEW QUESTIONS
What are zombie columns and how do you
prevent them?
Zombie columns are those that appear after bringing up a node
that has been down for long enough to not see the tombstone
(gc_grace_seconds).
293. @calonso
REVIEW QUESTIONS
What are the benefits of LeveledCompaction?
• Predictable fast read performance
• Not necessary to have a lot of free disk space for it to happen.
296. @calonso
CPU
• CPU helps writes
• Recommendations
• Dedicated machines: 8 core processors
• Virtual machines: 8 cores + CPU burst
297. @calonso
DISK
• SizeTieredCompaction: 50% free disk space
• LeveledCompaction: 10% free disk space
• Recommendations
• 500gb to 1tb per node
• Two drives: One for data, one for CommitLog
• SSDs if possible