EXPLAIN shows the plan; PROFILE runs it and shows what happened. Use PROFILE. The operators to recognise:
NodeIndexSeek- good. An index found the starting nodes.NodeByLabelScan- every node with that label. Acceptable on a small label, a problem on a large one.AllNodesScan- every node in the graph. Almost always a bug.Expand(All)- a traversal. Itsdb hitsis the work done following relationships.Filter- a predicate applied after rows were produced, so rows were read and discarded. AFilterwith a large input and a small output means the work should have been done by an index or a tighter pattern.Eager- the operator to watch for. It materialises all rows before continuing, which it does to avoid reading its own writes. AnEagerin a write query over a large input can hold the whole result in memory, and it is the usual explanation for an import that exhausts the heap.CartesianProduct- two disconnected patterns combined, producing the product of their rows. Almost always a missing relationship in the pattern or a missingWITH.
The two numbers: db hits is the actual storage work and is what you optimise. Rows through each operator is the cardinality, and the thing to look for is cardinality growing through a traversal - 1 row in, 10,000 out, 10,000,000 out - which tells you exactly which hop is the problem.
Cardinality is the real skill. A traversal's cost is the product of the degrees along it, so the question for every query is "how many nodes am I standing on, and what is their average degree?" The techniques: anchor on the most selective node; traverse from the smaller side; filter early with a WITH; and use DISTINCT deliberately, because path queries produce duplicate end nodes and counting them twice is a correctness bug as well as a cost.
Memory configuration matters more here than in most databases. The page cache holds the graph; if the working set does not fit, every hop is a disk read and index-free adjacency stops being an advantage. The heap holds query state. The rule of thumb: size the page cache to hold the store files you actually traverse, and the heap for your concurrent query state - and a heap much above 31 GB loses compressed object pointers, so very large heaps are worse than they look.
Graph algorithms - the Graph Data Science library - are worth knowing by name and shape: PageRank (influence), community detection (Louvain, Label Propagation, WCC - which finds your disconnected components and is the first thing to run on a new graph), centrality (betweenness, degree, closeness), similarity (node similarity, k-nearest neighbours), pathfinding (Dijkstra, A*, Yen's) and link prediction. The operational shape: you project a named graph into memory, run the algorithm, and write results back or stream them. Projection is the expensive part and the projected graph occupies memory for its lifetime, so dropping it matters.
Laboratory exercise 4 - a measured improvement.
Load at least five million nodes and twenty million relationships. Declare a baseline: five queries with p50, p95 and p99 and database hits for each, plus the page cache hit ratio.
Demonstrate each bad operator: write a query producing an AllNodesScan, one producing a CartesianProduct, one with a Filter discarding most of its input, and a write query producing an Eager. Fix each and record the database hits before and after.
Trace cardinality through a traversal: profile a three-hop query and record the rows at each operator, showing where the growth happens. Then reverse the traversal direction - start from the other end - and show the difference.
Apply index techniques and re-measure: a range index, a composite index, a text index for a CONTAINS query, and a relationship property index.
Demonstrate the page cache effect: shrink the page cache below the store size, measure a traversal, then size it correctly and measure again.
Run three algorithms through GDS: WCC to find your components, PageRank, and Louvain for communities. Record the projection time, the algorithm time, and the memory the projected graph occupies.
Deliverable: the benchmark report with database hits and percentiles at each step, each bad operator demonstrated and fixed, the cardinality trace in both directions, the index comparisons, the page cache measurement, the GDS results with projection costs, and one change that did not help.
// ==================================================================
// PROFILE, not EXPLAIN. And read db hits, not time.
// ==================================================================
PROFILE
MATCH (p:Person {email: 'ada@example.test'})-[:OWNS]->(a:Account)
-[t:TRANSFERRED]->(b:Account)
WHERE t.amount > 1000
RETURN b.id, t.amount;
//
// +-------------------+----------+------+---------+
// | Operator | Rows | DB | Details |
// +-------------------+----------+------+---------+
// | ProduceResults | 12 | 0 | |
// | Filter | 12 | 840 | t.amount > 1000
// | Expand(All) | 840 | 1702 | (a)-[t]->(b)
// | Expand(All) | 3 | 6 | (p)-[:OWNS]->(a)
// | NodeIndexSeek | 1 | 2 | :Person(email)
// +-------------------+----------+------+---------+
//
// READ IT BOTTOM UP. 1 person -> 3 accounts -> 840 transfers ->
// 12 after the filter.
//
// *** TWO NUMBERS: db hits is the WORK (optimise this). Rows is
// *** the CARDINALITY (watch where it GROWS). ***
// Here the Filter discarded 828 of 840 rows - so a relationship
// property index on t.amount might do that work in the index
// instead. That is what the profile is telling you.
// ==================================================================
// THE OPERATORS TO RECOGNISE.
// ==================================================================
// NodeIndexSeek GOOD. An index found the starting nodes.
// NodeByLabelScan every node with that label. Fine on a small
// label, a problem on a large one.
// AllNodesScan EVERY NODE IN THE GRAPH. Almost always a bug:
PROFILE MATCH (n) WHERE n.id = 'p-0001' RETURN n;
// AllNodesScan | 5,000,000 rows | 5,000,001 db hits
// -> no label, so no index can apply. ADD THE LABEL:
PROFILE MATCH (n:Person) WHERE n.id = 'p-0001' RETURN n;
// Filter a predicate applied AFTER rows were produced. Large
// input, small output = work an index should have done.
// Expand(All) a traversal; its db hits is the relationship work.
// *** Eager - THE OPERATOR TO WATCH FOR. ***
PROFILE
MATCH (p:Person)
MERGE (:Summary {person: p.id})
SET p.summarised = true;
// ... | Eager | 5,000,000 rows | ...
//
// Eager MATERIALISES ALL ROWS before continuing, to avoid reading
// its own writes. On a large input that holds the WHOLE RESULT IN
// MEMORY, and *** IT IS THE USUAL EXPLANATION FOR AN IMPORT THAT
// EXHAUSTS THE HEAP. ***
// The fix is almost always batching, which also removes the need
// for eagerness:
MATCH (p:Person)
CALL { WITH p
MERGE (:Summary {person: p.id})
SET p.summarised = true
} IN TRANSACTIONS OF 10000 ROWS;
// *** CartesianProduct - two DISCONNECTED patterns. ***
PROFILE
MATCH (p:Person), (a:Account)
WHERE p.id = 'p-1' AND a.id = 'acc-1'
RETURN p, a;
// CartesianProduct | 1 row | ... (harmless here: both anchored)
PROFILE
MATCH (p:Person), (a:Account)
RETURN count(*);
// CartesianProduct | 5,000,000 x 2,000,000 rows <- catastrophic
// Almost always a MISSING RELATIONSHIP in the pattern, or a
// missing WITH between two independent matches.
// ==================================================================
// *** CARDINALITY IS THE REAL SKILL. ***
// ==================================================================
// A traversal's cost is the PRODUCT OF THE DEGREES ALONG IT. So the
// question for every query is: "how many nodes am I standing on, and
// what is their average degree?"
//
// TRAVERSE FROM THE SMALLER SIDE. The same logical query, both ways:
PROFILE
MATCH (p:Person {id:'p-1'})-[:OWNS]->(a:Account)<-[:TRANSFERRED]-(src)
RETURN count(src);
// 1 -> 3 -> 840. 843 db hits
PROFILE
MATCH (src:Account)-[:TRANSFERRED]->(a:Account)<-[:OWNS]-(p:Person {id:'p-1'})
RETURN count(src);
// The planner usually reorders this correctly - CHECK that it did,
// because when it does not, the difference is enormous.
// FILTER EARLY with a WITH, so the next hop starts from fewer nodes:
MATCH (p:Person)-[:OWNS]->(a:Account)
WITH a WHERE a.balance > 100000 // <- narrow FIRST
MATCH (a)-[t:TRANSFERRED*1..2]->(b:Account)
RETURN b.id, count(*);
// DISTINCT, DELIBERATELY. Path queries produce DUPLICATE END NODES -
// one per path - so counting them twice is a CORRECTNESS bug as well
// as a cost:
MATCH (p:Person {id:'p-1'})-[:LIVES_AT|USED_DEVICE*1..3]-(other:Person)
RETURN count(other), count(DISTINCT other);
// -> 48, 11. Both numbers are meaningful; know which you want.
// Force a plan only as a last resort, and only with a comment saying
// why - a hint outlives the data distribution that justified it:
MATCH (p:Person) USING INDEX p:Person(email)
WHERE p.email = 'ada@example.test' RETURN p;
// ==================================================================
// MEMORY: it matters more here than in most databases.
// ==================================================================
CALL dbms.listConfig() YIELD name, value
WHERE name CONTAINS 'memory' RETURN name, value;
// server.memory.pagecache.size HOLDS THE GRAPH. If the working
// set does not fit, EVERY HOP IS A DISK READ and index-free
// adjacency stops being an advantage at all.
// server.memory.heap.max_size query state.
// *** A heap much above 31 GB LOSES COMPRESSED OBJECT POINTERS,
// *** so very large heaps are worse than they look. *** Stay
// below it unless you have measured a reason.
CALL db.stats.retrieve('GRAPH COUNTS');
// Store sizes - size the page cache from these, not from guesses.
// Then measure the hit ratio:
// neo4j_page_cache_hit_ratio > 0.98 wanted
// neo4j_page_cache_evictions rising = too small
// Demonstrate it: shrink the page cache below the store size,
// measure a traversal, size it correctly, measure again.
// ==================================================================
// GRAPH ALGORITHMS (GDS): project, run, drop.
// ==================================================================
// *** RUN THIS FIRST ON ANY NEW GRAPH. *** WCC finds your
// DISCONNECTED COMPONENTS, and a graph in 400 pieces when you
// expected one is a data loading bug you want to find now:
CALL gds.graph.project('fraud', ['Person','Account','Device','Address'],
{LIVES_AT: {orientation:'UNDIRECTED'},
USED_DEVICE: {orientation:'UNDIRECTED'},
OWNS: {orientation:'UNDIRECTED'},
TRANSFERRED: {orientation:'NATURAL'}});
CALL gds.wcc.stats('fraud')
YIELD componentCount, componentDistribution
RETURN componentCount, componentDistribution;
// PageRank - influence:
CALL gds.pageRank.stream('fraud')
YIELD nodeId, score
RETURN gds.util.asNode(nodeId).id AS id, score
ORDER BY score DESC LIMIT 20;
// Louvain - communities, which in a fraud graph are candidate rings:
CALL gds.louvain.write('fraud', {writeProperty: 'community'})
YIELD communityCount, modularity;
MATCH (p:Person) WITH p.community AS c, count(*) AS members
WHERE members BETWEEN 3 AND 20
RETURN c, members ORDER BY members DESC;
// Node similarity, Dijkstra, betweenness, k-NN, link prediction -
// the same project/run/write shape throughout.
CALL gds.graph.list() YIELD graphName, nodeCount, memoryUsage;
CALL gds.graph.drop('fraud');
//
// *** PROJECTION IS THE EXPENSIVE PART, and the projected graph
// *** OCCUPIES MEMORY FOR ITS LIFETIME - so DROP IT. *** Record the
// projection time, the algorithm time and the memory separately;
// people quote the algorithm time and pay for the projection.
Discussion
No questions on this topic yet. Sign in to ask the first one.