GraphRAG
The GraphRAG class implements a graph-based approach to retrieval augmented generation. It creates a knowledge graph from document chunks where nodes represent documents and edges represent semantic relationships, enabling both direct similarity matching and discovery of related content through graph traversal.
Basic usageBasic usage的直接链接
import { GraphRAG } from '@mastra/rag'
const graphRag = new GraphRAG(1536, 0.7)
// Create the graph from chunks and embeddings
graphRag.createGraph(documentChunks, embeddings)
// Query the graph with embedding
const results = await graphRag.query({
query: queryEmbedding,
topK: 10,
randomWalkSteps: 100,
restartProb: 0.15,
})
Constructor parametersConstructor parameters的直接链接
dimension?:
threshold?:
MethodsMethods的直接链接
createGraphcreategraph的直接链接
Creates a knowledge graph from document chunks and their embeddings.
createGraph(chunks: GraphChunk[], embeddings: GraphEmbedding[]): void
ParametersParameters的直接链接
chunks:
embeddings:
queryquery的直接链接
Performs a graph-based search combining vector similarity and graph traversal.
query({
query,
topK = 10,
randomWalkSteps = 100,
restartProb = 0.15
}: {
query: number[];
topK?: number;
randomWalkSteps?: number;
restartProb?: number;
}): RankedNode[]
ParametersParameters的直接链接
query:
topK?:
randomWalkSteps?:
restartProb?:
ReturnsReturns的直接链接
Returns an array of RankedNode objects, where each node contains:
id:
content:
metadata?:
score:
serializeserialize的直接链接
Returns a JSON-safe snapshot of the graph so it can be persisted and restored later instead of rebuilt with createGraph.
serialize(): GraphRAGSnapshot
ReturnsReturns的直接链接
Returns a GraphRAGSnapshot object containing:
version:
dimension:
threshold:
nodes:
edges:
The snapshot is a deep copy, so mutating it doesn't affect the graph it came from. Every node carries its full embedding, so snapshots are large: a 1,000-node graph built with 1536-dimension embeddings serializes to about 20 MB of JSON. Size your storage column accordingly.
deserializedeserialize的直接链接
Rebuilds a GraphRAG instance from a snapshot produced by serialize.
static deserialize(snapshot: GraphRAGSnapshot): GraphRAG
ParametersParameters的直接链接
snapshot:
Throws if the snapshot version is unsupported, if a node embedding doesn't match the snapshot dimension, or if an edge references a node that isn't in the snapshot. A bad snapshot therefore fails at load time instead of during a later query.
Persisting a graphPersisting a graph的直接链接
Building a graph is O(n²) in the number of chunks, so rebuilding it on every process start is wasteful. Serialize the graph once and store the snapshot wherever you already keep state. A snapshot is plain JSON. Any store works (a file, a blob column, a key-value cache), and GraphRAG doesn't depend on a storage backend.
import { readFile, writeFile } from 'node:fs/promises'
import { GraphRAG } from '@mastra/rag'
import type { GraphRAGSnapshot } from '@mastra/rag'
const SNAPSHOT_PATH = './docs-graph.json'
async function loadOrBuildGraph() {
try {
const snapshot = JSON.parse(await readFile(SNAPSHOT_PATH, 'utf8')) as GraphRAGSnapshot
return GraphRAG.deserialize(snapshot)
} catch {
// No usable snapshot yet, so build the graph from scratch
}
const graphRag = new GraphRAG(1536, 0.7)
graphRag.createGraph(documentChunks, embeddings)
await writeFile(SNAPSHOT_PATH, JSON.stringify(graphRag.serialize()))
return graphRag
}
A snapshot reflects the chunks it was built from and isn't updated incrementally. When the underlying documents change, build the graph again and store a new snapshot.
Advanced exampleAdvanced example的直接链接
// Stricter similarity threshold
const graphRag = new GraphRAG(1536, 0.8)
// Create graph from chunks and embeddings
graphRag.createGraph(documentChunks, embeddings)
// Query with custom parameters
const results = await graphRag.query({
query: queryEmbedding,
topK: 5,
randomWalkSteps: 200,
restartProb: 0.2,
})