Microsoft GraphRAG, hands-on: turn your documents into a knowledge graph you can interrogate
Plain RAG answers questions about single passages. GraphRAG builds a knowledge graph over your whole corpus — entities, relationships, communities, summaries — so you can ask the questions that span documents. This tutorial runs Microsoft's GraphRAG 3.3.0 end to end: install, index, and four ways to query.
- GraphRAG 3.3.0 installs with
pip install graphragon Python 3.10–3.12; the setup, init, and CLI commands in this tutorial were run against the real package on Python 3.12.3. - Indexing is one command (
graphrag index) but five stages: chunking, entity/relationship extraction, graph construction, Leiden community detection, and community-report writing, plus embeddings into LanceDB. - Global search is the reason GraphRAG exists — it map-reduces over community summaries to answer corpus-wide questions like “what are the top themes?” Local search answers entity-specific questions; DRIFT blends the two; basic search is plain vector RAG for comparison.
- The index is inspectable:
output/holds Parquet tables (entities,relationships,communities,community_reports,text_units) you can open with pandas — the graph is data, not a black box. - Cost scales with corpus size: every chunk costs at least one chat-model call, so start small and use inexpensive models (
gpt-4.1-minifor chat,text-embedding-3-smallfor embeddings). Indexing needs your own OpenAI API key.

You have a folder of documents — meeting notes, reports, research papers, support tickets — and a question that no single document answers. “What are the recurring themes across all of this?” “How is this supplier connected to that incident?” “Summarize what we know about this product line.”
Plain vector RAG fails these questions by design. It retrieves the five chunks most similar to your query and asks the model to answer from those. If the answer lives in the pattern across fifty documents rather than in any one passage, the top five chunks will not contain it. You get a confident answer built from fragments.
GraphRAG, Microsoft's open-source package, attacks the problem one level up. Before you ask anything, it reads the whole corpus with an LLM and builds a knowledge graph: every person, organization, place, and event becomes a node; every stated relationship becomes an edge with a strength score. It then clusters the graph into communities with the Leiden algorithm — dense neighborhoods of related entities — and writes a summary report for each community. When you ask a broad question, it does not search raw chunks; it map-reduces over the community reports. When you ask a specific question, it pulls the relevant subgraph plus the source text. The same index answers both kinds of question, and you can open the graph and read it yourself.
This tutorial runs the whole thing end to end with GraphRAG 3.3.0: install, initialize a project, index a small sample corpus you create yourself, inspect the resulting graph as data, and query it four ways. Every setup command, flag, and default below was verified against the installed package on Python 3.12.3 — including the exact contents of the generated settings.yaml. Indexing itself calls the OpenAI API, so that step needs your own key; the sample corpus is tiny on purpose, so the run costs pennies.
1. What you'll need#
- Python 3.10–3.12 (this tutorial used 3.12.3). GraphRAG's own docs list 3.10–3.12 as the supported range — 3.13 is not listed, so do not use it.
- An OpenAI API key with billing enabled. Indexing and querying both call the API; there is no local-model mode out of the box, though you can point the config at any OpenAI-compatible endpoint (see the FAQ).
- A few dollars of API credit at most for the sample corpus — realistically pennies with the mini models used here. Cost is driven by corpus size: one chat call per chunk for extraction, plus description summarization, one report per community, and embeddings. The official docs warn that GraphRAG “can consume a lot of LLM resources,” which is why you start small.
- About 30 minutes for the sample run, most of it waiting on the indexer. No GPU, no Docker, no database to install — the vector store is LanceDB, which ships inside the package and stores its data in a local folder.
One decision to make up front: which models to use. The init command defaults to gpt-4.1 for chat and text-embedding-3-large for embeddings. For learning the system, use the cheaper pair instead — gpt-4.1-mini and text-embedding-3-small. Extraction quality is slightly lower than with the flagship model, but the workflow is identical and the bill is a fraction of the size. You can switch models later by editing two lines in settings.yaml.
2. Step 1: Install GraphRAG#
Create a project folder and a virtual environment, then install the package. The install pulls in the GraphRAG sub-packages (graphrag-llm, graphrag-vectors, graphrag-storage, graphrag-cache, graphrag-input, graphrag-chunking), plus LanceDB, LiteLLM, NetworkX, and the OpenAI client — a substantial dependency tree, so give it a few minutes.
mkdir graphrag_quickstart
cd graphrag_quickstart
python -m venv .venv
source .venv/bin/activate
python -m pip install graphrag
Verify the install by printing the CLI help. You should see five commands: init, index, update, prompt-tune, and query.
graphrag --help
The version installed here is 3.3.0. If pip installs a newer version later, the commands below should still apply — the CLI surface has been stable across the 3.x line — but check the init defaults in your generated settings.yaml against the ones quoted in Step 4 before trusting them blindly.
3. Step 2: Initialize the project#
Run init from inside the project folder, passing the models you chose. Unlike older versions, 3.3.0 takes the model names as flags and does not prompt you interactively.
graphrag init --model gpt-4.1-mini --embedding text-embedding-3-small
That creates four things in the current directory:
.env— a single line,GRAPHRAG_API_KEY=<redacted>. This is where your key goes.settings.yaml— the full pipeline configuration. You will read it in the next step before changing anything.input/— an empty folder. Every document you want indexed goes here.prompts/— twelve prompt files the pipeline uses, fromextract_graph.txt(the entity/relationship extraction prompt) toglobal_search_map_system_prompt.txt. You can edit them, but do not need to yet.
Now put your key in .env. Replace the placeholder value — and only that value — with your OpenAI API key:
GRAPHRAG_API_KEY=sk-proj-your-key-here
Leave the api_key: <redacted> lines in settings.yaml alone. GraphRAG reads the key from the environment; the <redacted> in the YAML file is a placeholder that the .env value overrides. Editing the YAML to paste your key there works too, but then your key lives in a file you might commit — the .env route keeps it out of version control.
4. Step 3: Put documents in input/#
GraphRAG's default input type is plain text: .txt and .md files dropped into input/ are picked up automatically. (CSV and JSON inputs are supported too — see the input: section of settings.yaml.)
Start with a small corpus you control, not your real archive. The sample below is a fictional briefing pack about a specialty foods importer — four short memos with entities that recur across documents, which is exactly what makes a knowledge graph interesting: the same people, companies, and places showing up in different contexts. Create the files with heredocs so the corpus is reproducible:
cat > input/01-company-overview.txt << 'EOF'
Northwind Traders is a specialty foods importer based in Seattle, Washington.
Founder and CEO Elena Vasquez started the company in 2019 with three employees,
a single 12,000-square-foot warehouse near the Port of Seattle, and one container
of Arbequina olive oil from Jaen, Spain. Northwind now employs 48 people and
operates warehouses in Seattle and Portland, Oregon. The company imports olive
oil, saffron, and dried porcini mushrooms from fourteen producers in Spain,
Italy, and Greece, and sells to 40 restaurants and 60 specialty grocers across
the Pacific Northwest. Annual revenue reached 12.4 million dollars in 2025, up
from 4.1 million in 2021. The olive oil line is the largest by volume: Northwind
moves about 90,000 litres a year, mostly Arbequina and Picual from Jaen. Saffron
is the smallest line by weight and the most profitable per kilogram, sourced
mainly from Meridian Foods, a grower cooperative in Valencia, Spain. Dried porcini
come from three foragers' cooperatives in Piedmont, Italy. Elena Vasquez previously
ran procurement for Cascade Provisions in Portland. Operations director Priya Raman
oversees both warehouses and the company's cold-chain logistics. Northwind's
largest customer is Harbor & Vine, a Portland distributor that carries the full
Northwind catalog in Oregon and Washington and accounts for roughly a third of
total revenue. The company plans to open a tasting room at the Seattle warehouse
in 2027.
EOF
cat > input/02-harbor-vine-partnership.txt << 'EOF'
In January 2026, Northwind Traders signed an exclusive distribution partnership
with Harbor & Vine, a Portland-based distributor run by Daniel Okafor, who founded
the company in 2016. Talks began in October 2025 after Harbor & Vine's saffron
sales doubled in a year. Under the agreement, Harbor & Vine becomes the sole
distributor of Northwind's saffron line in Oregon and Washington for three years,
a line worth about 2.8 million dollars a year. The two companies will share a
joint warehouse in Tacoma, Washington, opening in June 2026, and split the 1.2
million dollar cost of a new cold-storage facility there. Daniel Okafor said the
partnership gives Harbor & Vine a premium product line it could not source on
its own, and that next-day delivery to 120 restaurants is now possible from the
Tacoma site. Elena Vasquez said the deal lets Northwind focus on importing while
Harbor & Vine handles last-mile delivery to restaurants. The agreement includes
a revenue share: Harbor & Vine keeps 22 percent of saffron-line sales, Northwind
keeps the rest. One carve-out: Northwind keeps direct sales to its ten largest
restaurant accounts. The companies also agreed to discuss adding the olive oil
line to the exclusive agreement in 2027.
EOF
cat > input/03-saffron-recall.txt << 'EOF'
In March 2026, Northwind Traders recalled one batch of saffron, lot SF-114,
after routine testing found moisture levels of 9.2 percent, above the company's
7 percent specification. The saffron came from Meridian Foods, a grower
cooperative of 23 farmers in Valencia, Spain, that has supplied Northwind since
2021 and provides about 40 percent of its saffron. Operations director Priya Raman
ordered a hold on all six incoming Meridian Foods lots the same day the test
results arrived, and halted all saffron shipments from the Seattle warehouse.
Harbor & Vine pulled lot SF-114 from its Portland warehouse within 24 hours and
notified 31 restaurant customers and 12 grocers. A laboratory retest by Cascade
Analytical in Portland in April 2026 cleared the remaining Meridian Foods stock,
and shipments resumed in May 2026 with a new rule: every incoming lot is tested
before it leaves the Seattle warehouse, with results filed by lot number. Elena
Vasquez told staff the recall cost the company roughly 180,000 dollars: 96,000 in
destroyed stock, 22,000 in testing, and 62,000 in customer credits. She said the
testing rule would stay in place permanently and that the company would qualify
a second saffron grower by September 2026 so no single supplier accounts for more
than 60 percent of any product line.
EOF
cat > input/04-q3-planning-memo.txt << 'EOF'
Q3 2026 planning memo, from Elena Vasquez to the Northwind Traders leadership team.
Three priorities for the quarter. First, expand the olive oil line: we will add
two new producers in Jaen, Spain, Almazara del Sur and Oro del Valle, and trial a
house-brand 500-millilitre bottle for the holiday season, with first shipments in
November. Second, deepen the Harbor & Vine partnership: Daniel Okafor and I have
agreed to extend the Tacoma joint warehouse lease to five years and to open
discussions about adding the olive oil line to the exclusive agreement in 2027.
The Tacoma cold-storage build-out, budgeted at 1.2 million dollars and shared
with Harbor & Vine, must be complete before the holiday rush. Third, supplier
resilience: after the Meridian Foods recall in March, Priya Raman will qualify a
second saffron grower in the Krokos Kozanis region of Greece by September so no
single supplier accounts for more than 60 percent of any product line. She will
also renegotiate the Meridian Foods contract to add moisture testing at origin.
Hiring: four new warehouse roles in Seattle, two in Portland, and one quality
assurance lead to run the new lot-testing rule. Budget for the quarter is 3.1
million dollars, including the Tacoma cold-storage build-out and the holiday
bottle trial. The tasting room planned for the Seattle warehouse in 2027 is on
hold until the Tacoma facility is running.
EOF
ls -la input/
Four files, 864 words — roughly 1,150 tokens, which fits in a single 1,200-token chunk. That is deliberate: one extraction call, a graph small enough to inspect by hand, but with real cross-document structure: Elena Vasquez appears in all four memos, Meridian Foods links the recall to the planning memo, and Harbor & Vine links the partnership to the recall response.
The official quickstart uses a different corpus — A Christmas Carol by Charles Dickens, downloaded from Project Gutenberg. That path is worth knowing, because a novella-length book is where community summaries start to shine:
curl https://www.gutenberg.org/cache/epub/24022/pg24022.txt -o ./input/book.txt
One caveat, verified while writing this tutorial: on November 29, 2026, gutenberg.org was returning HTTP 503 maintenance pages on every URL form of that download, so the command above may fail until the site is back. The Northwind corpus above works regardless, and for your real use the corpus is your own documents anyway — that is the entire point.

5. Step 4: Read settings.yaml before you run it#
Before spending any API calls, read the config init generated. The file is commented and short; these are the settings that shape your first run, taken verbatim from a freshly generated 3.3.0 config:
chunking:
type: tokens
size: 1200
overlap: 100
encoding_model: o200k_base
Documents are split into 1,200-token chunks with 100 tokens of overlap, counted with the o200k_base encoding. Overlap matters: an entity mentioned at a chunk boundary still appears with enough surrounding context in at least one chunk. For dense technical documents, a smaller chunk size (600–800) can improve extraction precision; for narrative text, the default is fine.
extract_graph:
completion_model_id: default_completion_model
prompt: "prompts/extract_graph.txt"
entity_types: [organization, person, geo, event]
max_gleanings: 1
The extractor pulls out four entity types by default — organizations, people, places, and events — and records relationships between them with a strength score. max_gleanings: 1 means the model gets one extra pass to catch entities it missed the first time; raising it improves recall at the cost of another call per chunk. This is the first setting to customize for your domain: a legal corpus wants [organization, person, geo, event, law, court]; a codebase wants modules and functions (and a different prompt — see Step 9).
cluster_graph:
max_cluster_size: 10
community_reports:
completion_model_id: default_completion_model
graph_prompt: "prompts/community_report_graph.txt"
text_prompt: "prompts/community_report_text.txt"
max_length: 2000
max_input_length: 8000
Communities are detected with hierarchical Leiden clustering, capped at ten entities per cluster at the finest level, and each community gets a report of up to 2,000 tokens written from at most 8,000 tokens of input. These reports are the heart of global search — they are what the model reads when you ask a corpus-wide question.
Three more defaults worth knowing:
- Vector store:
vector_store: {type: lancedb, db_uri: output/lancedb}— embeddings live in a local LanceDB folder insideoutput/. Nothing external to run. - Claim extraction is off:
extract_claims: {enabled: false}. Turning it on extracts standalone factual claims (“Northwind recalled lot SF-114 in March 2026”) into their own table — useful for fact-heavy corpora, at the cost of more LLM calls. - Description summarization:
summarize_descriptions: {max_length: 500}— when the same entity appears in many chunks, its scattered descriptions are merged into one summary of at most 500 tokens.
For this first run, change nothing. The defaults are sane, and you want a baseline before you start tuning.
6. Step 5: Validate the config before spending anything#
GraphRAG can validate your whole pipeline without executing it. Run the indexer in dry-run mode with validation skipped — the skip flag tells it not to make the preflight LLM calls that check your model configuration, which is what you want when you are only checking the config itself:
graphrag index --dry-run --skip-validation
Verified on this setup, the command exits with code 0 in a few seconds. You may see one harmless warning from LiteLLM about failing to fetch its remote model cost map and falling back to a local backup — that is a network artifact of the sandbox it ran in, not a problem with your config. If the command errors instead, the message names the setting to fix; the two usual culprits are a malformed settings.yaml edit and a missing input/ folder.
Run this dry-run every time you edit the config. It is free, it is fast, and it catches the typo that would otherwise burn a full indexing run.
7. Step 6: Run the indexer#
Now the real run. From the project root:
graphrag index
The indexer works through its stages in order: loading the input files, chunking them into text units, extracting entities and relationships from every chunk, merging duplicate entities and summarizing their descriptions, building the entity graph, detecting communities with Leiden, writing a report for each community, and embedding the text units and entities into LanceDB. It prints progress as it goes and ends with “All workflows completed successfully.”
For the four-file Northwind corpus this takes a couple of minutes. A book-length corpus takes longer — extraction is one chat call per chunk plus gleanings, and community reports are one call per community — and the official docs' warning about LLM usage is worth remembering before you point it at a thousand documents. Two things keep repeat runs cheap: the indexer caches LLM responses in cache/, so re-running after a config change reuses any call whose inputs have not changed (pass --no-cache only when you deliberately want fresh LLM calls, for example after editing a prompt); and graphrag index --method fast exists as an alternative indexing method alongside the default standard, for when you want a quicker pass over a large corpus while you are still iterating.
When it finishes, output/ holds the index: a set of Parquet tables — entities.parquet, relationships.parquet, communities.parquet, community_reports.parquet, text_units.parquet, and documents.parquet — plus the output/lancedb folder with the vector embeddings. That is the whole index: files on disk, no server, no database to administer.
8. Step 7: Look at what it built#
Before asking anything, inspect the graph. This is the step most tutorials skip, and it is the one that builds your intuition for what the system actually extracted — including its mistakes. The index is plain Parquet, so pandas reads it directly:
import pandas as pd
entities = pd.read_parquet("output/entities.parquet")
relationships = pd.read_parquet("output/relationships.parquet")
reports = pd.read_parquet("output/community_reports.parquet")
print(f"{len(entities)} entities, {len(relationships)} relationships, "
f"{len(reports)} community reports")
print(entities[["title", "type", "description"]].head(10).to_string())
print(relationships[["source", "target", "description", "weight"]]
.sort_values("weight", ascending=False).head(10).to_string())
What to look for: the entities table has one row per entity with its type and a merged description (title, type, description, plus the text_unit_ids that link it back to source chunks). The relationships table has one row per edge — source, target, a description of the relationship, and a numeric weight. On the Northwind corpus you should see Elena Vasquez, Northwind Traders, Harbor & Vine, Meridian Foods, and lot SF-114, with the strongest edges running between the entities that co-occur most. If an entity is missing or mistyped — a person filed as an organization, a relationship the text never stated — that is an extraction error, and it will show up in answers later. Fix it by tightening the extraction prompt or the entity types, not by arguing with the query step.
The community reports are the other table to read. Each row is one community with a title and a summary of up to 2,000 tokens. On a four-file corpus there will be only a few; on a book there will be dozens, organized into a hierarchy of levels — broad themes at the top, tight clusters at the bottom. The --community-level flag on queries (default 2) picks which level of that hierarchy global search reads from: higher values mean smaller, more specific communities.
One more useful switch: if you want a file you can open in a graph viewer, set snapshots: {graphml: true} in settings.yaml before indexing. The indexer then writes a GraphML snapshot of the entity graph alongside the Parquet tables, which tools like Gephi and yEd open directly — the fastest way to see the communities instead of reading about them.

9. Step 8: Ask questions, four ways#
GraphRAG ships four search methods, and picking the wrong one is the most common beginner mistake. They all read the same index; they differ in what they retrieve and what kind of question they serve. The default method is global, so a bare graphrag query is a global search.
Global search answers corpus-wide questions by map-reducing over the community reports: it scores the reports against your question, summarizes the relevant ones, and reduces those summaries into a final answer. Ask it the questions plain RAG cannot answer:
graphrag query "What are the top themes in this story?"
graphrag query "How did the saffron recall change Northwind's supplier strategy?"
The first of those is the example from the official quickstart. The second is the interesting one for the Northwind corpus: no single memo states the strategy change, but the recall memo and the planning memo together do — and the community reports are where that synthesis lives.
Local search answers entity-specific questions. It finds the entities your question mentions, pulls their neighborhood from the graph — descriptions, relationships, and the source text units — and answers from that subgraph. Use it when the question is about a who, a what, or a how-are-they-connected:
graphrag query "Who is Elena Vasquez and what are her main relationships?" --method local
graphrag query "What happened to lot SF-114?" --method local
DRIFT search blends the two. It uses community information to expand a local-style question into follow-up questions, retrieves a wider variety of facts, and synthesizes them — a more thorough answer to a specific question, at the cost of more LLM calls. Reach for it when a local answer feels thin or misses connections you know are in the corpus:
graphrag query "What is Northwind's relationship with Harbor & Vine?" --method drift
Basic search is plain vector RAG over the text units: embed the question, take the top k chunks, summarize. It exists so you can compare GraphRAG's answers against the baseline on the same index — the honest control group:
graphrag query "What happened to lot SF-114?" --method basic
Two flags shape every query. --response-type describes the format you want — the default is “Multiple Paragraphs”, but “Single Sentence” or “List of 3-7 Points” work too. --streaming prints the answer token by token instead of waiting for the whole response. Both are verified flags from the installed CLI:
graphrag query "List the key events in Northwind's 2026 timeline" \
--method global --response-type "List of 3-7 Points" --streaming
Run the same question through global, local, and basic and compare. That comparison is the tutorial's real lesson: the three methods will disagree, and the disagreement tells you which retrieval strategy fits which question. If global and local agree, the answer is well-supported. If basic contradicts the other two, the top chunks were probably missing context — the exact failure GraphRAG exists to fix.
10. Which approach should you use?#
Choose by the shape of the question, not by habit:
| Method | Ask it when… | What it reads | Cost |
|---|---|---|---|
| Global (default) | The question spans the corpus: themes, trends, “what do we know about X overall?” | Community reports, map-reduce | High — one call per relevant report, plus a reduce |
| Local | The question names an entity: who, what, how are A and B connected? | Entity subgraph + source text units | Low — one focused retrieval |
| DRIFT | A specific question needs broader evidence than local search found | Communities + subgraph, via generated follow-ups | Highest — expands into multiple queries |
| Basic | You want the plain-RAG baseline, or the answer is a fact in one passage | Top-k similar text units | Lowest — one embedding + one call |
The rule of thumb: start with local for facts and global for synthesis, use DRIFT when either feels incomplete, and keep basic around as the control that tells you whether the graph is earning its keep. If basic answers everything just as well, your corpus does not need a graph — it needs better chunking.
11. Step 9: Tune the prompts to your domain#
The default prompts are written for general text. On a specialized corpus — legal filings, medical literature, code — they extract the wrong things, because “entity” means something different in your domain than in the default prompt's examples. GraphRAG's answer is prompt-tune: it samples your own documents, infers the domain, and generates tuned versions of the extraction and search prompts:
graphrag prompt-tune --domain "specialty food importing"
The command takes your input documents, embeds a sample of chunks (300 by default, set with --n-subset-max), and rewrites the prompt files in prompts/ with domain-specific entity types and examples. If you omit --domain, it infers one from the data. --selection-method controls how it picks the sample chunks — random by default, or top, all, or auto. After tuning, re-index: the new prompts only affect runs that happen after they are written.
Two cautions. First, prompt-tune itself costs LLM calls, so run it on a representative sample, not your entire archive. Second, read the tuned prompts before you trust them — open prompts/extract_graph.txt and check that the entity types and the worked example actually match your domain. Auto-templating is a starting point, not a verdict.
12. Step 10: Keep the index fresh#
Corpora grow. When you add documents to input/, you do not need to rebuild the whole graph from scratch: graphrag update applies an incremental update, processing the new documents and merging them into the existing index. The updated index is written to an update_output folder rather than overwriting output/, so your previous index stays intact until you decide to swap it in:
graphrag update
Update accepts the same --method options as index (standard, fast, standard-update, fast-update) and the same --cache behavior, so repeat runs stay cheap. For a corpus that changes daily — a support-ticket queue, a research feed — schedule an update run and you have a knowledge graph that keeps up with the documents instead of freezing at the first index.
13. The takeaway#
GraphRAG earns its complexity on exactly one kind of question: the kind no single document answers. If your questions are “what does this passage say?”, plain vector RAG is cheaper, faster, and sufficient — run basic search and prove it to yourself. If your questions are “what are the themes across all of this?”, “how is A connected to B?”, or “what changed, and why?”, the graph is the difference between an answer and a guess.
The workflow to keep: small corpus first, read settings.yaml before you run anything, validate with --dry-run --skip-validation, inspect the Parquet tables before you trust the answers, and pick the search method by the shape of the question. Do that, and the next time someone hands you a folder of documents and asks what is in it, you will have an answer that is built from the whole folder — not from the five chunks that happened to match.
Where to go next: the official getting-started guide is the quickstart this tutorial follows, the configuration reference documents every setting in settings.yaml, and the query engine overview explains the four search methods in depth. The project itself lives at github.com/microsoft/graphrag.