create() vs use(): Use create() for new files only. Use use() to open existing files. Calling create() on an existing file will overwrite it!Search and Ask
Copy
import { use, create, Memvid } from '@memvid/sdk';
async function searchExample() {
// Open existing memory
const mv: Memvid = await use('basic', 'notes.mv2', { readOnly: true });
// Search with options
const hits = await mv.find('deterministic', { k: 5, snippetChars: 200 });
console.log(`Found ${hits.total_hits} results`);
for (const hit of hits.hits) {
console.log(` ${hit.score.toFixed(2)}: ${hit.title}`);
}
// Ask with LLM synthesis
const answer = await mv.ask('How does the WAL work?', {
model: 'openai:gpt-4o-mini',
modelApiKey: process.env.OPENAI_API_KEY,
k: 10
});
console.log(answer.answer);
// Timeline queries
const timeline = await mv.timeline({
since: 1730000000,
until: 1730003600,
limit: 20
});
console.log(`Timeline entries: ${timeline.length}`);
}
Creating and Ingesting
Copy
import { create, use, Memvid } from '@memvid/sdk';
import { existsSync } from 'fs';
async function ingestExample() {
const path = 'knowledge.mv2';
// IMPORTANT: create() for NEW files, use() for EXISTING files
const mv: Memvid = existsSync(path)
? await use('basic', path) // Open existing
: await create(path, 'basic'); // Create new
// Enable lexical search
await mv.enableLex();
// Add documents with vector compression (for text content)
await mv.put({
title: 'API Documentation',
label: 'docs',
text: 'The API provides endpoints for search and retrieval...',
vectorCompression: true
});
// Add from file
await mv.put({
title: 'User Guide',
label: 'docs',
file: 'guide.pdf',
vectorCompression: true
});
await mv.seal();
}
Verification and Repair
Copy
import { use } from '@memvid/sdk';
async function maintenanceExample() {
// Verify integrity
const result = await use.verify('notes.mv2', { deep: true }) as {
overall_status: string;
checks: unknown[];
};
if (result.overall_status === 'passed') {
console.log('File is valid');
} else {
console.log('Issues found:', result.checks);
}
// Repair if needed
const report = await use.doctor('notes.mv2', {
rebuildTimeIndex: true,
rebuildLexIndex: true,
vacuum: true
});
console.log('Repair complete:', report);
}
Error Handling
Copy
import { use, CapacityExceededError, LockedError } from '@memvid/sdk';
async function errorHandlingExample() {
try {
const mv = await use('basic', 'knowledge.mv2');
await mv.put({
title: 'Large Document',
label: 'docs',
file: 'large-file.pdf',
vectorCompression: true
});
await mv.seal();
} catch (error) {
if (error instanceof CapacityExceededError) {
console.log('MV001: Capacity exceeded - upgrade plan');
} else if (error instanceof LockedError) {
console.log('MV007: File is locked by another process');
} else if (error instanceof Error) {
console.log('Error:', error.message);
}
}
}
Express Server Example
Copy
import express from 'express';
import { open } from '@memvid/sdk';
const app = express();
app.use(express.json());
// Reuse a shared-lock handle for the lifetime of the server.
const mem = await open('knowledge.mv2', 'basic', { readOnly: true });
app.post('/search', async (req, res) => {
const { query, k = 10 } = req.body;
const results = await mem.find(query, { k });
res.json(results);
});
app.post('/ask', async (req, res) => {
const { question } = req.body;
const answer = await mem.ask(question, {
model: 'openai:gpt-4o-mini',
modelApiKey: process.env.OPENAI_API_KEY,
maskPii: true,
});
res.json(answer);
});
app.listen(3000, () => console.log('Server running on port 3000'));
PDF Table Extraction
Copy
import { create, use, Memvid } from '@memvid/sdk';
import { existsSync } from 'fs';
async function tableExample() {
const path = 'invoices.mv2';
const mv: Memvid = existsSync(path)
? await use('basic', path)
: await create(path, 'basic');
await mv.enableLex();
// Extract tables from PDF
const result = await mv.putPdfTables('invoice.pdf', true);
console.log(`Extracted ${result.tables_count} tables`);
// List tables
const tables = await mv.listTables();
for (const table of tables) {
console.log(` ${table.tableId}: ${table.nRows} x ${table.nCols}`);
}
// Get table data
const data = await mv.getTable('pdf_table_1_page1', 'dict') as {
headers?: string[];
rows?: unknown[][];
};
console.log('Headers:', data.headers);
// Export to CSV
const csv = await mv.getTable('pdf_table_1_page1', 'csv');
console.log(csv);
await mv.seal();
}