Skip to content

Graph Class

The Graph class is the main interface for interacting with your knowledge graph.

Instance Creation

Create a Graph instance using createGraph():

typescript
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

typescript
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):

typescript
interface InsertOptions {
  onProgress?: (progress: InsertProgress) => void;
}

interface InsertProgress {
  current: number;
  total: number;
  phase: "chunking" | "extracting" | "embedding" | "storing";
}

Return Value

typescript
interface InsertResult {
  chunks: number;
  entities: number;
  relations: number;
}

Examples

Insert a single string:

typescript
await graph.insert("GraphRAG.js is a TypeScript library...");

Insert multiple strings:

typescript
await graph.insert([
  "Document 1 content...",
  "Document 2 content...",
  "Document 3 content...",
]);

Insert with metadata:

typescript
await graph.insert({
  content: "Document content...",
  metadata: {
    source: "https://example.com",
    author: "John Doe",
    date: "2024-01-01",
    category: "research",
  },
});

Track progress:

typescript
await graph.insert(documents, {
  onProgress: (progress) => {
    console.log(`${progress.phase}: ${progress.current}/${progress.total}`);
  },
});

query()

Query the knowledge graph with natural language questions.

Signature

typescript
// 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):

typescript
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):

typescript
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):

typescript
interface StreamQueryResult {
  textStream: AsyncIterable<string>;     // Streamed answer chunks
  context: string | any[];               // Retrieved context
  usage?: { promptTokens: number; completionTokens: number };
}

ContextResult (contextOnly: true):

typescript
interface ContextResult {
  context: string | any[];               // Retrieved context
  metadata?: Record<string, any>;
}

Examples

Basic query:

typescript
const result = await graph.query("What is GraphRAG.js?");
console.log(result.text);

Query with mode (provider-specific):

typescript
// 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:

typescript
const { textStream, context } = await graph.query("Explain the architecture", {
  stream: true,
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Context-only query:

typescript
const { context } = await graph.query("What is GraphRAG?", {
  contextOnly: true,
});

// Use context with your own LLM pipeline

Query with options:

typescript
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.

typescript
entities.list(filters?: {
  type?: string;
  limit?: number;
  offset?: number;
}): Promise<GEntity[]>

Example:

typescript
// 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.

typescript
entities.get(id: string): Promise<GEntity | null>

Example:

typescript
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.

typescript
entities.search(query: string, limit?: number): Promise<GEntity[]>

Example:

typescript
const results = await graph.entities.search("OpenAI", 5);

entities.delete()

Delete an entity and its relationships.

typescript
entities.delete(id: string): Promise<void>

Example:

typescript
await graph.entities.delete("entity-123");

relations

Access to relationship operations.

Methods

relations.list()

List all relationships or filter by criteria.

typescript
relations.list(filters?: {
  source?: string;
  target?: string;
  type?: string;
  limit?: number;
  offset?: number;
}): Promise<GRelation[]>

Example:

typescript
// 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.

typescript
relations.get(source: string, target: string): Promise<GRelation[]>

Example:

typescript
const relations = await graph.relations.get("person-1", "org-1");

relations.delete()

Delete a specific relationship.

typescript
relations.delete(source: string, target: string, type?: string): Promise<void>

Example:

typescript
// 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

typescript
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:

typescript
const graphml = await graph.export("graphml");
fs.writeFileSync("graph.graphml", graphml);

Export as JSON:

typescript
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:

typescript
const csv = await graph.export("csv");
// Returns: "nodes.csv\n...\n\nedges.csv\n..."

close()

Clean up resources and close connections.

Signature

typescript
close(): Promise<void>

Example

typescript
// 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.

typescript
interface GEntity {
  id: string;
  name: string;
  type: string;
  description: string;
  metadata?: Record<string, any>;
}

GRelation

Represents a relationship (edge) in the graph.

typescript
interface GRelation {
  source: string;
  target: string;
  type: string;
  description: string;
  weight?: number;
  metadata?: Record<string, any>;
}

DocInput

Document input with optional metadata.

typescript
interface DocInput {
  content: string;
  metadata?: Record<string, any>;
}

Error Handling

typescript
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:

typescript
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:

typescript
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:

typescript
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:

typescript
const { context } = await graph.query("question", { contextOnly: true });
console.log("Retrieved context:", context);

See Also

Released under the Elastic License 2.0.