Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 30 ยท Interviews and Cheat Sheet

Cassandra and Neo4j cheat sheet

A one-page reference for CQL and Cypher syntax, Cassandra consistency levels, modeling rules and common pitfalls, with a searchable stand-in.

This is the page to keep open while you work. It condenses the whole tutorial into syntax, rules and checklists: CQL for Cassandra, Cypher for Neo4j, consistency levels, modeling rules and the mistakes people make most often. Each section links to the lesson that explains the topic in depth, so use the cheat sheet to remember and the lessons to understand.

Everything in the code blocks is read-only, because Cassandra and Neo4j are servers that cannot run in a browser tab. Two small programs at the end are runnable stand-ins: a searchable version of this sheet, and a calculator for consistency levels. The details of syntax differ a little between versions, so confirm uncommon options in the manual for the version you run.

CQL (Cassandra)

Keyspaces and tables

SQL
CREATE KEYSPACE shop
  WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
USE shop;

CREATE TABLE events_by_user_day (
  user_id uuid,
  day     date,
  ts      timeuuid,
  kind    text,
  PRIMARY KEY ((user_id, day), ts)       -- (partition key), clustering
) WITH CLUSTERING ORDER BY (ts DESC)
  AND default_time_to_live = 7776000;

ALTER TABLE events_by_user_day ADD detail text;
DROP TABLE events_by_user_day;

Basics: CQL: keyspaces, tables and basic queries.

Reading and writing

SQL
INSERT INTO events_by_user_day (user_id, day, ts, kind)
VALUES (?, '2026-03-01', now(), 'view') USING TTL 86400;

SELECT * FROM events_by_user_day
 WHERE user_id = ? AND day = '2026-03-01' AND ts > ? LIMIT 20;

UPDATE events_by_user_day SET kind = 'click'
 WHERE user_id = ? AND day = ? AND ts = ?;

DELETE FROM events_by_user_day WHERE user_id = ? AND day = ? AND ts = ?;

INSERT INTO users (name, email) VALUES ('ada', '[email protected]') IF NOT EXISTS;  -- LWT
UPDATE counters SET hits = hits + 1 WHERE page = ?;                       -- counter table

INSERT and UPDATE are both upserts. Setting a column to null or deleting writes a tombstone.

Query rules in one list

  • Supply every partition key column with = (or IN).
  • Restrict clustering columns left to right, with no gaps.
  • One range (<, >, <=, >=) is allowed, on the last restricted clustering column.
  • Anything else needs an index or ALLOW FILTERING, and that is a warning sign.
  • ORDER BY only on the clustering columns, in the table's order or its exact reverse.

See Partition keys and clustering keys.

Types

Kind Types
Text and numbers text, int, bigint, decimal, double, boolean
Time and ids timestamp, date, time, uuid, timeuuid
Collections list<T>, set<T>, map<K,V>, frozen<...>
Other counter, user-defined types, blob, inet

Details: Data types, collections and UDTs.

Consistency levels

Level Replicas that must respond Typical use
ANY (writes only) any node, even a stored hint almost never
ONE 1 fast, tolerant, may be stale
TWO, THREE 2, 3 rare
QUORUM floor(RF / 2) + 1 across the cluster strong reads and writes
LOCAL_QUORUM quorum inside the local data center multi-DC default for strong
EACH_QUORUM (writes) quorum in every data center rare, slow
ALL every replica strongest, no failures tolerated
SERIAL, LOCAL_SERIAL Paxos, for conditional statements LWT reads

Strong consistency: R + W > RF. With RF 3, quorum plus quorum is enough. More in Replication and tunable consistency.

Modeling rules (Cassandra)

  1. List the queries first. One table per query, named x_by_y.
  2. The partition key is what the query supplies. Keep partitions bounded: add a time bucket.
  3. Clustering columns give the sort order. Add a unique tie-breaker (an id or a timeuuid).
  4. Denormalize on purpose and write all copies with idempotent upserts.
  5. Avoid unbounded collections, huge partitions, queue-like deletes and hot keys.
  6. Use TTL for expiring data and a time-window compaction strategy for it.

Guides: Query-first data modeling and Time-series and bucketing patterns.

Cypher (Neo4j)

Patterns

CYPHER
(n)                         // any node
(p:Person)                  // label
(p:Person {name: 'Ada'})    // label and property
(a)-[:FOLLOWS]->(b)         // directed relationship
(a)-[r:RATED {stars: 5}]->(m)
(a)-[:FOLLOWS*1..3]->(b)    // 1 to 3 hops
(a)-[:KNOWS]-(b)            // either direction

Reading

CYPHER
MATCH (p:Person)-[:FOLLOWS]->(f:Person)
WHERE p.name = $name AND f.active
RETURN f.name AS name, f.joined
ORDER BY f.joined DESC
SKIP 0 LIMIT 10;

OPTIONAL MATCH (p)-[:LIKES]->(m)           // keeps p even with no match
RETURN p.name, count(m), collect(m.title)

MATCH (p:Person)-[:FOLLOWS]->(f)
WITH p, count(f) AS following
WHERE following > 100                      // WITH = pipeline stage / HAVING
RETURN p.name, following;

MATCH path = shortestPath((a:Person {name:'Ada'})-[*..6]-(b:Person {name:'Gus'}))
RETURN [n IN nodes(path) | n.name];

Writing

CYPHER
CREATE (p:Person {name: 'Ada', born: 1815});
MERGE (p:Person {id: $id}) ON CREATE SET p.created = timestamp() ON MATCH SET p.seen = timestamp();
MATCH (a:Person {id: 1}), (b:Person {id: 2}) MERGE (a)-[:FOLLOWS]->(b);
MATCH (p:Person {id: 1}) SET p.name = 'Ada L.', p:Admin;
MATCH (p:Person {id: 1}) REMOVE p.nickname, p:Admin;
MATCH (p:Person {id: 1}) DETACH DELETE p;   // DETACH removes relationships first

Constraints, indexes and tuning

CYPHER
CREATE CONSTRAINT person_id IF NOT EXISTS FOR (p:Person) REQUIRE p.id IS UNIQUE;
CREATE INDEX person_name IF NOT EXISTS FOR (p:Person) ON (p.name);
EXPLAIN MATCH ...   // the plan, not executed
PROFILE MATCH ...   // executed, with db hits per step

Learn more: Cypher: MATCH, CREATE and patterns, Cypher: MERGE, SET, DELETE and constraints and Paths, aggregation and WITH.

Graph modeling rules

  • Nodes are things, relationships are verbs, properties describe either.
  • Relationship types are specific (PURCHASED, not RELATED_TO); the direction carries meaning.
  • Make something a node when you traverse through it, count it, or give it relationships of its own (a genre, a city, a device).
  • Avoid supernodes (one node with millions of relationships) and generic catch-all types.
  • Always parameterize ($name), constrain ids with uniqueness, and bound variable-length paths.

Pitfalls checklist

Symptom Likely cause Fix
Query needs ALLOW FILTERING Table was not built for the query Add a table keyed for it
Slow, timeouts on one key Wide or hot partition Add a bucket to the partition key
Deleted rows slow reads Many tombstones in the scan Redesign (no queue tables), tune TTL and compaction
Deleted data returns Repair slower than gc_grace_seconds Repair regularly
Stale read Low consistency level QUORUM or LOCAL_QUORUM for both
Cypher runs for minutes Cartesian product or unbounded path PROFILE, add an index, bound the path
Duplicate nodes after a re-run CREATE instead of MERGE MERGE plus uniqueness constraint

Stand-in 1: a searchable cheat sheet

The program below holds a few of the sheet's entries in a list and filters it by a keyword, the way you might search a reference in a terminal. It is a toy, but it shows the pattern for building your own personal snippet finder.

JS Search the cheat sheet

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in 2: a consistency calculator

Give it a replication factor and it prints what each common level means: how many replicas respond, and how many can be down. It uses the rule quorum = floor(RF / 2) + 1.

Python Consistency levels for any replication factor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With RF 1 there is nothing to replicate and no failure can be tolerated; with RF 3 or 5 the quorum pair stays strong while still tolerating failures. That is why RF 3 is the usual production starting point.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Cypher keyword makes an import safe to run twice?

    MERGE matches the pattern and creates it only when it is missing.
  2. 2. With RF=5, how many replicas make a quorum?

    floor(5 / 2) + 1 = 3.
  3. 3. Which CQL query rule is correct?

    Cassandra needs the full partition key to find the replicas. Clustering restrictions go left to right with at most one range.
  4. 4. What does DETACH DELETE do that plain DELETE does not?

    A node with relationships cannot be deleted by plain DELETE. DETACH DELETE removes them first.

Summary

  • CQL: supply the whole partition key, restrict clustering columns from the left, at most one range, and design a table per query.
  • Quorum is floor(RF / 2) + 1; R + W > RF gives strong reads.
  • Cypher: MATCH reads patterns, MERGE makes writes repeatable, WITH pipelines stages, PROFILE reveals cost.
  • Bound partitions and paths, use constraints and parameters, and repair before gc_grace_seconds runs out.
  • Revisit the lessons behind each section when the one-liners are not enough, starting from The NoSQL families and when to choose them.

This is the last lesson of the track. Continue with Practice exercises with solutions to test yourself again.