Neo4j
medium 25 minNeo4j is a graph database.
See it run
Follow stored links, see a walk spread, write without duplicates, and commit with a majority.
Operations
Anchor and expand
Find Ana's grandchildren in the family graph.
Step 1 of 5
The graph
5 nodes, 5 relationships
Five people, three parent links and two marriages. The arrow is the stored direction.
Step 1: The graph
def grandchildren(index, key): start = index[key] # the anchor out = [] for child in start.out["PARENT_OF"]: for g in child.out["PARENT_OF"]: out.append(g) return out- Work
- 1 lookup, 2 hops
- Watch out for
- Missing index
- Scan first
- Reads every person
The other branches of the graph are never read.
In the real world
The same neo4j doing real jobs. Pick one and step through it.
A1 to A4 are accounts. Ph is a phone and Ad is an address.
Step 1 of 5
Four accounts
4 accounts
In their own rows nothing is strange.
Step 1: Four accounts
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No uniqueness constraint on the key
criticalEvery MERGE scans the label, and two requests at once can create two nodes.
WrongMERGE (p:Person {id: $id}) // no constraintRightCREATE CONSTRAINT person_id IF NOT EXISTSFOR (p:Person) REQUIRE p.id IS UNIQUEAn unbounded path
criticalWork grows with degree to the power of hops until memory or patience ends.
WrongMATCH (a:Person {id: $id})-[*]-(b)RightMATCH (a:Person {id: $id})-[:FOLLOWS]->{1,3}(b:Person)Values pasted into the query
majorEach text is a new plan, and input can become code.
Wrongrun("MATCH (p {id: '" + user_input + "'})")Rightrun("MATCH (p:Person {id: $id}) RETURN p", id=user_input)Read, compute, write back
majorRead committed lets another transaction change the value in between.
Wrongn = read("RETURN p.likes")write("SET p.likes = $n", n + 1)RightSET p.likes = p.likes + 1
Interview tips
How to explain it
- Links are stored as data.
- An index finds the first node, then we walk.
- Cost is the neighbourhood touched.
Say three things
- The type.
- The direction.
- The depth limit.
Reach for it when
- The path is the answer.
- The number of steps is unknown.
- Shared things join people.
Choose something else when
- You add up everything.
- One join is enough.
- Writes exceed one leader.