GrafeoDB¶
The main database class. All query methods return Promise<QueryResult>.
Constructor¶
// In-memory database
const db = GrafeoDB.create();
// Persistent database
const db = GrafeoDB.create('./my_graph.db');
// Open existing database
const db = GrafeoDB.open('./my_graph.db');
Parameters¶
| Method | Parameters | Description |
|---|---|---|
create(path?) | path: string \| undefined | Create a database (in-memory if no path) |
open(path) | path: string | Open an existing database |
Query Methods¶
All query methods accept an optional params object for parameterized queries.
execute()¶
Execute a GQL (ISO standard) query.
const result = await db.execute(
'MATCH (p:Person) WHERE p.age > $minAge RETURN p.name',
{ minAge: 25 }
);
executeCypher()¶
Execute a Cypher query. Requires the cypher feature.
executeGremlin()¶
Execute a Gremlin query. Requires the gremlin feature.
executeGraphql()¶
Execute a GraphQL query. Requires the graphql feature.
executeSparql()¶
Execute a SPARQL query against the RDF triple store. Requires the sparql feature.
executeSql()¶
Execute a SQL/PGQ query (SQL:2023 GRAPH_TABLE). Requires the sql-pgq feature.
const result = await db.executeSql(
'SELECT * FROM GRAPH_TABLE (MATCH (p:Person) COLUMNS (p.name AS name))'
);
Node Operations¶
createNode()¶
Create a node with labels and optional properties.
const node = db.createNode(['Person'], { name: 'Alix', age: 30 });
console.log(node.id); // 0
console.log(node.labels); // ['Person']
getNode()¶
Get a node by ID. Returns null if not found.
deleteNode()¶
Delete a node by ID. Returns true if the node existed.
setNodeProperty()¶
Set a property on a node.
removeNodeProperty()¶
Remove a property from a node. Returns true if the property existed.
addNodeLabel()¶
Add a label to an existing node. Returns true if the label was added.
removeNodeLabel()¶
Remove a label from a node. Returns true if the label was removed.
getNodeLabels()¶
Get all labels for a node. Returns null if the node doesn't exist.
Edge Operations¶
createEdge()¶
Create an edge between two nodes with a type and optional properties.
const edge = db.createEdge(0, 1, 'KNOWS', { since: 2024 });
console.log(edge.edgeType); // 'KNOWS'
console.log(edge.sourceId); // 0
console.log(edge.targetId); // 1
getEdge()¶
Get an edge by ID. Returns null if not found.
deleteEdge()¶
Delete an edge by ID. Returns true if the edge existed.
setEdgeProperty()¶
Set a property on an edge.
removeEdgeProperty()¶
Remove a property from an edge. Returns true if the property existed.
Properties¶
| Property | Type | Description |
|---|---|---|
nodeCount | number | Number of nodes in the database |
edgeCount | number | Number of edges in the database |
Transaction Methods¶
beginTransaction()¶
Start a new transaction with an optional isolation level.
Isolation levels: "read_committed", "snapshot" (default), "serializable".
Vector Search¶
createVectorIndex()¶
Create an HNSW vector similarity index on a node property.
async createVectorIndex(
label: string,
property: string,
dimensions?: number,
metric?: string, // 'cosine' (default), 'euclidean', 'dot'
m?: number, // connections per node (default: 16)
efConstruction?: number // build quality (default: 128)
): Promise<void>
dropVectorIndex()¶
Drop a vector index. Returns true if the index existed.
rebuildVectorIndex()¶
Rebuild a vector index by rescanning all matching nodes. Preserves the original index configuration.
Auto-sync: rebuild is rarely needed
Vector indexes auto-sync when you call setNodeProperty(), batchCreateNodes(), or batchCreateNodesWithProps() with vector data. You only need rebuildVectorIndex() after importing data through non-standard paths or to compact the index after many deletions.
vectorSearch()¶
Search for the k nearest neighbors of a query vector. Returns [[nodeId, distance], ...] sorted by distance ascending (lower distance = more similar). The distance scale depends on the metric configured at index creation: cosine [0, 2], euclidean [0, inf), dot_product (negated), manhattan [0, inf).
async vectorSearch(
label: string,
property: string,
query: number[],
k: number,
ef?: number,
filters?: Record<string, any>
): Promise<number[][]>
const results = await db.vectorSearch('Document', 'embedding', queryVec, 10);
for (const [nodeId, distance] of results) {
console.log(`Node ${nodeId}: distance ${distance}`);
}
// With metadata filter
const filtered = await db.vectorSearch(
'Document', 'embedding', queryVec, 10, undefined, { user_id: 1 }
);
batchCreateNodes()¶
Bulk-insert nodes with vector properties. Returns an array of node IDs.
batchVectorSearch()¶
Batch search for nearest neighbors of multiple query vectors.
async batchVectorSearch(
label: string,
property: string,
queries: number[][],
k: number,
ef?: number,
filters?: Record<string, any>
): Promise<number[][][]>
mmrSearch()¶
Search for diverse nearest neighbors using Maximal Marginal Relevance. Returns [[nodeId, distance], ...] in MMR selection order. The distance values are identical to those returned by vectorSearch() for the same nodes (lower = more similar). The ordering reflects MMR's relevance-diversity balance, not pure distance sorting.
async mmrSearch(
label: string,
property: string,
query: number[],
k: number,
fetchK?: number,
lambdaMult?: number, // diversity vs relevance (0 = max diversity, 1 = max relevance)
ef?: number,
filters?: Record<string, any>
): Promise<number[][]>
Text Search¶
createTextIndex()¶
Create a BM25 text index on a node property for full-text search. The index is automatically kept in sync as nodes are created, updated, or deleted. You do not need to call rebuildTextIndex() after normal write operations.
dropTextIndex()¶
Drop a text index. Returns true if the index existed.
rebuildTextIndex()¶
Rebuild a text index by rescanning all matching nodes. Text indexes auto-sync on normal writes; you only need this after importing data through non-standard paths.
textSearch()¶
Search a text index using BM25 scoring. Returns [[nodeId, score], ...] sorted by descending relevance (higher score = more relevant). BM25 scores are unbounded positive floats.
hybridSearch()¶
Combine text (BM25) and vector similarity search. For best results, create both a text index (createTextIndex()) and a vector index (createVectorIndex()). If either index is missing, that source is silently omitted from fusion.
Returns [[nodeId, score], ...] sorted by fused score descending (higher = more relevant). These are fusion scores, not distances.
Score convention differs from vectorSearch
hybridSearch() returns fusion scores where higher = better. vectorSearch() returns distances where lower = better. For temporal decay, multiply fusion scores but divide distances.
async hybridSearch(
label: string,
textProperty: string,
vectorProperty: string,
queryText: string,
k: number,
queryVector?: number[],
fusion?: string, // 'weighted' for weighted fusion
weights?: number[] // [textWeight, vectorWeight], default [0.5, 0.5]
): Promise<number[][]>
Embedding (opt-in)¶
These methods require the embed feature flag.
registerEmbeddingModel()¶
Register an ONNX embedding model for text-to-vector conversion.
async registerEmbeddingModel(
name: string,
modelPath: string,
tokenizerPath: string,
batchSize?: number
): Promise<void>
embedText()¶
Generate embeddings for a list of texts. Returns one float array per input text.
vectorSearchText()¶
Search a vector index using a text query, generating the embedding on-the-fly.
async vectorSearchText(
label: string,
property: string,
modelName: string,
queryText: string,
k: number,
ef?: number
): Promise<number[][]>
Change Data Capture¶
These methods require the cdc feature flag.
nodeHistory()¶
Returns the full change history for a node.
edgeHistory()¶
Returns the full change history for an edge.
nodeHistorySince()¶
Returns change events for a node since a given epoch.
changesBetween()¶
Returns all change events across entities in an epoch range.
Each ChangeEvent is a JSON object:
{
entity_id: number;
entity_type: 'node' | 'edge';
kind: 'create' | 'update' | 'delete';
epoch: number;
timestamp: number;
before: Record<string, any> | null;
after: Record<string, any> | null;
}
Admin Methods¶
info()¶
Returns high-level database information as a JSON object.
schema()¶
Returns schema information (labels, edge types, property keys).
version()¶
Returns the Grafeo engine version string.
compact()¶
Converts the database to a read-only CompactStore. Takes a snapshot of all nodes and edges, builds a columnar store with CSR adjacency, and switches to read-only mode. Write operations will throw after this call.
const db = GrafeoDB.create();
await db.execute("INSERT (:Person {name: 'Alix', age: 30})");
db.compact();
const result = await db.execute("MATCH (p:Person) RETURN p.name"); // fast
close()¶
Close the database and release resources.