Mental model
Neo4j represents entities as labeled nodes and their connections as typed, directed relationships; both can carry properties. Cypher MATCH describes patterns over those records, while indexes help locate starting nodes before the engine follows stored relationships. Query cost therefore depends on anchor selectivity, path length, and branching factor, not merely on the number of clauses in the query.
Theory
A property graph has two record kinds. A node can have several labels and a map of properties; a relationship has one type, a direction, endpoints, and its own properties. An order, for example, may connect a customer to a product with a CONTAINS relationship whose quantity and unitPrice describe that particular purchase. Putting those values on the relationship avoids inventing a separate line-item node when the relationship itself is the fact.
Labels and relationship types give a graph its vocabulary, but they do not automatically enforce identity. If a person must have a unique external identifier, create a uniqueness constraint and index for that label and property. Then an application can find one well-defined start node and traverse from it. Without such an anchor, a query may begin with an all-node scan even if every later step follows a short path.
Cypher expresses the desired pattern rather than an instruction-by-instruction pointer loop. A pattern such as (customer:Customer)-[:PLACED]->(order:Order)-[:CONTAINS]->(product:Product) binds nodes and relationships. WHERE narrows those bindings, and RETURN projects the fields the caller needs. An index seek can reduce the initial candidate set, but each relationship expansion can multiply the amount of work. A selective first predicate and a bounded path are often more valuable than adding another index to every property.
The planner estimates candidate rows from available indexes and graph statistics. EXPLAIN shows the planned operators without executing the query; PROFILE runs it and reports actual rows and database hits. A large difference between estimated and actual rows points to skewed values or a poor starting point. A plan that repeatedly expands from a high-degree node may be expensive even when it returns only a few final rows, because filtering can happen after the engine has visited many candidates.
Quantitative model
For a tree-shaped traversal with average branching factor b and maximum depth d, the number of candidate node visits from one start is bounded by the geometric sum below. Real graphs have cycles and overlapping paths, so the engine may deduplicate some matches; skew can also make a single node much more expensive than the average.
Here b is the mean number of outgoing relationships eligible at each hop, d is the number of hops, and V_max is candidate visits per start node. Suppose an index finds 120 customers, each customer reaches four orders, and each order reaches four products. At depth two, the estimate is candidate visits. A broad scan of a two-million-node store could inspect up to two million starts before expansion. A selective indexed anchor changes the scale, while an unbounded relationship pattern can erase that advantage.
Failure modes and misconceptions
An unbounded path pattern is not a harmless way to ask for “all related records.” High-degree nodes create explosive fan-out, and cycles can make the same entities reachable through many different paths. Define a useful hop limit, constrain relationship types and direction, and return only the fields needed by the caller. If a query is meant to find the shortest path, state that goal explicitly instead of enumerating every possible path and sorting afterward.
Another common mistake is treating the graph as schemaless and skipping integrity rules. Duplicate customer nodes make a traversal return repeated orders; a missing relationship type can silently exclude records; and storing a changing fact on a node can make its ownership ambiguous. Use uniqueness constraints for identity, name relationship types precisely, and decide whether a fact belongs to a node, an edge, or its own entity before loading data.
An index is a way to find a starting point, not a substitute for a good graph shape. A function around an indexed property may stop the planner from using the expected seek. A wide OR predicate can also select a plan that reads more nodes than expected. Confirm the actual plan with PROFILE against representative data, including high-degree and empty-result cases.
Trade-offs
Modeling a relationship as an edge makes a connection direct to traverse and lets the connection carry its own properties. A separate node is better when the relationship has independent identity, a lifecycle, or its own rich set of links. This choice changes query shape and storage overhead. Similarly, denormalizing a frequently requested summary can reduce repeated traversal but creates an update obligation when source facts change.
Indexes consume disk and memory and add work to writes. Index only fields used to find selective anchors or satisfy important ordering requirements. Keep path depth tied to a product requirement, not a guess about future flexibility. A shorter query that returns fewer rows is not automatically cheaper; compare actual database hits, rows visited, and latency percentiles with realistic label distributions.
Decision scenario
A recommendation endpoint starts from a user ID and follows FOLLOWS edges to authors, then WROTE edges to books. Some users follow 30 authors while influencer accounts follow 40,000; the endpoint returns 20 books but currently takes 1.8 seconds at p95. First enforce a unique user ID index, inspect the plan and actual row counts, and reduce the candidate path with a recency or category predicate before ranking. If those authors and their books are reused across many users, a bounded precomputed candidate set may be cheaper than traversing the entire influencer neighborhood on every request.
Learning outcomes
- Distinguish node labels, relationship types, direction, and properties when modeling a domain fact.
- Predict when a Cypher query needs a selective indexed start versus a bounded expansion.
- Use
EXPLAINandPROFILEto compare estimated and actual work, not just returned rows. - Choose between a relationship property, a separate node, and a denormalized summary based on lifecycle and query needs.
Implementation pattern
This Python driver example anchors a two-hop lookup on a unique customer email, passes values as parameters, and caps returned rows. It returns a compact projection instead of materializing full nodes and relationships in application memory.
pythonimport osfrom neo4j import GraphDatabaseQUERY = """MATCH (customer:Customer {email: $email})-[:PLACED]->(order:Order)-[:CONTAINS]->(product:Product)WHERE order.createdAt >= $sinceRETURN order.id AS orderId, product.sku AS sku, product.name AS nameORDER BY order.createdAt DESCLIMIT $limit"""driver = GraphDatabase.driver(os.environ["NEO4J_URI"],auth=(os.environ["NEO4J_USER"], os.environ["NEO4J_PASSWORD"]),)with driver.session(database=os.getenv("NEO4J_DATABASE", "neo4j")) as session:rows = session.execute_read(lambda tx: list(tx.run(QUERY, email="buyer@example.com", since="2026-01-01", limit=50)))for row in rows:print(row["orderId"], row["sku"], row["name"])driver.close()