sqlite-vec/site/using/js.md
Alex Garcia 356f75cca7 docs
2024-07-31 12:55:03 -07:00

2.8 KiB

Using sqlite-vec in Node.js, Deno, and Bun

npm

To use sqlite-vec in Node.js, Deno or Bun, install the sqlite-vec NPM package using your favorite package manager:

::: code-group

npm install sqlite-vec
bun install sqlite-vec
deno add npm:sqlite-vec

:::

Once installed, use the sqliteVec.load() function to load sqlite-vec SQL functions into a SQLite connection.

import * as sqliteVec from "sqlite-vec";
import Database from "better-sqlite3";

const db = new Database(":memory:");
sqliteVec.load(db);

const { vec_version } = db
  .prepare("select vec_version() as vec_version;")
  .get();

console.log(`vec_version=${vec_version}`);

The load() function is compatable with better-sqlite3, node-sqlite3, jsr:@db/sqlite (Deno), and bun:sqlite.

Working with vectors in JavaScript

if your vectors are represented as an array of numbers, wrap it in a Float32Array, and use .buffer accessor to bind as a parameter to sqlite-vec SQL functions.

// TODO
const embedding = new Float32Array([0.1, 0.2, 0.3, 0.4]);
const stmt = db.prepare("select vec_length(?)");
console.log(stmt.run(embedding.buffer));

Node.js

Here's a quick recipe of using sqlite-vec with better-sqlite3 in Node.js.

See simple-node/demo.mjs for a more complete Node.js demo.

Deno

Here's a quick recipe of using sqlite-vec with jsr:@db/sqlite in Deno. It will only work on Deno version 1.44 or greater, because of a bug in previous Deno version.

Keep in mind, the better-sqlite3 example above also works in Deno, you just need to prefix the better-sqlite3 import with npm:, like import * from "npm:better-sqlite3".

See simple-deno/demo.ts for a more complete Deno demo.

Bun

Here's a quick recipe of using sqlite-vec with bun:sqlite in Bun. The better-sqlite3 example above also works with Bun.

See simple-bun/demo.ts for a more complete Bun demo.