Graph databases are supposed to make relationship queries fast. So why does this Cypher query take 40 seconds?
MATCH (u:User), (p:Product)
WHERE u.email = 'ana@example.com' AND p.sku = 'X-100'
MATCH (u)-[:FRIEND*]-(f)-[:BOUGHT]->(p)
RETURN DISTINCT f.name;
Neo4j is fast at following relationships from a known starting point. Slow Cypher usually means one of three things: finding the starting point is slow, the query multiplies rows, or the traversal is unbounded.
Step 1: PROFILE it
PROFILE
MATCH (u:User {email: 'ana@example.com'})-[:FRIEND]-(f)
RETURN count(f);
PROFILE runs the query and shows each operator with rows and db hits. (EXPLAIN shows the plan without running it.) Read from the bottom up, and look for:
AllNodesScanorNodeByLabelScanwhere you expected an index seek;CartesianProduct;Eager;- an operator whose row count explodes compared with the one below it.
Problem 1: no index for the starting node
NodeByLabelScan on :User means Neo4j is checking every user's email. Add an index, or better, a uniqueness constraint (which includes an index):
CREATE CONSTRAINT user_email IF NOT EXISTS FOR (u:User) REQUIRE u.email IS UNIQUE;
CREATE INDEX product_sku IF NOT EXISTS FOR (p:Product) ON (p.sku);
CREATE TEXT INDEX user_name_text IF NOT EXISTS FOR (u:User) ON (u.name); -- CONTAINS / ENDS WITH
The plan should then start with NodeIndexSeek or NodeUniqueIndexSeek. Also check that the query uses the label: MATCH (u {email: …}) without :User can't use a label index.
Problem 2: cartesian products
Comma-separated patterns that aren't connected produce every combination:
MATCH (u:User), (p:Product) -- 1M users × 100k products = 100 billion rows
