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.
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()
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.
| Parameter | Type | Description |
|---|---|---|
| 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()
Create a new HNSW index from a Float32Array of pre-computed embeddings. This is the primary way to build an index from scratch.
| Parameter | Type | Required | Description |
|---|---|---|---|
vectors | Float32Array | required | All embeddings concatenated into one flat array. Length must equal N × dim. |
dim | number | required | Embedding dimension. Must match the model used: 384 (all-MiniLM-L6-v2), 768 (nomic-embed-text), 1536 (OpenAI text-embedding-3-small). |
M | number | required | HNSW graph connectivity. Higher = better recall, more memory. Recommended: 16. Range: 4–64. |
ef_construction | number | required | Build-time accuracy. Higher = better index quality, slower build. Recommended: 200. |
ef_search | number | required | Query-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 case | M | ef_construction | ef_search |
|---|---|---|---|
| Default (documentation search) | 16 | 200 | 50 |
| Higher recall (product search) | 24 | 400 | 100 |
| Faster build (large corpus) | 12 | 100 | 40 |
| Maximum quality | 32 | 500 | 200 |
engine.search()
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
queryEmbedding | Float32Array | required | The query vector. Must have the same dimension as the index. |
k | number | required | Number 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()
Restore a previously serialized HNSW index. Use this to load a pre-built index from a static file, localStorage, or IndexedDB.
| Parameter | Type | Required | Description |
|---|---|---|---|
jsonString | string | required | JSON 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()
Serialize the current HNSW index to a JSON string. Use for caching, persistent storage, or shipping as a pre-built static asset.
| Parameter | Type | Required | Description |
|---|---|---|---|
| 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()
Add a single vector to an existing index. Useful for incremental updates when you cannot rebuild the full index.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | number | required | Integer ID for this vector. Used to identify the result in search output. |
embedding | Float32Array | required | The vector to add. Must match the index dimension. |
metadata | any | optional | Any 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()
Remove a vector from the index by ID. The HNSW graph is updated to exclude this vector from future search results.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | number | required | Integer 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
| Model | dim | Size | Browser-native | Best for |
|---|---|---|---|---|
| all-MiniLM-L6-v2 | 384 | 23MB | ✅ Transformers.js | General text, docs, small latency budget |
| nomic-embed-text | 768 | 274MB | ✅ Transformers.js | Higher quality, larger apps |
| multilingual-e5-small | 384 | 118MB | ✅ Transformers.js | Multilingual content |
| text-embedding-3-small | 1536 | API | ❌ Server only | OpenAI pipeline (generate at build time) |
| text-embedding-ada-002 | 1536 | API | ❌ Server only | Legacy 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.