Graph Class
The Graph class is the main interface for interacting with your knowledge graph.
Instance Creation
Create a Graph instance using createGraph():
import { createGraph } from "@graphrag-js/core";
import { lightrag } from "@graphrag-js/lightrag";
import { memoryStorage } from "@graphrag-js/memory";
import { openai } from "@ai-sdk/openai";
const graph = createGraph({
model: openai("gpt-4o-mini"),
embedding: openai.embedding("text-embedding-3-small"),
provider: lightrag(),
storage: memoryStorage(),
});Methods
insert()
Add documents to the knowledge graph.
Signature
insert(
input: string | string[] | DocInput | DocInput[],
options?: InsertOptions
): Promise<InsertResult>Parameters
input: The documents to insert. Can be:
- Single string
- Array of strings
- Single document object with metadata
- Array of document objects
options (optional):
interface InsertOptions {
onProgress?: (progress: InsertProgress) => void;
}
interface InsertProgress {
current: number;
total: number;
phase: "chunking" | "extracting" | "embedding" | "storing";
}Return Value
interface InsertResult {
chunks: number;
entities: number;
relations: number;
}Examples
Insert a single string:
await graph.insert("GraphRAG.js is a TypeScript library...");Insert multiple strings:
await graph.insert([
"Document 1 content...",
"Document 2 content...",
"Document 3 content...",
]);Insert with metadata:
await graph.insert({
content: "Document content...",
metadata: {
source: "https://example.com",
author: "John Doe",
date: "2024-01-01",
category: "research",
},
});Track progress:
await graph.insert(documents, {
onProgress: (progress) => {
console.log(`${progress.phase}: ${progress.current}/${progress.total}`);
},
});query()
Query the knowledge graph with natural language questions.
Signature
// Regular query
query(
question: string,
options?: QueryOptions
): Promise<QueryResult>
// Streaming query
query(
question: string,
options: QueryOptions & { stream: true }
): Promise<StreamQueryResult>
// Context-only query
query(
question: string,
options: QueryOptions & { contextOnly: true }
): Promise<ContextResult>Parameters
question: string: The natural language question to answer.
options (optional):
interface QueryOptions {
mode?: string; // Provider-specific query mode
maxDepth?: number; // Graph traversal depth
topK?: number; // Number of initial results
stream?: boolean; // Enable streaming
contextOnly?: boolean; // Return context without LLM answer
withReferences?: boolean; // Include source references
filters?: Record<string, any>; // Metadata filters
}Return Values
QueryResult (default):
interface QueryResult {
text: string; // Generated answer
context: string | any[]; // Retrieved context
usage: { promptTokens: number; completionTokens: number };
metadata?: Record<string, any>; // Additional metadata
}StreamQueryResult (stream: true):
interface StreamQueryResult {
textStream: AsyncIterable<string>; // Streamed answer chunks
context: string | any[]; // Retrieved context
usage?: { promptTokens: number; completionTokens: number };
}ContextResult (contextOnly: true):
interface ContextResult {
context: string | any[]; // Retrieved context
metadata?: Record<string, any>;
}Examples
Basic query:
const result = await graph.query("What is GraphRAG.js?");
console.log(result.text);Query with mode (provider-specific):
// LightRAG modes
await graph.query("Question", { mode: "local" });
await graph.query("Question", { mode: "global" });
await graph.query("Question", { mode: "hybrid" });
// Microsoft GraphRAG modes
await graph.query("Question", { mode: "local" });
await graph.query("Question", { mode: "global" });Streaming query:
const { textStream, context } = await graph.query("Explain the architecture", {
stream: true,
});
for await (const chunk of textStream) {
process.stdout.write(chunk);
}Context-only query:
const { context } = await graph.query("What is GraphRAG?", {
contextOnly: true,
});
// Use context with your own LLM pipelineQuery with options:
const result = await graph.query("Question", {
topK: 10,
maxDepth: 2,
withReferences: true,
});entities
Access to entity operations.
Methods
entities.list()
List all entities or filter by criteria.
entities.list(filters?: {
type?: string;
limit?: number;
offset?: number;
}): Promise<GEntity[]>Example:
// Get all entities
const allEntities = await graph.entities.list();
// Filter by type
const people = await graph.entities.list({ type: "person" });
// Paginate
const page1 = await graph.entities.list({ limit: 10, offset: 0 });
const page2 = await graph.entities.list({ limit: 10, offset: 10 });entities.get()
Get a specific entity by ID.
entities.get(id: string): Promise<GEntity | null>Example:
const entity = await graph.entities.get("entity-123");
if (entity) {
console.log(entity.name, entity.type, entity.description);
}entities.search()
Search entities by name or description.
entities.search(query: string, limit?: number): Promise<GEntity[]>Example:
const results = await graph.entities.search("OpenAI", 5);entities.delete()
Delete an entity and its relationships.
entities.delete(id: string): Promise<void>Example:
await graph.entities.delete("entity-123");relations
Access to relationship operations.
Methods
relations.list()
List all relationships or filter by criteria.
relations.list(filters?: {
source?: string;
target?: string;
type?: string;
limit?: number;
offset?: number;
}): Promise<GRelation[]>Example:
// Get all relations
const allRelations = await graph.relations.list();
// Filter by source entity
const entityRelations = await graph.relations.list({
source: "entity-123",
});
// Filter by type
const workRelations = await graph.relations.list({
type: "works_at",
});relations.get()
Get relationships between two entities.
relations.get(source: string, target: string): Promise<GRelation[]>Example:
const relations = await graph.relations.get("person-1", "org-1");relations.delete()
Delete a specific relationship.
relations.delete(source: string, target: string, type?: string): Promise<void>Example:
// Delete all relations between two entities
await graph.relations.delete("person-1", "org-1");
// Delete specific relation type
await graph.relations.delete("person-1", "org-1", "works_at");export()
Export the graph in various formats.
Signature
export(format: "graphml" | "json" | "csv"): Promise<string>Parameters
format: The export format:
"graphml"- GraphML XML format (compatible with Neo4j, Gephi, Cytoscape)"json"- JSON format with nodes and edges"csv"- CSV format (two files: nodes.csv and edges.csv)
Examples
Export as GraphML:
const graphml = await graph.export("graphml");
fs.writeFileSync("graph.graphml", graphml);Export as JSON:
const json = await graph.export("json");
const data = JSON.parse(json);
console.log(data.nodes.length, "nodes");
console.log(data.edges.length, "edges");Export as CSV:
const csv = await graph.export("csv");
// Returns: "nodes.csv\n...\n\nedges.csv\n..."close()
Clean up resources and close connections.
Signature
close(): Promise<void>Example
// Always close when done
await graph.close();Important: Always call close() when you're done with the graph, especially when using external storage backends. This ensures:
- Database connections are properly closed
- Pending writes are flushed
- Resources are released
Data Types
GEntity
Represents an entity (node) in the graph.
interface GEntity {
id: string;
name: string;
type: string;
description: string;
metadata?: Record<string, any>;
}GRelation
Represents a relationship (edge) in the graph.
interface GRelation {
source: string;
target: string;
type: string;
description: string;
weight?: number;
metadata?: Record<string, any>;
}DocInput
Document input with optional metadata.
interface DocInput {
content: string;
metadata?: Record<string, any>;
}Error Handling
import { GraphError, StorageError, ProviderError } from "@graphrag-js/core";
try {
await graph.insert(documents);
} catch (error) {
if (error instanceof StorageError) {
console.error("Storage error:", error.message);
} else if (error instanceof ProviderError) {
console.error("Provider error:", error.message);
} else {
console.error("Unknown error:", error);
}
}Best Practices
1. Resource Management
Always close graphs when done:
const graph = createGraph(options);
try {
await graph.insert(documents);
await graph.query("question");
} finally {
await graph.close();
}2. Progress Tracking
Track progress for long-running inserts:
await graph.insert(largeDataset, {
onProgress: ({ phase, current, total }) => {
const percent = Math.round((current / total) * 100);
console.log(`${phase}: ${percent}%`);
},
});3. Batch Inserts
Insert documents in batches for better performance:
const batchSize = 100;
for (let i = 0; i < documents.length; i += batchSize) {
const batch = documents.slice(i, i + batchSize);
await graph.insert(batch);
}4. Context Inspection
Use contextOnly to inspect retrieved context:
const { context } = await graph.query("question", { contextOnly: true });
console.log("Retrieved context:", context);See Also
- createGraph() - Create a graph instance
- GraphProvider - Provider interface
- Storage Interfaces - Storage backends