The Big Picture
Step-by-Step Explanation
Step 1 — Keyword Extraction
What it does: Pulls out the important words from your question. How: Two methods run together:- Simple filter: Removes common words (“the”, “is”, “what”) and keeps meaningful terms
- LLM extraction: Asks the language model to identify proper nouns, names, places, and specific terms
Question: “What did Professor Harmon discover at the lighthouse?” Simple keywords:Code:["professor", "harmon", "discover", "lighthouse"]LLM keywords:["Professor Harmon", "lighthouse"]
MultiPathRetrieval._extract_keywords() in multi_path.py
Step 2 — Embed the Question
What it does: Converts the question text into a numerical vector (a list of numbers) that captures its meaning. Why: This vector is used later to find chunks and facts that are semantically similar to the question — even if they don’t share the exact same words. Code:Embedder.aembed_query() in providers/base.py
Step 3a — RELATES Vector Search (Knowledge Graph Facts)
What it does: Searches the relationship edges in the graph by meaning similarity.finalize() embeds the fact text of every relationship between entities except those only a relationship-only table owns (like “Alice WORKS_AT Acme Corp”); an edge ingested since the last finalize() has no vector yet and cannot be found here, and an existing edge whose fact a later ingest changed keeps its earlier vector (finalize() embeds only edges that have none). This step finds the relationships most relevant to the question.
Returns: Fact strings in the one format every relation line uses, source —[TYPE]→ target: text [key: value; ...]:
description. An edge with no description (an older graph) shows its fact instead, without the leading (Alice, WORKS_AT, Acme Corp): triple. The edge’s own values, the signed columns a table wrote on it, follow in brackets, cut near 200 characters.
The names are the endpoints’ current names, read from the edge’s endpoint nodes: a dedup merge moves an edge onto the surviving entity but leaves the extraction-time src_name and tgt_name stored on the edge, so those are used only when an endpoint has no name. A hit becomes a fact line only when it has both names and a rel_type (an edge only a relationship-only table owns is not embedded, so it never comes back here). The endpoints of every hit are also merged into the entity list in step 4, by their stored ids; an endpoint without a name gets an empty name, so it seeds relationship expansion without showing its raw id among the Key Entities.
Important: Facts are scored by their vector similarity to the question. Low-scoring facts are filtered out (see Step 8b) to reduce noise.
Code: search_relates_edges() in entity_discovery.py
Step 3b — Text-to-Cypher (Graph Queries, opt-in)
What it does: Asks the LLM to write a database query (in the Cypher language) that can directly answer the question from the graph structure. Off by default. It costs an extra LLM call on every question, up to 3 when a generated query fails validation and is regenerated. Turn it on withGraphRAG(..., enable_cypher=True) (or MultiPathRetrieval(enable_cypher=True) for a strategy you build yourself).
Why it matters: Some questions are answered by no passage, only by the structure or the values in the graph:
- “How many organizations are in the story?” → needs
COUNT - “What is the average age of the engineers at Acme?” → needs
avg()over a typed column - “List all locations mentioned” → needs
MATCH (l:Location) RETURN l.name
- The LLM receives the ontology as a schema block: every entity label with its properties and their types, including
aliases(the other names a dedup merge folded into the entity); a note that a merged entity can carry more than one type label; anUnknownlabel for entities extraction could not type; theRELATESedge with itsrel_typevalues (when the ontology declares no relations, the first 31 default extraction types, as hints); and the provenance edges, whereMENTIONED_INcarries what that chunk says about the entity. The edge’s storedsrc_nameandtgt_nameare marked as possibly outdated, withstartNode(r).nameandendNode(r).namenamed as the current names. The prompt asks for case-insensitive name matching that also checksaliases. - It generates a Cypher query tailored to the question.
- The query is validated (it must be read-only and use known labels,
Unknownincluded) and sanitized (aLIMIT 25is added when missing, unsupported FalkorDB patterns removed). A query that fails validation is regenerated, up to 3 attempts. - If the query executes successfully, up to 20 rows go directly to the final LLM context in their own section — they are NOT filtered by the reranker. If generation or execution fails, the path returns nothing and the other paths still produce results.
employees__age as an INTEGER). That is what lets a generated query aggregate over a column instead of treating it as text, and it is the main reason to turn this path on.
Rows carry their column names. Each row reaches the answering model as column: value pairs (average_age: 39.5), not bare values, with the columns of one row joined by |. A node reads as name: description (the description cut near 300 characters), never as its full property map with the embedding and bookkeeping; a whole Chunk node reads as its passage (original_chunk for a contextual chunk), even when it has a name; lists and maps are rendered element by element, so nodes inside them read the same way, and carry no column name. The section names the question the query was generated from, so an aggregate is attributable to what was asked:
GraphRAG passes every ontology change to its retrieval strategy through RetrievalStrategy.set_ontology(): the first load, set_ontology(), each evolution method, and a table declaring typed columns during ingest(). Generated Cypher sees a new column the moment a table declares it, with no restart. A strategy you pass only per call (completion(..., strategy=s)) is lent the current ontology for that call when it has none of its own; one constructed with ontology= keeps that ontology and does not see later changes, so leave it unset unless you want a fixed override.
Runs in parallel with step 3a to avoid adding latency.
Code: execute_cypher_retrieval() in cypher_generation.py
Step 4 — Entity Discovery
What it does: Finds entities (people, places, organizations, etc.) in the graph that match the question’s keywords. Two paths:-
Path A — Name matching, as two batched database queries over the first 8 LLM keywords (case-insensitively deduplicated):
- Exact name or alias (case-insensitive), up to 3 entities per keyword, direct name matches before alias matches, then by id. These are added first, so an exact match survives the later caps.
- Name or alias
CONTAINS(e.g., “lighthouse” matches “The Old Lighthouse”), up to 5 per keyword, leaving out the exact matches of pass 1, shortest names first, then alphabetical, then by id. A broad keyword cannot crowd out a rare one. A short acronym (an LLM keyword of three characters or fewer in capitals, such as “US”) only matches exactly or by fulltext, under any spelling of it among the keywords (“us” too), since as a substring it hits unrelated names (“Austria”, “Museum”).
aliasesare the names a dedup merge folded into the entity; a list and a single string (one alias) both count. -
Path B — Fulltext search: Uses the
__Entity__fulltext index on names and descriptions, up to 3 entities for each of the first 6 keywords. Name matches come first: results are ordered by exact name match, then a name containing the keyword (both case-insensitive, ignoring surrounding spaces), then fulltext score, then id. Without that order, a common term scores every hit alike, and a search for “Northwind Robotics” could return dates whose descriptions mention the company instead of the company itself.
name of every node a row returns, lists and maps included. The first 50 distinct names (case-insensitive) are matched case-insensitively against entity names and aliases, direct name matches first, then by id, up to 50 entities. Each comes back with its stored id and current name, so it matches nodes in steps 5 and 6; a value that names no entity stays only in the row text.
Enumeration questions (containing phrases such as “list all”, “every”, “each”, “name all” or “all the”) also add up to 20 siblings: the other neighbours of a hub entity that is connected to two or more of the entities already found, ordered by name, then id.
The entities’ own data. For the first max_entities entities (30 by default), the entity’s own scalar properties are fetched too: the typed columns a table wrote (employees__age) and the declared attributes extraction filled. The SDK’s bookkeeping is left out (id, name, type, description, description_piece_count, source_chunk_ids, spans, embedding, entity_key, is_stub, descriptions, aliases, merged_labels, mention_edge_count, description_summarised), and so are values a merge set aside (<key>__dropped). They are shown in the Key Entities section (step 9).
Code: discover_entities() in entity_discovery.py
Step 5 — Relationship Expansion
What it does: Starting from the discovered entities, walks the graph’sRELATES edges, ranked by how close each edge is to the question.
Both directions. Edges are followed whichever way they are stored, so an entity that is only ever the object of a relation (“X founded Acme”) still has edges to walk.
Up to three rounds, one link further each round, so a chain question (“their student, then that student’s child”) is followed one link per round:
An entity already expanded is not expanded again, and an edge returned by one round is not matched again by a later one, so a back-edge does not take a slot of its far end.
Ranked by the question. Each entity’s edges are ordered by the cosine distance between the question vector and the edge’s embedding (written by
finalize()), then by neighbour id, relation type and edge id. An edge with no embedding ranks after every embedded one. Since a relationship table’s own edges are never embedded, each round also fetches up to 2 such edges per entity in a second query, so a busy entity’s document edges cannot hide its table values.
Cut to max_relationships (20 by default). Lines that say the same thing collapse into one, while two edges between same-name entities with different evidence or values both stay. Lines already in the facts section (step 3a) are left out before the cap is applied. The rest are ordered closest first (equal distances by the line’s text). When there are more lines than the cap, unembedded edges keep up to a fifth of the room (4 at the default), more when the embedded edges leave room. Within each part, lines found beyond the first link (rounds 2 and 3) keep at least a third of the room when there are that many, so first-link lines cannot crowd them all out; room they do not use goes back to first-link lines.
Returns: Formatted relationship strings, one edge per line, in the same format as the facts of step 3a: the endpoints’ current names (an endpoint with no name, such as a table row without a name column, is shown by its id), the edge’s description (its fact without the leading triple when it has none), and the edge’s own table values in brackets:
expand_relationships() in relationship_expansion.py
Step 6 — Chunk Retrieval (4 Paths)
What it does: Finds the actual text passages (chunks) from the original documents that are most relevant to the question. This is the core of passage-based retrieval. Four independent paths ensure we don’t miss relevant passages:
All four paths contribute to a single pool of candidate chunks.
Table rows. A chunk written from a table row has no embedding and is reached only through its entities, so paths C and D keep it slots of its own instead of ranking it after every embedded chunk.
Documents being updated or deleted. Chunks of a document that is not live are left out: the
<id>__pending__<hex> copy an update() writes before cutover, and a document marked pending_delete. Paths C and D skip them before their caps, so they cannot take a slot and leave it empty; the fulltext and vector hits are filtered afterwards, and the vector slots they took are refilled by searching wider (doubling, up to 1024 hits) until filled or the index runs out. A chunk with no document is kept.
Contextual chunks. For a chunk that contextual chunking wrote, the passage is the document’s own text (original_chunk), not the model-written context sentence that opens its indexed text.
Code: retrieve_chunks() in chunk_retrieval.py
Step 7 — Document Mapping
What it does: Looks up which source document each chunk came from, so the final answer can reference the source. Code:fetch_chunk_documents() in chunk_retrieval.py
Step 8 — Reranking (Differentiated)
Facts and passages are ranked by different criteria because they have different characteristics:8a — Passage Reranking (Stored Embeddings)
What it does: Ranks the candidate chunks by how similar their meaning is to the question, keeping the topchunk_top_k (20 by default).
How: Each chunk already has an embedding vector stored in the graph from ingestion. Instead of re-computing embeddings (which would require an expensive API call), we fetch the stored vectors and compute cosine similarity locally. This makes reranking instant instead of taking 2-3 seconds. The candidates without a stored vector, mostly table-row chunks, which ingestion never embeds, are embedded in one call and ranked with the rest, however many there are, so a table row that answers the question is not ranked last. Only when no candidate has a stored vector are they all embedded. Candidates with equal similarity keep the order the paths of step 6 found them in.
Code: rerank_chunks() in result_assembly.py
8b — Fact Filtering (Score Threshold)
What it does: Filters knowledge graph facts by their vector similarity score from step 3a. Why separate? Facts are short structured strings (“Alice —[WORKS_AT]→ Acme”) while passages are long prose paragraphs. Short text has higher cosine similarity variance — a threshold that works for passages would let too many irrelevant facts through. Facts use a threshold of 0.25, keep at most 12, and always keep at least the top 3. Code:filter_facts_by_relevance() in result_assembly.py
Step 9 — Context Assembly
What it does: Combines everything into a structured context document that the LLM uses to generate the final answer. Sections (in order):
An entity line reads
- Name: description (key: value; key: value). The description is cut at a word near 400 characters; the values are the entity’s own data from step 4, in key order, cut at a pair boundary near 200 characters (a single longer value is cut too). Two entities that share a name stay two lines when their description or values differ; a name with neither is listed once, and a described entity of the same name takes its place.
retrieve() returns one RetrieverResultItem per section. The final LLM receives this structured context and generates a natural language answer.
Code: assemble_raw_result() in result_assembly.py
Scores and Ordering
Scores are similarities: higher means closer. Chunk, entity and relationship vector searches return1 - cosine distance and order by it descending. A threshold such as the fact filter’s min_score=0.25 is a floor on similarity.
Almost no search depends on the engine’s row order. FalkorDB 4.x and 6.0.x list unordered rows differently, so these searches order their rows before their LIMIT or cap:
- chunk and entity vector search break ties between equally close nodes by id, fetching more rows (up to 1024) while the cut is still a tie;
- the
RELATESvector search (step 3a) does the same, breaking ties by source id, target id, relation type, description and fact; - chunk fulltext search orders by score, then id;
- entity fulltext search orders by name match, then score, then id;
- the exact-name match orders direct name matches before alias matches, then by id;
- the name
CONTAINSmatch orders by name length, then name, then id; - text-to-Cypher entity lookup orders direct name matches before alias matches, then by id;
- the sibling expansion orders by name, then id;
- relationship expansion orders each entity’s edges before its per-entity limit by distance, neighbour id, relation type and edge id, and its lines by distance, then text;
- the MENTIONED_IN chunk path orders by distance, then chunk id; the 2-hop chunk path orders embedded chunks by distance, then id, and chunks without an embedding by id;
- reranking and fact filtering keep candidates with equal scores in the order the searches above returned them;
GraphStore.get_connected_entities()(used byLocalRetrieval) orders before its cap for 1-hop traversals.
GraphStore.get_connected_entities() with more than one hop, and the rows of a generated Cypher query, which are ordered only if the query the LLM wrote says so.
Every retrieval query also runs on FalkorDB 6.0, which rejects some forms 4.x accepts, such as an outer variable referenced in a subquery’s ORDER BY.
Benchmark Results
All experiments were run on the same pre-built graph (graphrag_sdk_v2_retrieval_benchmark) with 100 questions scored by an LLM judge (0-10 scale).
Enhancement Comparison
Accuracy by Question Type
Text-to-Cypher helps most with Contextual Summarize questions where structured graph relationships provide the context the LLM needs to produce comprehensive summaries.
Isolated Path Performance
Each retrieval path was tested in isolation (only that path, no others) to measure its individual contribution:
Key insight: No single path matches the combined pipeline (83.8%). The value is in multi-path fusion — each path finds information the others miss, and together they cover more ground than any individual approach.
Latency Profile
Configuration
Toggling Text-to-Cypher
For the default strategy, one flag onGraphRAG:
GraphRAG, which then keeps its ontology current:
GraphRAG(enable_cypher=...) is ignored when you pass retrieval_strategy.
Tuning Parameters
Choosing Paths per Question (Path Router)
By defaultMultiPathRetrieval runs every gateable path for every question. Pass a router to select only the gateable paths a question needs; the separately configured enable_cypher path still runs whenever enabled:
A router’s plan is a set of ids from
RETRIEVAL_PATHS: relates (RELATES vector search), entity_cypher (exact / CONTAINS name match), entity_fulltext (full-text name match), expansion (relationship expansion) and chunks (passage retrieval). Unknown ids are ignored, and an empty plan or a failing router falls back to every path, so routing never silently loses recall, except when the latency budget is exhausted: then the router’s LatencyBudgetExceededError propagates and retrieval stops. A plan with expansion but no path that finds seed entities (relates or an entity path) gets both entity paths added. Any object with async plan(query, ctx) -> set[str] works as a router.
RETRIEVAL_PATHS names MultiPathRetrieval’s internal paths. The agent toolkit’s retrieve tool has its own, agent-facing names in graphrag_sdk.tools.specs.RETRIEVE_PATHS (facts, exact_names, fuzzy_names, links, passages; see Agentic Retrieval); facts, exact_names, fuzzy_names and passages map to relates, entity_cypher, entity_fulltext and chunks, while links is the toolkit’s own relation walk.