CozoDB for Node.js

0.7.6 · active · verified Wed Apr 22

Cozo-node is a Node.js binding for CozoDB, an embedded Datalog and graph database. It provides direct native access to CozoDB's capabilities, allowing developers to embed a powerful, relational-like database engine directly within their Node.js applications. The current stable version is 0.7.6, with recent minor releases indicating active development. Cozo-node differentiates itself by offering various storage engines, including in-memory ('mem'), SQLite, and RocksDB (depending on compile-time flags), enabling flexible persistence options. It exposes a simple API for running Datalog queries, managing relations, and handling database backups and restores. While primarily accessed via JavaScript/TypeScript, its underlying implementation is in Rust, providing high performance and low-level control. This library is suitable for applications requiring an embedded, queryable knowledge base or a lightweight graph database solution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an in-memory CozoDb instance, perform basic data insertion, query data with and without parameters, and execute more complex Datalog queries with relations, ensuring proper database closure.

import { CozoDb } from 'cozo-node';

async function main() {
    const db = new CozoDb('mem'); // Use 'mem' for in-memory, 'sqlite' for persistent storage
    try {
        console.log('Inserting initial data...');
        await db.run("?[] <- [['hello', 'world!'], ['cozo', 'database']]");

        console.log('Querying all data...');
        const result1 = await db.run("?[a, b] <- [[a, b]]");
        console.log("Result of '?[a, b] <- [[a, b]]':", result1);

        console.log('Querying with parameters...');
        const result2 = await db.run("?[message] <- [['hello', $name]]", { "name": "JavaScript" });
        console.log("Result of '?[message] <- [['hello', $name]]':", result2);

        console.log('Creating and querying a relation...');
        await db.run(`
            :create parent {child, parent}
            :insert parent <- [['Alice', 'Bob'], ['Bob', 'Charlie']]
        `);
        const ancestors = await db.run(`
            ?[ancestor] := parent{child, parent}, ancestor = parent
            :union
            ?[ancestor] := parent{child, intermediate}, ancestor_rec{intermediate, ancestor}
        `, { child: 'Alice' });
        console.log("Ancestors of Alice:", ancestors);

    } catch (err: any) {
        console.error("Database operation failed:", err.display || err.message);
    } finally {
        console.log("Closing database connection.");
        db.close();
        console.log("Database connection closed.");
    }
}

main();

view raw JSON →