LLM Technology8 min read

Building Knowledge Graph Apps with Large Language Models

When a knowledge graph helps an LLM app, how to extract entities into Neo4j with an LLM, query them with Cypher, and where Microsoft GraphRAG fits.

By AI Agents DirectoryLast checked
A building with many plants in front of it

A knowledge graph stores facts as nodes (people, products, places) joined by named relationships. Pairing one with a large language model lets you answer questions that plain vector search handles badly, because the connections between facts are stored explicitly instead of being left for the model to guess. This guide covers when a graph is worth the effort, how to build one from text with an LLM, how to query it, and what “GraphRAG” means in practice. Everything here is checked against the official Neo4j documentation, the Microsoft GraphRAG docs and repository, and the GraphRAG research paper.

When a graph actually helps

Standard retrieval-augmented generation (RAG) embeds chunks of text and pulls back the chunks most similar to the question. Microsoft’s GraphRAG documentation names two places where that baseline falls short:

  • Connecting the dots. The answer depends on several pieces of information that only link up through shared entities. “Which planet is ruled by the family Paul is heir to?” needs two hops: Paul to House Atreides, then House Atreides to Caladan. Neither chunk alone answers it.
  • Whole-corpus questions. “What are the main themes in this dataset?” is not a lookup at all. The GraphRAG paper (Edge et al., arXiv 2404.16130) frames it as query-focused summarization and argues ordinary RAG fails on it.

If your questions are mostly “find the paragraph that says X”, a vector index alone is simpler and cheaper; see our Chroma vs Qdrant comparison or the guide to filtering vector search with metadata. A graph pays off when relationships are the point: org charts, supply chains, citations, product dependencies, or any domain where people ask multi-hop questions.

The two main toolkits

Neo4j GraphRAG for PythonMicrosoft GraphRAG
What it isNeo4j’s first-party Python package for building and querying graphsResearch pipeline that indexes a corpus into a graph plus community summaries
Installpip install neo4j-graphrag (Python 3.10+)pip install graphrag (Python 3.10-3.12)
StorageNeo4j 5.18.1+ or AuraParquet tables by default, plus a vector store
QueryingVector, hybrid, vector+Cypher, Text2Cypher retrieversGlobal, local, DRIFT and basic search
StatusMaintained by Neo4j; the KG builder is still marked experimentalLargely in maintenance mode
Docsneo4j.com/docs/neo4j-graphrag-pythonmicrosoft.github.io/graphrag

Neo4j’s package replaces the older neo4j-genai package, which is deprecated. LLM support comes through optional extras for OpenAI, Anthropic, Vertex AI, Cohere, Mistral and Ollama, so you install, for example, neo4j-graphrag[openai].

Step 1: extract entities and relationships with an LLM

Neo4j’s documentation breaks graph construction into a handful of components: a text splitter that cuts input into chunks the model can handle, an optional schema, an optional “lexical graph” of Document and Chunk nodes, an LLM-based extractor for entities and relations, and a writer that saves the results. SimpleKGPipeline wires these together.

The schema matters most. You list the node labels, relationship types and allowed patterns you care about, and the LLM is steered toward them. If you pass no schema, the pipeline asks the LLM to derive one from the input once and then applies it to every chunk. Here is the official README example, trimmed slightly:

import asyncio

from neo4j import GraphDatabase
from neo4j_graphrag.embeddings import OpenAIEmbeddings
from neo4j_graphrag.experimental.pipeline.kg_builder import SimpleKGPipeline
from neo4j_graphrag.llm import OpenAILLM

driver = GraphDatabase.driver("neo4j://localhost:7687", auth=("neo4j", "password"))

node_types = ["Person", "House", "Planet"]
relationship_types = ["PARENT_OF", "HEIR_OF", "RULES"]
patterns = [
    ("Person", "PARENT_OF", "Person"),
    ("Person", "HEIR_OF", "House"),
    ("House", "RULES", "Planet"),
]

embedder = OpenAIEmbeddings(model="text-embedding-3-large")
llm = OpenAILLM(
    model_name="gpt-5",
    model_params={
        "max_completion_tokens": 16000,
        "reasoning_effort": "low",
        "response_format": {"type": "json_object"},
    },
)

kg_builder = SimpleKGPipeline(
    llm=llm,
    driver=driver,
    embedder=embedder,
    schema={
        "node_types": node_types,
        "relationship_types": relationship_types,
        "patterns": patterns,
    },
    on_error="IGNORE",
    from_file=False,
)

text = (
    "The son of Duke Leto Atreides and the Lady Jessica, Paul is the heir of House "
    "Atreides, an aristocratic family that rules the planet Caladan."
)
asyncio.run(kg_builder.run_async(text=text))
driver.close()

A few details from the docs that matter in real use:

  • APOC is required. The README says the APOC core library must be installed in your Neo4j instance for this feature.
  • Structured output is automatic for OpenAILLM, VertexAILLM and AnthropicLLM. When the model supports it, the pipeline enforces the schema at the API level and ignores a response_format you set yourself.
  • Failures are skipped by default. If extraction fails on one chunk, that chunk is dropped and the rest are saved. Switch on_error to RAISE if silent gaps are unacceptable.
  • Duplicates are merged. After each run, an entity resolution step merges nodes that share a label and an identical name. Fuzzy (RapidFuzz) and semantic (spaCy) resolvers are available for messier data.
  • Chunks stay linked. The lexical graph keeps Chunk nodes connected to their Document with FROM_DOCUMENT and to each other with NEXT_CHUNK, so you can trace any extracted fact back to its source text.

The KG builder sits in the package’s experimental namespace, and Neo4j says experimental features may change without notice and are not recommended for production. Pin your version.

Step 2: query the graph with Cypher

Cypher is Neo4j’s declarative query language. Once the example above has run, the two-hop question from earlier is a single pattern match. Because no properties were specified in the schema, the builder gives each entity a name property by default:

MATCH (p:Person)-[:HEIR_OF]->(h:House)-[:RULES]->(pl:Planet)
RETURN p.name, h.name, pl.name

This is the core advantage over chunk retrieval: the hop is answered by the database, not inferred by the model. Writing such queries by hand is fine for known question types. For open-ended questions, the package offers Text2CypherRetriever, which has an LLM write the Cypher. You can give it your schema and a few example question/query pairs to improve accuracy. The docs warn that the generated query may not be valid, and the retriever raises Text2CypherRetrievalError when it cannot run.

Step 3: combine vectors and graph traversal

Most production setups mix the two approaches. The package ships several retrievers, and they all feed the same GraphRAG class that calls the LLM:

  • VectorRetriever: plain similarity search over a Neo4j vector index.
  • VectorCypherRetriever: runs the vector search, then executes a Cypher query starting from each matched node to pull in neighbouring context.
  • HybridRetriever and HybridCypherRetriever: use both a vector index and a full-text index.
  • ToolsRetriever: lets an LLM pick which retrievers to call for a given question.
  • Retrievers for Weaviate, Pinecone and Qdrant if your vectors live outside Neo4j.

With VectorCypherRetriever your retrieval query can use two variables, node (the vector hit) and score. Neo4j’s own movie example returns a film’s title and plot plus its actors:

retrieval_query = """
RETURN node.title as movieTitle,
       node.plot as moviePlot,
       collect { MATCH (actor:Actor)-[:ACTED_IN]->(node) RETURN actor.name } AS actors
"""
retriever = VectorCypherRetriever(driver, index_name=INDEX_NAME, retrieval_query=retrieval_query)
rag = GraphRAG(retriever=retriever, llm=llm)
response = rag.search(query_text="Who starred in The Matrix?", retriever_config={"top_k": 5})
print(response.answer)

Two practical notes: the docs recommend returning node properties rather than whole nodes, and Neo4j vector search is approximate nearest neighbour, so results are not guaranteed to be exact. The vector index’s dimensions must also match your embedding model. If you already work in LangChain or LlamaIndex, the package’s LLM interface is LangChain-compatible and it includes adapters for both frameworks’ text splitters; see our pages on LangChain agents and LlamaIndex.

Microsoft GraphRAG: community summaries for big-picture questions

Microsoft’s approach goes further than entity extraction. Its indexer splits the corpus into “TextUnits”, extracts entities, relationships and key claims, clusters the graph hierarchically with the Leiden algorithm, and writes summaries for each community from the bottom up. At query time it offers four modes:

  • Global search answers whole-dataset questions by working through all community reports in a map-reduce pattern. The docs call it “resource-intensive”.
  • Local search answers questions about specific entities by combining graph data with raw text chunks.
  • DRIFT search is local search with community context added, which broadens where the query starts.
  • Basic search is ordinary top-k vector RAG, included for comparison.

The official quickstart is a few commands. graphrag init creates settings.yaml, a .env file for your API key, and an input folder for text files:

python -m pip install graphrag
graphrag init
graphrag index
graphrag query "What are the top themes in this story?"
graphrag query "Who is Scrooge and what are his main relationships?" --method local

Before you adopt it, weigh three warnings from Microsoft itself. Indexing is expensive, and the docs suggest starting with the tutorial dataset and cheaper models. Results out of the box may be weak, so prompt tuning is strongly recommended. And the repository states the code is a demonstration rather than a supported Microsoft offering, and is now largely in maintenance mode with no new features planned. It is a good way to understand the community-summary technique, but plan for owning it yourself if you ship it.

Choosing an approach

  • Mostly lookup questions: start with a vector index; add a graph later if multi-hop questions show up.
  • Known entities and relationships, multi-hop questions: build a schema-guided graph with SimpleKGPipeline and query it with Cypher or VectorCypherRetriever.
  • Users ask for themes and summaries across a large corpus: try Microsoft GraphRAG’s global search, and budget for indexing cost.

Whichever route you take, the schema you design and the quality of extraction decide most of the outcome. Review a sample of extracted nodes before trusting answers built on them. For tools that support these pipelines, browse our LLM infrastructure directory.

#Knowledge graphs#GraphRAG#Neo4j#RAG#LLM technology
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.