1 Graph database fundamentals
Imagine drawing your family on a big sheet of paper. You draw a circle for you, a circle for Mum, a circle for Grandpa β and then you draw lines between them: "Mum is my mum," "Grandpa is Mum's dad." A graph database is exactly that paper: little circles for things, and lines for how they're connected. Instead of a boring list, you get a map of who-knows-what.
A graph database stores data as a network made of three ingredients. Once you know these three words, you understand the whole idea:
The three building blocks
| Word | What it is | The circle-and-line picture |
|---|---|---|
| Node (also called a vertex) | A "thing" or entity β a person, a movie, a city, a product. | A circle on the page. |
| Edge (also called a relationship) | A connection between two nodes, and it has a direction and a name. | A labelled arrow joining two circles. |
| Property | A piece of information stored on a node or an edge, as a keyβvalue pair. | A sticky note attached to a circle or an arrow. |
The official name for this design is the property graph model, because both
the nodes and the relationships can carry properties. A node usually also has one or more
labels (a type tag like Person or
Movie) so the database knows what kind of thing it is.
In a graph database, relationships are first-class citizens. They aren't hidden inside columns or worked out on the fly β they are stored directly, as real objects, sitting right next to the things they connect. Following a connection is therefore as cheap as walking from one circle to the next.
A diagram in words: a tiny movie graph
Let's build a real little graph about people and movies. Read each line as "circle β arrow β circle":
Spelling that out in our three building blocks:
- Nodes:
KeanuandLana(both labelledPerson), andThe Matrix(labelledMovie). - Edges:
Keanu βACTED_INβ The MatrixandLana βDIRECTEDβ The Matrix. Notice the arrows have names and point a direction. - Properties:
name="Keanu Reeves"on the person node;year=1999on the movie node. We could even put a propertyrole="Neo"on the ACTED_IN edge itself.
In a spreadsheet you might store actors in one sheet, movies in another, and a third sheet
listing which actor was in which movie. To answer "who directed a film Keanu acted in?" you'd
have to flip between all three sheets and match IDs by hand. In the graph above, you just
walk the arrows: start at Keanu, hop along
ACTED_IN to The Matrix, then hop backwards along
DIRECTED to land on Lana. Two hops, no matching needed.
Contrast with rows and tables
A traditional database stores data in tables β grids of rows and columns, like a spreadsheet. A table is brilliant for "here is a list of customers and their email addresses." But a table has no built-in idea of a connection. To link two tables you must repeat an ID in both (a "foreign key") and then recompute the link every time you ask a question. A graph skips that bookkeeping: the link is simply stored. We'll dig into exactly when each one wins in Topic 3.
"People you may know" on social media, "customers who bought this also boughtβ¦", Google Maps finding a route between two places, fraud detection spotting suspicious rings of accounts β these are all graph problems. The data is naturally a network, so a graph database fits like a glove.
2 Knowledge graphs & triples
Think of all the little facts you know, written as tiny three-word sentences: "Dogs are animals," "Bingo is a dog," "Bingo loves bones." If you draw a circle for every thing in those sentences and connect them with arrows, you've drawn a giant web of everything you know. That web is a knowledge graph β a map of facts where you can trace a path from one fact to another and figure out new things, like "Bingo is an animal."
A knowledge graph is a graph (nodes + edges, from Topic 1) used specifically to store facts about the world in a structured, connected way. It's how you turn a pile of loose facts into a web a computer β or an AI agent β can navigate and reason over.
Facts as triples: subject β relationship β object
The atom of a knowledge graph is the triple: a fact written as exactly three parts β a subject, a relationship (also called a predicate), and an object. In graph terms, the subject and object are nodes, and the relationship is the edge between them.
| Subject | Relationship | Object | The fact in English |
|---|---|---|---|
| Marie Curie | WON | Nobel Prize | Marie Curie won a Nobel Prize. |
| Marie Curie | BORN_IN | Warsaw | Marie Curie was born in Warsaw. |
| Warsaw | CAPITAL_OF | Poland | Warsaw is the capital of Poland. |
| Marie Curie | STUDIED | Physics | Marie Curie studied physics. |
Because every fact is a triple, and triples share nodes, the facts automatically link up into one connected web. The "Marie Curie" node above is shared by three triples, and "Warsaw" is shared by two β so without any extra effort you can chain facts together: Marie Curie β born in β Warsaw β capital of β Poland, letting you conclude she was born in Poland even though no single triple said so.
Why an agent loves this shape
Recall from Session 1 that an LLM stores everything as fuzzy patterns in its parameters, with a knowledge cutoff and a tendency to hallucinate. A knowledge graph is the opposite: facts are explicit, checkable, and connected. An agent can:
- Look up a precise fact instead of guessing it ("What did Curie win?" β follow
the
WONedge β "Nobel Prize"). No hallucination. - Traverse several edges to answer a question no single fact answers, exactly like the Warsaw β Poland chain above. This is called multi-hop reasoning.
- Stay current: add or correct a triple and the agent instantly "knows" the new fact β no expensive retraining (contrast with training in Session 1).
Question to the agent: "Which country was the physicist who won the Nobel Prize born in?"
The agent walks the graph:
- Find the node that
WONβNobel PrizeandSTUDIEDβPhysicsβ Marie Curie. - From Marie Curie follow
BORN_INβ Warsaw. - From Warsaw follow
CAPITAL_OFβ Poland. - Answer: Poland.
Three separate stored facts combined into one new answer β with a clear, auditable trail showing why the answer is right. That traceability is something a raw LLM guess can't give you.
When you Google "Marie Curie" and a little fact-box appears on the right, that's Google's Knowledge Graph serving triples. Wikidata is a giant public knowledge graph anyone can query. The idea scales from a handful of triples to billions.
3 Relational (SQL) vs graph databases
Imagine two ways to keep your address book. Way one: a neat list in a notebook β great for "what's Sam's phone number?" Way two: a big web of strings connecting all your friends β great for "who are Sam's friends' friends?" Neither way is "better"; they're good at different questions. The notebook is a normal (SQL) database. The web of strings is a graph database.
The traditional workhorse is the relational database (queried with a language called SQL). It stores data in tables and is the default choice for most software. So when should you reach for a graph instead? The honest answer: it depends on whether your questions are about rows, or about relationships.
Side-by-side comparison
| Aspect | Relational / SQL | Graph |
|---|---|---|
| Stores data as | Tables (rows & columns). | Nodes & edges (a network). |
| Relationships | Implied via foreign keys; recomputed at query time with JOINs. | Stored directly as first-class objects. |
| Great at | Aggregates over many rows β sums, counts, averages, reports. | Traversing connections β "who connects to whom," paths, multi-hop. |
| Struggles with | Deep relationship questions (many JOINs get slow & complex). | Big tabular aggregates & simple flat lookups (overkill). |
| Query language | SQL. | Cypher (Neo4j), Gremlin, etc. β covered in Topic 4. |
| Classic use | Bank ledgers, inventory, invoices, analytics dashboards. | Social networks, recommendations, fraud rings, knowledge graphs. |
The "JOIN explosion" problem β why graphs win at traversal
In SQL, to follow a relationship you perform a JOIN: an operation that matches rows from two tables by a shared ID. One JOIN is fine. But traversal questions need one JOIN per hop, and the cost grows fast. Consider a friendship table where each row is "person A is friends with person B."
| Question | SQL effort | Graph effort |
|---|---|---|
| Sam's friends | 1 JOIN β fine. | 1 hop. |
| Friends of friends | 2 JOINs β getting heavier. | 2 hops. |
| Friends of friends of friends | 3 JOINs β slowing down a lot. | 3 hops. |
| Anyone connected within 5 steps | 5 JOINs over a huge table β often painfully slow. | 5 hops β still quick. |
This blow-up is the JOIN explosion: each extra hop forces SQL to re-scan and re-match enormous numbers of row combinations, so query time can climb steeply. A graph database doesn't re-match anything β at each node, the relationships are already sitting there as pointers, so it simply follows them. Graph people call this index-free adjacency: a node knows its neighbours directly, no lookup table required. The result: deep traversals stay fast even as the data grows.
You want to suggest new friends to Sam by finding people who are friends-of-friends but not yet Sam's direct friends.
- In SQL: join the friendship table to itself (Sam β friends), then join again (friends β their friends), then filter out Sam and anyone already a direct friend, then de-duplicate. Several JOINs, easy to get wrong, and slow on millions of rows.
- In a graph: start at Sam, hop two relationships out, exclude one-hop neighbours. Two hops, naturally fast β this is the graph's home turf.
That's why every "People you may know" feature is powered by a graph, not a stack of JOINs.
Graphs are not a universal upgrade. If your real question is "what was our total revenue last quarter?" β a big aggregate over rows β a relational database is faster, cheaper, and simpler. Many real systems use both: SQL for transactions and reports, a graph for the connected/relationship parts. Pick the tool that matches the shape of your questions, not the hype.
Relationships and traversal (friends-of-friends, paths, multi-hop) β graph wins, because it stores links directly and dodges the JOIN explosion. Tabular aggregates and simple lookups β SQL wins. Match the database to the kind of question you ask most.
4 Neo4j, Cypher & GraphRAG
If a graph is a web of circles and arrows, you need a program to hold the web and a way to ask it questions. Neo4j is the most popular program for holding graphs, and Cypher is the friendly language for asking β and the lovely thing is that a Cypher question is shaped like a little drawing of the very arrows you're looking for. You literally draw the pattern in text.
Neo4j is the leading graph database β the most widely used way to store and query property graphs. It comes with its own query language, Cypher, designed so that querying feels like sketching the pattern you want to find.
Cypher: drawing patterns in text
Cypher uses round brackets () for nodes and arrows
--> for relationships β so the query literally looks like the graph. Square
brackets [] name the relationship type. Here is a small query that finds the
directors of films Keanu Reeves acted in (our Topic 1 graph):
// Find who directed films that Keanu acted in
MATCH (keanu:Person {name: "Keanu Reeves"})-[:ACTED_IN]->(movie:Movie)<-[:DIRECTED]-(director:Person)
RETURN movie.title, director.name
Read it like a sentence: "MATCH a Person named Keanu who ACTED_IN a Movie that a director
DIRECTED, then RETURN the movie's title and the director's name." The pattern
(keanu)-[:ACTED_IN]->(movie)<-[:DIRECTED]-(director) is a tiny picture of
the two hops we walked by hand back in Topic 1 β Cypher just does the walking for you.
Creating data is just as visual. To add a fact (a triple from Topic 2):
// Add the fact: Marie Curie BORN_IN Warsaw
MERGE (mc:Person {name: "Marie Curie"})
MERGE (w:City {name: "Warsaw"})
MERGE (mc)-[:BORN_IN]->(w)
MERGE means "create this if it doesn't already exist," so you can safely add
facts without making duplicates β handy when an agent is continuously writing new knowledge.
Where graphs meet GenAI: graph memory and GraphRAG
Now we connect today's session to two earlier ones.
Graphs as agent memory (Session 9)
In Session 9 we built memory systems so an agent could remember facts across
conversations. A graph is a powerful kind of long-term memory: as the agent learns things about a user
β "Medha prefers window seats," "Medha works at Scaler," "Scaler is in Bangalore" β it writes
them as triples into a graph. Later it can traverse them to reason: "Where does Medha's employer
operate?" β follow WORKS_AT then LOCATED_IN β
"Bangalore." This is relational memory: memory that captures how facts connect,
not just isolated notes.
GraphRAG vs vector RAG (Sessions 4β5)
Recall RAG (Retrieval-Augmented Generation) from Sessions 4β5: you embed documents into vectors, and at query time you fetch the chunks whose embeddings are closest in meaning, then hand them to the LLM. That's excellent for "find me passages that sound like my question." But classic vector RAG retrieves isolated chunks β each snippet comes back on its own, with no idea how it relates to the others.
GraphRAG upgrades this by retrieving connected facts from a knowledge graph instead of (or alongside) loose text chunks. Here's the contrast:
| Aspect | Vector RAG (Sessions 4β5) | GraphRAG |
|---|---|---|
| What's retrieved | Isolated text chunks ranked by semantic similarity. | Connected nodes & relationships from a graph. |
| Good at | "Find passages that mean roughly this." | "Find this fact and everything it connects to." |
| Multi-hop questions | Weak β answer may be split across chunks that don't link. | Strong β just traverse the edges. |
| Explainability | "These chunks looked similar." | A clear path of facts showing why. |
Question: "Which of our suppliers are based in the same city as a customer who filed a complaint last month?"
- Vector RAG: it might fetch a chunk mentioning complaints and a separate chunk mentioning supplier cities β but it has no way to connect them, so the LLM is left guessing the link. This is the classic "isolated chunks" weakness.
- GraphRAG: traverse the graph β
Complaint βFILED_BYβ Customer βLOCATED_INβ City βLOCATED_INβ Supplierβ and return exactly the matching suppliers, with the path as proof. A multi-hop relationship question, which is precisely what graphs are built for (Topic 3).
Many real systems use a hybrid: vectors to find the right starting nodes by meaning, then graph traversal to gather the connected facts around them β the best of both sessions.
Whether you use vector RAG or GraphRAG, the retrieved facts are stuffed into the prompt and an LLM writes the final answer. If you're building this with Claude (Anthropic's models), the same Session 1 rules apply β the facts must fit in the context window, and you still pay per token for everything you retrieve and send. GraphRAG often sends fewer, more relevant facts, which can mean cleaner answers and lower cost than dumping many loosely-related chunks.
Neo4j stores property graphs; Cypher queries them by letting you draw the pattern of nodes and arrows you want. Plugged into GenAI, graphs become relational memory (Session 9) and power GraphRAG β retrieving connected, explainable facts instead of the isolated chunks of vector RAG (Sessions 4β5).
()-[]->()). Graphs serve as an agent's
relational memory and power GraphRAG, which retrieves connected,
multi-hop, explainable facts β a complement to the isolated-chunk retrieval of vector RAG.
β Putting it all together
You just learned how to give an AI a memory of connections. Here's the one-paragraph story that ties all four topics together:
A graph database stores data as a network of nodes (things), edges (named, directed relationships) and properties (details on either), making relationships first-class. Used to hold facts, it becomes a knowledge graph built from triples (subject β relationship β object) that link into a web an agent can traverse for multi-hop reasoning. Compared with a relational/SQL database, graphs win on relationship-heavy, traversal questions because they avoid the JOIN explosion via index-free adjacency, while SQL still wins on tabular aggregates. Neo4j and its Cypher language make graphs practical, and when wired into GenAI they act as an agent's relational memory (Session 9) and power GraphRAG β retrieving connected, explainable facts instead of the isolated chunks of vector RAG (Sessions 4β5).
Quick self-check
What are the three building blocks of a property graph?
Nodes (things/entities), edges (named, directed relationships between nodes), and properties (keyβvalue details stored on a node or an edge). Nodes also usually carry a label naming their type.
What is a "triple" in a knowledge graph, with an example?
A fact written as subject β relationship β object, e.g. "Marie Curie β BORN_IN β Warsaw." The subject and object are nodes; the relationship is the edge. Triples share nodes, so they link into one navigable web.
Why does a "friends of friends of friends" query favour a graph over SQL?
Each hop costs SQL another JOIN, and deep traversals cause the JOIN explosion (re-matching huge numbers of row combinations, getting slow). A graph stores relationships directly (index-free adjacency), so it just follows pointers hop by hop and stays fast.
How does GraphRAG differ from the vector RAG you learned in Sessions 4β5?
Vector RAG retrieves isolated text chunks ranked by semantic similarity. GraphRAG retrieves connected nodes and relationships from a knowledge graph, so it handles multi-hop questions and gives an explainable path of facts. Many systems combine both (vectors to find start nodes, graph traversal to gather connected facts).
In Cypher, what do round brackets and arrows represent?
Round brackets () represent nodes and arrows
--> (with [:TYPE] for the relationship name)
represent edges β so a Cypher pattern looks like a little drawing of the graph you want to match.
π References & Further Reading
Class material
- π Original course notes / handout (source sheet) β open the shared GenAI class material for this session.
- Class handout: "Graph Databases & Relational Memory".
Papers, docs & deep dives
- Neo4j documentation β the leading property-graph database covered in Topic 4.
- Cypher query language manual β the pattern-drawing query language for Neo4j.
- Microsoft GraphRAG β open-source framework for graph-based retrieval-augmented generation.
- Wikidata β a giant public knowledge graph you can browse and query as triples.
- Amazon Neptune β a managed graph database service, for seeing graphs in production.