The central modelling question is: node or relationship? The heuristics, in order:
- If you need to connect it to something else, it is a node. An address that two people share is a node; an address used only as one person's attribute can be a property.
- If it has properties that matter, it is probably a node or a relationship with properties - and if those properties need to be queried independently, a node.
- If the same fact involves three or more entities, it is a node. A relationship joins exactly two things, so "person X used device Y at location Z" becomes a
:Sessionnode with three relationships. This is the graph equivalent of an associative table and it is a pattern you will use constantly. - If you find yourself putting a list of identifiers in a property, that is relationships you have not created yet.
The failure modes in both directions are real. Under-modelling leaves everything as properties and gives you a graph you cannot traverse. Over-modelling turns every attribute into a node and gives you a graph with ten times the nodes and traversals that pass through meaningless intermediate hops. The test is whether a traversal through the node answers a question you actually ask.
MERGE is the most useful and most dangerous clause in Cypher. MERGE (p:Person {id: 'p-1'}) means "match this pattern or create it", which is exactly what idempotent loading needs. The trap: MERGE matches on the entire pattern you give it, so MERGE (p:Person {id: 'p-1', name: 'Ada'}) will create a second node if one exists with that id and a different name. The rule is to MERGE on the identifying properties only and use ON CREATE SET and ON MATCH SET for everything else.
The second trap: MERGE on a pattern containing a relationship will create the nodes as well if the whole pattern does not match - so MERGE (a:Person {id:'1'})-[:KNOWS]->(b:Person {id:'2'}) can create duplicate people. Merge the nodes separately, then merge the relationship.
And MERGE needs an index or constraint on the merged property, or it scans - which on a bulk load means a scan per row.
Constraints and indexes. A uniqueness constraint guarantees one node per label-property combination and creates a backing index, so it is usually the right way to get both. Node key constraints (Enterprise) do the same for a composite. Existence constraints (Enterprise) require a property to be present. Index types: range (the default, for equality and ranges), text (for CONTAINS and ENDS WITH), point (spatial), full-text (via a procedure, for real text search), and vector (for embeddings, in recent versions).
The operational point: MERGE and anchored MATCH both need an index to avoid a scan, and a bulk load without one is quadratic.
Laboratory exercise 2 - two models, measured.
Write the query list for the capstone's fraud graph - at least ten queries, numbered.
Design two graph models serving it. The contrast that matters: one where shared attributes (address, device, phone, IP) are properties on the person, and one where they are nodes that several people can connect to. The second is the fraud-detection model; the first cannot answer the questions fraud detection asks, and demonstrating that is the exercise.
Implement both. Implement every query in both, and for the queries the property model cannot answer, say so and explain why.
Measure both with PROFILE: database hits, rows through each operator, and elapsed time, for every query.
Implement the :Session pattern for a three-entity fact and show the queries it enables.
Demonstrate both MERGE traps: create a duplicate node by merging on a non-identifying property, and create duplicate nodes by merging a relationship pattern. Then fix both and show the correct form.
Create every constraint and index your model needs, test each constraint by violating it, and measure a bulk MERGE load with and without the backing index.
Deliverable: the numbered query list, both models with a diagram of each, every query in both with profiles, the queries the property model cannot answer, the :Session pattern, both MERGE traps demonstrated and fixed, the constraint violation outputs, the indexed-against-unindexed load timings, and a page arguing for one model.
// ==================================================================
// *** NODE OR RELATIONSHIP? The central modelling question. ***
// ==================================================================
// THE PROPERTY MODEL - and why fraud detection cannot use it:
CREATE (p:Person {
id: 'p-0001', name: 'Ada',
address: '1 High St, London E1 1AA', // a PROPERTY
device_id: 'dev-77', // a PROPERTY
phone: '+44 20 7946 0000' // a PROPERTY
});
// Now ask: "who else uses device dev-77?"
MATCH (p:Person) WHERE p.device_id = 'dev-77' RETURN p;
// This works - with an index - and it is the ONLY question you can
// ask. You cannot ask "find people connected through any shared
// attribute within three hops", which IS THE FRAUD QUESTION.
// THE GRAPH MODEL - shared attributes become NODES:
MERGE (p:Person {id: 'p-0001'}) ON CREATE SET p.name = 'Ada';
MERGE (a:Address {normalised: '1-high-st-london-e11aa'});
MERGE (d:Device {fingerprint: 'dev-77'});
MERGE (ph:Phone {e164: '+442079460000'});
MERGE (p)-[:LIVES_AT]->(a);
MERGE (p)-[:USED_DEVICE]->(d);
MERGE (p)-[:HAS_PHONE]->(ph);
//
// Now the fraud question is a traversal:
MATCH (p:Person {id:'p-0001'})-[:LIVES_AT|USED_DEVICE|HAS_PHONE]-
(shared)-[:LIVES_AT|USED_DEVICE|HAS_PHONE]-(other:Person)
WHERE other <> p
RETURN other.name, labels(shared)[0] AS via, count(*) AS links
ORDER BY links DESC;
// *** THE PROPERTY MODEL CANNOT ANSWER THIS AT ALL. *** That is
// the exercise: not that the graph model is faster, but that it
// can express a question the other cannot.
// THE HEURISTICS, in order:
// 1. IF YOU NEED TO CONNECT IT TO SOMETHING ELSE, IT IS A NODE.
// 2. If it has properties that must be queried independently, node.
// 3. IF THE FACT INVOLVES THREE OR MORE ENTITIES, IT IS A NODE -
// because a relationship joins EXACTLY TWO things:
MERGE (s:Session {id: 'sess-abc123'})
ON CREATE SET s.at = datetime(), s.ip = '10.0.0.1'
WITH s
MATCH (p:Person {id:'p-0001'}), (d:Device {fingerprint:'dev-77'}),
(l:Location {geohash: 'gcpvj'})
MERGE (p)-[:IN_SESSION]->(s)
MERGE (s)-[:ON_DEVICE]->(d)
MERGE (s)-[:AT_LOCATION]->(l);
// The graph equivalent of an associative table, and a pattern
// you will use constantly.
// 4. *** IF YOU ARE PUTTING A LIST OF IDENTIFIERS IN A PROPERTY,
// *** THAT IS RELATIONSHIPS YOU HAVE NOT CREATED YET. ***
// THE FAILURE IN THE OTHER DIRECTION IS ALSO REAL:
// OVER-MODELLING turns every attribute into a node and gives you
// ten times the nodes and traversals that pass through meaningless
// hops. (p)-[:HAS_NAME]->(:Name {value:'Ada'}) is not a graph, it
// is a mistake.
// THE TEST: does a traversal THROUGH this node answer a question
// you actually ask? If not, it is a property.
// ==================================================================
// *** MERGE: the most useful and most dangerous clause in Cypher. ***
// ==================================================================
// TRAP 1: MERGE MATCHES ON THE ENTIRE PATTERN YOU GIVE IT.
MERGE (p:Person {id: 'p-0001', name: 'Ada Lovelace'});
MERGE (p:Person {id: 'p-0001', name: 'Ada L.'});
MATCH (p:Person {id: 'p-0001'}) RETURN count(p);
// -> 2. *** TWO NODES WITH THE SAME ID. *** Because the second
// MERGE's pattern did not match (the name differed), so it CREATED.
//
// THE RULE: MERGE ON THE IDENTIFYING PROPERTIES ONLY.
MERGE (p:Person {id: 'p-0001'})
ON CREATE SET p.name = 'Ada Lovelace', p.created_at = datetime()
ON MATCH SET p.name = 'Ada L.', p.updated_at = datetime();
// Idempotent, and it does what you meant.
// TRAP 2: MERGE ON A PATTERN WITH A RELATIONSHIP CREATES THE NODES
// TOO, if the WHOLE pattern does not match.
MERGE (a:Person {id:'p-1'})-[:KNOWS]->(b:Person {id:'p-2'});
// If the relationship does not exist, this creates it AND BOTH
// NODES - even if nodes with those ids already exist. Duplicate
// people, silently.
//
// THE FIX: merge the nodes SEPARATELY, then the relationship:
MERGE (a:Person {id:'p-1'})
MERGE (b:Person {id:'p-2'})
MERGE (a)-[:KNOWS]->(b);
// TRAP 3: MERGE WITHOUT AN INDEX SCANS. On a bulk load that is a
// scan PER ROW - quadratic, and it looks like the import "got slow".
// Create the constraint FIRST, always. Measure both in the lab.
// ==================================================================
// CONSTRAINTS and INDEXES.
// ==================================================================
// A UNIQUENESS constraint also CREATES A BACKING INDEX, so it is
// usually the right way to get both:
CREATE CONSTRAINT person_id IF NOT EXISTS
FOR (p:Person) REQUIRE p.id IS UNIQUE;
CREATE CONSTRAINT device_fp IF NOT EXISTS
FOR (d:Device) REQUIRE d.fingerprint IS UNIQUE;
CREATE CONSTRAINT address_norm IF NOT EXISTS
FOR (a:Address) REQUIRE a.normalised IS UNIQUE;
// TEST IT. Every constraint, by violating it:
CREATE (:Person {id: 'p-0001'});
// -> Node(123) already exists with label `Person` and property
// `id` = 'p-0001'
// Enterprise-only, and worth knowing they exist:
// CREATE CONSTRAINT ... REQUIRE (n.a, n.b) IS NODE KEY; // composite
// CREATE CONSTRAINT ... REQUIRE n.email IS NOT NULL; // existence
// INDEX TYPES, each for a different predicate:
CREATE INDEX person_email IF NOT EXISTS
FOR (p:Person) ON (p.email); // RANGE: = and < >
CREATE INDEX transfer_at IF NOT EXISTS
FOR ()-[t:TRANSFERRED]-() ON (t.at); // on a RELATIONSHIP
CREATE TEXT INDEX person_name_text IF NOT EXISTS
FOR (p:Person) ON (p.name); // CONTAINS, ENDS WITH
CREATE FULLTEXT INDEX person_search IF NOT EXISTS
FOR (p:Person) ON EACH [p.name, p.email]; // real text search
// CREATE POINT INDEX ... // spatial
// CREATE VECTOR INDEX ... OPTIONS {indexConfig: {...}} // embeddings
SHOW INDEXES;
SHOW CONSTRAINTS;
CALL db.awaitIndexes(300); // indexes build ASYNCHRONOUSLY -
// wait before benchmarking, or you
// measure a half-built index
// A RANGE index does NOT serve CONTAINS. Use a TEXT index:
PROFILE MATCH (p:Person) WHERE p.name CONTAINS 'Love' RETURN p;
// And a FULLTEXT index is a procedure call, not a WHERE clause:
CALL db.index.fulltext.queryNodes('person_search', 'lovelace~')
YIELD node, score RETURN node.name, score ORDER BY score DESC;
// ==================================================================
// OPTIONAL MATCH and aggregation.
// ==================================================================
MATCH (p:Person {id:'p-0001'})
OPTIONAL MATCH (p)-[:OWNS]->(a:Account)
OPTIONAL MATCH (p)-[:LIVES_AT]->(addr:Address)
RETURN p.name, collect(DISTINCT a.id) AS accounts, addr.city;
// OPTIONAL MATCH is a LEFT OUTER JOIN: nulls rather than no row.
// WITHOUT it, a person with no account DISAPPEARS FROM THE RESULT,
// which is the commonest cause of "my query is missing rows".
MATCH (a:Account)-[t:TRANSFERRED]->(b:Account)
WHERE t.at > datetime() - duration('P30D')
RETURN a.id,
count(t) AS transfers,
sum(t.amount) AS total,
avg(t.amount) AS mean,
percentileCont(t.amount, 0.95) AS p95,
collect(DISTINCT b.id)[0..5] AS sample_targets
ORDER BY total DESC LIMIT 20;
// Aggregation implicitly groups by the NON-AGGREGATED keys, so
// there is no GROUP BY. That surprises SQL users once.
Discussion
No questions on this topic yet. Sign in to ask the first one.