In this lesson, you will learn how to optimize your graph query performance by balancing traversal counts against relationship selectivity.
Understanding the Traversal Cost
In graph databases, performance isn't just about how many nodes you touch; it’s about how many "edges" you traverse to find your answer. When you write a pattern match query, the database engine executes a plan based on the starting node and the breadth of the relationships it must follow. If your query forces the engine to traverse "supernodes"—nodes with thousands of connections—your traversal count explodes, leading to latency.
Analyzing Selectivity
Selectivity refers to how effectively a specific filter reduces the number of candidate paths. Consider a query looking for a user’s friends:
MATCH (u:User {id: 123})-[:FRIEND]->(f:User)-[:PURCHASED]->(p:Product)
WHERE p.category = 'Electronics'
RETURN p
If you start at u:User {id: 123}, the traversal count depends on how many friends that user has. If that user has 5,000 friends, the engine must traverse 5,000 [:FRIEND] edges before even looking at the [:PURCHASED] relationship.
Optimizing the Plan
To tune this query, you should aim to increase the "selectivity" of the starting point or prune the search space early. If the number of 'Electronics' purchases globally is significantly smaller than the number of friends a user has, you might optimize the query plan by starting the traversal from the Product node instead:
MATCH (p:Product {category: 'Electronics'})<-[:PURCHASED]-(f:User)<-[:FRIEND]-(u:User {id: 123})
RETURN p
By reversing the traversal direction or introducing a more restrictive filter at the start of your pattern, you reduce the number of intermediate nodes the database must keep in memory. Always inspect the execution plan (using EXPLAIN or PROFILE) to see how many "db hits" occur at each hop. If a particular step shows a massive increase in rows, that is your bottleneck. Prioritize paths that reach highly selective filters as early as possible in your MATCH clause to minimize the total number of traversals.
Key Takeaway: Optimize query plans by placing the most selective filters at the start of the traversal to minimize the number of intermediate nodes processed.