VelesDB TypeScript SDK: The Local Vector Database for AI & RAG. Microsecond semantic search in Browser & Node.js.
npm install @wiscale/velesdb-sdkOfficial TypeScript SDK for VelesDB - Vector Search in Microseconds.
``bash`
npm install @wiscale/velesdb-sdk
`typescript
import { VelesDB } from '@wiscale/velesdb-sdk';
// Initialize with WASM backend
const db = new VelesDB({ backend: 'wasm' });
await db.init();
// Create a collection
await db.createCollection('documents', {
dimension: 768, // BERT embedding dimension
metric: 'cosine'
});
// Insert vectors
await db.insert('documents', {
id: 'doc-1',
vector: new Float32Array(768).fill(0.1),
payload: { title: 'Hello World', category: 'greeting' }
});
// Batch insert
await db.insertBatch('documents', [
{ id: 'doc-2', vector: [...], payload: { title: 'Second doc' } },
{ id: 'doc-3', vector: [...], payload: { title: 'Third doc' } },
]);
// Search
const results = await db.search('documents', queryVector, { k: 5 });
console.log(results);
// [{ id: 'doc-1', score: 0.95, payload: { title: '...' } }, ...]
// Cleanup
await db.close();
`
`typescript
import { VelesDB } from '@wiscale/velesdb-sdk';
const db = new VelesDB({
backend: 'rest',
url: 'http://localhost:8080',
apiKey: 'your-api-key' // optional
});
await db.init();
// Same API as WASM backend
await db.createCollection('products', { dimension: 1536 });
await db.insert('products', { id: 'p1', vector: [...] });
const results = await db.search('products', query, { k: 10 });
`
Create a new VelesDB client.
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| backend | 'wasm' \| 'rest' | Yes | Backend type |url
| | string | REST only | Server URL |apiKey
| | string | No | API key for authentication |timeout
| | number | No | Request timeout (ms, default: 30000) |
Initialize the client. Must be called before any operations.
Create a new collection.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| dimension | number | Required | Vector dimension |metric
| | 'cosine' \| 'euclidean' \| 'dot' \| 'hamming' \| 'jaccard' | 'cosine' | Distance metric |storageMode
| | 'full' \| 'sq8' \| 'binary' | 'full' | Memory optimization mode |
#### Storage Modes
| Mode | Memory (768D) | Compression | Use Case |
|------|---------------|-------------|----------|
| full | 3 KB/vector | 1x | Default, max precision |sq8
| | 776 B/vector | 4x | Scale, RAM-constrained |binary
| | 96 B/vector | 32x | Edge, IoT |
`typescript`
// Memory-optimized collection
await db.createCollection('embeddings', {
dimension: 768,
metric: 'cosine',
storageMode: 'sq8' // 4x memory reduction
});
Insert a single vector.
`typescript`
await db.insert('docs', {
id: 'unique-id',
vector: [0.1, 0.2, ...], // or Float32Array
payload: { key: 'value' } // optional metadata
});
Insert multiple vectors efficiently.
Search for similar vectors.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| k | number | 10 | Number of results |filter
| | object | - | Filter expression |includeVectors
| | boolean | false | Include vectors in results |
Delete a vector by ID. Returns true if deleted.
Get a vector by ID. Returns null if not found.
Full-text search using BM25 algorithm.
`typescript`
const results = await db.textSearch('docs', 'machine learning', { k: 10 });
Combined vector + text search with RRF fusion.
`typescript`
const results = await db.hybridSearch(
'docs',
queryVector,
'machine learning',
{ k: 10, vectorWeight: 0.7 } // 0.7 = 70% vector, 30% text
);
Execute a VelesQL query.
`typescript
// Simple query
const results = await db.query(
'documents',
"SELECT * FROM documents WHERE category = 'tech' LIMIT 10"
);
// With vector parameter
const results = await db.query(
'documents',
"SELECT * FROM documents WHERE VECTOR NEAR $query LIMIT 5",
{ query: [0.1, 0.2, ...] }
);
// Hybrid query
const results = await db.query(
'docs',
"SELECT * FROM docs WHERE VECTOR NEAR $v AND content MATCH 'rust' LIMIT 10",
{ v: queryVector }
);
`
Multi-query fusion search for RAG pipelines using Multiple Query Generation (MQG).
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| k | number | 10 | Number of results |fusion
| | 'rrf' \| 'average' \| 'maximum' \| 'weighted' | 'rrf' | Fusion strategy |fusionParams
| | object | { k: 60 } | Strategy-specific parameters |filter
| | object | - | Filter expression |
`typescript
// RRF fusion (default) - best for most RAG use cases
const results = await db.multiQuerySearch('docs', [emb1, emb2, emb3], {
k: 10,
fusion: 'rrf',
fusionParams: { k: 60 }
});
// Weighted fusion - like SearchXP scoring
const results = await db.multiQuerySearch('docs', [emb1, emb2], {
k: 10,
fusion: 'weighted',
fusionParams: { avgWeight: 0.6, maxWeight: 0.3, hitWeight: 0.1 }
});
// Average/Maximum fusion
const results = await db.multiQuerySearch('docs', vectors, {
k: 10,
fusion: 'average' // or 'maximum'
});
`
> Note: Multi-query fusion is only available with the REST backend.
Check if a collection is empty.
`typescript`
const empty = await db.isEmpty('documents');
if (empty) {
console.log('No vectors in collection');
}
Flush pending changes to disk.
`typescript`
await db.flush('documents');
Close the client and release resources.
VelesDB supports hybrid vector + graph queries.
`typescript`
await db.addEdge('social', {
id: 1, source: 100, target: 200,
label: 'FOLLOWS',
properties: { since: '2024-01-01' }
});
`typescript`
const edges = await db.getEdges('social', { label: 'FOLLOWS' });
`typescript`
const result = await db.traverseGraph('social', {
source: 100, strategy: 'bfs', maxDepth: 3
});
`typescript`
const degree = await db.getNodeDegree('social', 100);
Execute advanced SQL-like queries with aggregation, joins, and set operations.
`typescript
// Group by with aggregates
const result = await db.query('products',
SELECT category, COUNT(*), AVG(price)
FROM products
GROUP BY category
HAVING COUNT(*) > 5 AND AVG(price) > 50);
// Access results
for (const row of result.results) {
console.log(row.payload.category, row.payload.count);
}
`
`typescript
// Order by semantic similarity
const result = await db.query('docs',
SELECT * FROM docs
ORDER BY similarity(vector, $v) DESC
LIMIT 10, { v: queryVector });`
`typescript
// Cross-collection join
const result = await db.query('orders',
SELECT * FROM orders
JOIN customers AS c ON orders.customer_id = c.id
WHERE status = $status, { status: 'active' });`
`typescript
// Combine query results
const result = await db.query('users',
SELECT * FROM active_users
UNION
SELECT * FROM archived_users);
// Find common elements
const result = await db.query('users',
SELECT id FROM premium_users
INTERSECT
SELECT id FROM active_users);`
`typescript
// RRF fusion (default)
const result = await db.query('docs',
SELECT * FROM docs
USING FUSION(strategy = 'rrf', k = 60)
LIMIT 20);
// Weighted fusion
const result = await db.query('docs',
SELECT * FROM docs
USING FUSION(strategy = 'weighted', vector_weight = 0.7, graph_weight = 0.3)
LIMIT 20);`
Build type-safe VelesQL queries with the fluent builder API.
`typescript
import { velesql } from '@wiscale/velesdb-sdk';
// Graph pattern query
const builder = velesql()
.match('d', 'Document')
.nearVector('$queryVector', queryVector)
.andWhere('d.category = $cat', { cat: 'tech' })
.limit(10);
const queryString = builder.toVelesQL();
const params = builder.getParams();
const results = await db.query('documents', queryString, params);
// Graph traversal with relationships
const graphQuery = velesql()
.match('p', 'Person')
.rel('KNOWS')
.to('f', 'Person')
.where('p.age > 25')
.return(['p.name', 'f.name'])
.toVelesQL();
`
`typescript
import { VelesDBError, ValidationError, ConnectionError, NotFoundError } from '@wiscale/velesdb-sdk';
try {
await db.search('nonexistent', query);
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Collection not found');
} else if (error instanceof ValidationError) {
console.log('Invalid input:', error.message);
} else if (error instanceof ConnectionError) {
console.log('Connection failed:', error.message);
}
}
``
1. Use batch operations for multiple inserts
2. Reuse Float32Array for queries when possible
3. Use WASM backend for browser apps (no network latency)
4. Pre-initialize the client at app startup
MIT License - See LICENSE for details.
VelesDB Core is licensed under ELv2 (source available).