api reference

altor-vec API Reference

Complete reference for the altor-vec JavaScript/TypeScript API. All methods are part of the WasmSearchEngine class, which wraps the underlying Rust/WASM HNSW implementation.

Install: npm install altor-vec — MIT licensed, 54KB gzipped WASM, works in any browser. Quick start guide →

Import

// ESM (recommended)
import init, { WasmSearchEngine } from 'altor-vec';

// CommonJS
const { default: init, WasmSearchEngine } = require('altor-vec');

init()

await init()

Initialize the altor-vec WebAssembly module. Must be called once before any WasmSearchEngine methods. Returns a promise that resolves when the WASM binary is loaded and ready.

ParameterTypeDescription
No parameters.

Returns: Promise<void>

import init, { WasmSearchEngine } from 'altor-vec';

// Call once at app startup, before any search operations
await init();
console.log('altor-vec WASM ready');

WasmSearchEngine.from_vectors()

WasmSearchEngine.from_vectors(vectors, dim, M, ef_construction, ef_search)

Create a new HNSW index from a Float32Array of pre-computed embeddings. This is the primary way to build an index from scratch.

ParameterTypeRequiredDescription
vectorsFloat32ArrayrequiredAll embeddings concatenated into one flat array. Length must equal N × dim.
dimnumberrequiredEmbedding dimension. Must match the model used: 384 (all-MiniLM-L6-v2), 768 (nomic-embed-text), 1536 (OpenAI text-embedding-3-small).
MnumberrequiredHNSW graph connectivity. Higher = better recall, more memory. Recommended: 16. Range: 4–64.
ef_constructionnumberrequiredBuild-time accuracy. Higher = better index quality, slower build. Recommended: 200.
ef_searchnumberrequiredQuery-time accuracy. Higher = better recall, slower search. Recommended: 50. Can be tuned without rebuilding.

Returns: WasmSearchEngine instance

const DIM = 384; // embedding dimension
const N = docs.length; // number of documents
const vectors = new Float32Array(N * DIM); // pre-filled with embeddings

const engine = WasmSearchEngine.from_vectors(
  vectors,
  DIM,
  16,   // M
  200,  // ef_construction
  50    // ef_search
);

Tuning guide:

Use caseMef_constructionef_search
Default (documentation search)1620050
Higher recall (product search)24400100
Faster build (large corpus)1210040
Maximum quality32500200

engine.search()

engine.search(queryEmbedding, k) → string

Find the k nearest neighbors to a query embedding using approximate nearest-neighbor search (HNSW). Typically runs in under 1ms for 10,000-vector indexes.

ParameterTypeRequiredDescription
queryEmbeddingFloat32ArrayrequiredThe query vector. Must have the same dimension as the index.
knumberrequiredNumber of nearest neighbors to return. Must be ≤ N (index size).

Returns: string — JSON-encoded array of {id: number, score: number} objects, sorted by score descending (most similar first). Parse with JSON.parse().

// Example: search with a query embedding
const queryEmbedding = new Float32Array(384); // your query vector
const k = 5;

const resultsJson = engine.search(queryEmbedding, k);
const results = JSON.parse(resultsJson);
// results: [{id: 3, score: 0.97}, {id: 11, score: 0.94}, ...]

// Map back to your documents
const docs_results = results.map(r => ({
  ...docs[r.id],
  similarity: r.score
}));

Score interpretation: Scores are cosine similarity values in range [0, 1]. A score of 1.0 means identical vectors. Scores above 0.8 are generally strong semantic matches.

WasmSearchEngine.from_json()

WasmSearchEngine.from_json(jsonString) → WasmSearchEngine

Restore a previously serialized HNSW index. Use this to load a pre-built index from a static file, localStorage, or IndexedDB.

ParameterTypeRequiredDescription
jsonStringstringrequiredJSON string produced by engine.to_json().

Returns: WasmSearchEngine instance — fully restored, ready to search immediately.

// Load pre-built index from a static file (recommended for production)
const resp = await fetch('/search-index.json');
const json = await resp.text();
const engine = WasmSearchEngine.from_json(json);

// Or restore from localStorage
const saved = localStorage.getItem('altor-search-index');
if (saved) {
  const engine = WasmSearchEngine.from_json(saved);
}

engine.to_json()

engine.to_json() → string

Serialize the current HNSW index to a JSON string. Use for caching, persistent storage, or shipping as a pre-built static asset.

ParameterTypeRequiredDescription
No parameters.

Returns: string — JSON representation of the index. Size is approximately 4× the raw vector data (due to the HNSW graph structure).

const json = engine.to_json();

// Store in localStorage (small indexes)
localStorage.setItem('altor-search-index', json);
console.log('Index size:', (json.length / 1024).toFixed(1) + 'KB');

// Or write to disk at build time (Node.js)
import { writeFileSync } from 'fs';
writeFileSync('public/search-index.json', json);

engine.add()

engine.add(id, embedding, metadata)

Add a single vector to an existing index. Useful for incremental updates when you cannot rebuild the full index.

ParameterTypeRequiredDescription
idnumberrequiredInteger ID for this vector. Used to identify the result in search output.
embeddingFloat32ArrayrequiredThe vector to add. Must match the index dimension.
metadataanyoptionalAny JSON-serializable value associated with this vector (e.g., document title, URL).

Returns: void

Note: For bulk additions (100+ vectors), rebuilding the index with from_vectors() is significantly faster than calling add() in a loop. Use add() for truly incremental updates only.

// Add a new document after the index is built
const newEmbedding = new Float32Array(384); // your new vector
engine.add(docs.length, newEmbedding, { title: 'New document', url: '/new' });
docs.push({ title: 'New document', url: '/new' }); // keep docs in sync

engine.delete()

engine.delete(id)

Remove a vector from the index by ID. The HNSW graph is updated to exclude this vector from future search results.

ParameterTypeRequiredDescription
idnumberrequiredInteger ID of the vector to remove. Must match the ID used when adding the vector.

Returns: void

// Remove document with id=3 from search results
engine.delete(3);

TypeScript types

altor-vec ships TypeScript declaration files. All methods are fully typed.

import init, { WasmSearchEngine } from 'altor-vec';

// TypeScript infers: init() returns Promise<void>
await init();

// TypeScript infers: WasmSearchEngine.from_vectors() returns WasmSearchEngine
const engine: WasmSearchEngine = WasmSearchEngine.from_vectors(vectors, 384, 16, 200, 50);

// TypeScript infers: engine.search() returns string (JSON)
const raw: string = engine.search(queryEmbedding, 5);
const results: Array<{id: number, score: number}> = JSON.parse(raw);

Embedding model reference

ModeldimSizeBrowser-nativeBest for
all-MiniLM-L6-v238423MB✅ Transformers.jsGeneral text, docs, small latency budget
nomic-embed-text768274MB✅ Transformers.jsHigher quality, larger apps
multilingual-e5-small384118MB✅ Transformers.jsMultilingual content
text-embedding-3-small1536API❌ Server onlyOpenAI pipeline (generate at build time)
text-embedding-ada-0021536API❌ Server onlyLegacy OpenAI (generate at build time)

Error handling

try {
  await init();
  const engine = WasmSearchEngine.from_vectors(vectors, dim, 16, 200, 50);
  const results = JSON.parse(engine.search(queryEmbedding, 5));
} catch (err) {
  if (err.message.includes('dimension mismatch')) {
    // Query embedding dimension doesn't match index dimension
  } else if (err.message.includes('WASM not initialized')) {
    // init() was not called before using WasmSearchEngine
  } else {
    console.error('altor-vec error:', err);
  }
}

Frequently asked questions

Q: What does init() do exactly?
It fetches and instantiates the altor-vec WASM binary. It must resolve before calling any WasmSearchEngine methods.

Q: What does search() return?
JSON.stringify([{id: number, score: number}, ...]) sorted by score descending. Parse with JSON.parse().

Q: Can I run altor-vec in Node.js?
Yes. The WASM binary runs in Node.js 18+ via the native WebAssembly API. Import the same package — no special Node build needed.

Q: What happens if I call search() before init()?
It throws an error. Always await init() before using WasmSearchEngine.