@grafeo-db/js
v0.6.1
Published
Node.js/TypeScript bindings for Grafeo - a high-performance embeddable graph database
Maintainers
Readme
@grafeo-db/js
Node.js/TypeScript bindings for Grafeo, a high-performance, embeddable graph database with a Rust core.
Installation
npm install @grafeo-db/jsQuick Start
An ES module (index.mjs, or a .js file in a package with "type": "module"), with top-level await:
import { GrafeoDB } from '@grafeo-db/js';
// In-memory database
const db = GrafeoDB.create();
// Or persistent: const db = GrafeoDB.create('./my-graph');
// Create nodes and an edge
const alix = db.createNode(['Person'], { name: 'Alix', age: 30 });
const gus = db.createNode(['Person'], { name: 'Gus', age: 25 });
db.createEdge(alix.id, gus.id, 'KNOWS', { since: 2024 });
// Query with GQL
const result = await db.execute('MATCH (p:Person) WHERE p.age > 20 RETURN p.name, p.age');
for (const row of result.toArray()) {
console.log(row); // { 'p.name': 'Alix', 'p.age': 30 }, then Gus
}
db.close();CommonJS works as well: const { GrafeoDB } = require('@grafeo-db/js');.
API Reference
Database
// Create or open: one of
const db = GrafeoDB.create(); // in-memory
// const db = GrafeoDB.create('./path'); // persistent: created, or opened if it exists
// const db = GrafeoDB.open('./path'); // open existing
// const db = GrafeoDB.create('./path', { queryTimeout: 5_000 }); // queries fail after 5 s (null: no limit)
// Counts
db.nodeCount(); // number of nodes
db.edgeCount(); // number of edgesQuery Languages
All query methods return Promise<QueryResult> and accept optional parameters:
await db.execute(gql, params?); // GQL (ISO standard)
await db.executeCypher(query, params?); // Cypher
await db.executeGremlin(query, params?); // Gremlin
await db.executeGraphql(query, params?); // GraphQL
await db.executeSparql(query, params?); // SPARQL
await db.executeSql(query, params?); // SQL/PGQ (SQL:2023)Node & Edge CRUD
const node = db.createNode(['Label'], { key: 'value' });
const edge = db.createEdge(sourceId, targetId, 'TYPE', { key: 'value' });
const n = db.getNode(id); // JsNode | null
const e = db.getEdge(id); // JsEdge | null
db.setNodeProperty(id, 'key', 'value');
db.setEdgeProperty(id, 'key', 'value');
db.deleteNode(id); // returns boolean
db.deleteEdge(id); // returns booleanTransactions
const tx = db.beginTransaction();
try {
await tx.execute("INSERT (:Person {name: 'Harm'})");
tx.commit();
} catch (e) {
tx.rollback();
throw e;
}A commit that fails (a write conflict, gqlStatus 40000) ends the transaction: tx.isActive is false after it and
tx.rollback() does nothing, so the catch above sees the conflict. Such an error has isRetryable set: run the
transaction again.
With explicit resource management (using, in Node.js 24+ or TypeScript compiled to an older target), a transaction
that is not committed rolls back at the end of its block:
{
using tx = db.beginTransaction();
await tx.execute("INSERT (:Person {name: 'Harm'})");
tx.commit(); // auto-rollback if not committed
}Transaction control statements (START TRANSACTION, COMMIT, ROLLBACK) are refused inside tx.execute()
(gqlStatus 25000): end a transaction with tx.commit() or tx.rollback().
QueryResult
result.columns; // column names
result.length; // row count
result.executionTimeMs; // execution time (ms)
result.get(0); // single row as object
result.toArray(); // all rows as objects
result.scalar(); // first column of first row
result.nodes(); // extracted nodes
result.edges(); // extracted edgesErrors
A call that fails throws, or rejects its promise with, an Error. An error from the database also has gqlStatus,
its ISO GQL status: 22012 for a division by zero, 22003 for a value out of range, 42001 for a syntax error,
25000 for a transaction that already ended, 08000 for a database file another handle or process holds. It also has
errorCode, the Grafeo code (GRAFEO-S004 for that held file), and isRetryable, whether running it again can
succeed (a write conflict).
import type { GrafeoError } from '@grafeo-db/js';
try {
await db.execute('RETURN 1 / 0');
} catch (error) {
console.log((error as GrafeoError).gqlStatus); // '22012'
}Graph Projections
db.createProjection('people', ['Person'], ['KNOWS']); // returns boolean
const projections = db.listProjections(); // ['people']
db.dropProjection('people');Data Import
const count = await db.importCsv('./users.csv', { label: 'Person', headers: true });
const count2 = await db.importJsonl('./events.jsonl', { label: 'Event' });Backup and Restore
db.backupFull('/backups/full');
db.backupIncremental('/backups/incr');
GrafeoDB.restoreToEpoch('/backups/full', 100, './restored');Vector Search
// Create an HNSW index
await db.createVectorIndex('Document', 'embedding', 384);
// Bulk insert
const ids = await db.batchCreateNodes('Document', 'embedding', vectors);
// Search
const results = await db.vectorSearch('Document', 'embedding', queryVector, 10);Features
- GQL, Cypher, SPARQL, Gremlin, GraphQL and SQL/PGQ query languages
- Full node/edge CRUD with property management
- ACID transactions with automatic rollback
- HNSW vector similarity search with batch operations
- Graph projections (filtered virtual views)
- CSV and JSON Lines import
- Incremental backup and restore
- Async/await API backed by Rust + Tokio
- TypeScript definitions included
Links
- Documentation
- API Stability: which calls are stable and which are experimental; a call here has the level of the Rust call it wraps
- GitHub
- Python Package
- WASM Package
License
Apache-2.0
