DEV Community

Pavel Espitia
Pavel Espitia

Posted on

Keep Your Local RAG Index Fresh Without Re-Embedding Everything

Editing docs/access.md should refresh its vectors without rebuilding the rest of your handbook index. A manifest makes that decision possible by recording the source text's identity and the settings used to produce each indexed record.

For each document, keep a stable document ID, a hash of the extracted text, the embedding model identifier, and a chunker version. On each indexing run, compare the current manifest with the previous one. New or changed content gets embedded again; removed documents are deleted from the vector store; unchanged records are reused only if the model and chunking identity also match.

A runnable delta planner

This Node.js script plans work from two JSON manifests. It does not call Ollama or modify a database. Save as plan-index.mjs and run node plan-index.mjs old.json current.json. Each file is a JSON array with objects shaped like {"id":"docs/access","contentHash":"...","embeddingModel":"nomic-embed-text:v1","chunkerVersion":"md-v2"}. The hash should represent the exact normalized text you embed, not just the file’s timestamp.

// plan-index.mjs
import fs from 'node:fs/promises';

const [oldFile, currentFile] = process.argv.slice(2);
if (!oldFile || !currentFile) {
  throw new Error('Usage: node plan-index.mjs old.json current.json');
}

async function load(file) {
  const rows = JSON.parse(await fs.readFile(file, 'utf8'));
  if (!Array.isArray(rows)) throw new Error(`${file} must contain a JSON array`);
  const map = new Map();
  for (const row of rows) {
    if (![row.id, row.contentHash, row.embeddingModel, row.chunkerVersion]
      .every((value) => typeof value === 'string' && value.length > 0)) {
      throw new Error(`Invalid manifest row in ${file}`);
    }
    if (map.has(row.id)) throw new Error(`Duplicate document ID ${row.id} in ${file}`);
    map.set(row.id, row);
  }
  return map;
}

const previous = await load(oldFile);
const current = await load(currentFile);
const embed = [];
const reuse = [];
const remove = [];

for (const [id, now] of current) {
  const before = previous.get(id);
  if (!before || before.contentHash !== now.contentHash ||
      before.embeddingModel !== now.embeddingModel ||
      before.chunkerVersion !== now.chunkerVersion) {
    embed.push(id);
  } else {
    reuse.push(id);
  }
}
for (const id of previous.keys()) {
  if (!current.has(id)) remove.push(id);
}

console.log(JSON.stringify({ embed, reuse, remove }, null, 2));
Enter fullscreen mode Exit fullscreen mode

Try it with an old row for docs/access, then change contentHash in the current file and add docs/retention. The plan should list both IDs under embed. Remove docs/access from the current manifest and it appears under remove. Change only the model identifier and every current document using the old model becomes eligible for re-embedding.

Which changes invalidate a vector?

Hash extracted, normalized text after deciding how line endings, whitespace, and metadata are handled. If extraction changes but the source bytes do not, the embedding input may still have changed. Conversely, hashing only a file’s modification time can cause unnecessary work when timestamps change without content changes.

An embedding model change requires rebuilding vectors for the affected collection: vectors from different models are not generally interchangeable. Store a pinned revision or full identifier that resolves to the same weights on subsequent runs. Also record vector dimension and distance metric in collection metadata so incompatible records do not silently mix.

A document may have identical text but produce different passages after the splitting rules change. Include a chunker version or a hash of the chunking configuration in the manifest. When that identity changes, reprocess the document's chunks as a unit and replace the old chunk IDs. Otherwise stale chunks can survive beside the refreshed ones.

Deletion and partial failure need a plan

Deletion detection is just as important as additions. If a source disappears and its vectors remain, retrieval can surface material the current corpus no longer contains. Keep a document-to-chunk mapping so removal can delete all records for one source. For larger indexes, apply updates transactionally or write a new generation and swap it in after successful embedding; an interrupted run should not leave half the documents updated.

Inspect the plan before wiring it to database operations. Generate vectors for the embed IDs with Ollama’s embeddings API, which accepts text or batches. The manifest producer can use Node's file-system and crypto APIs to read source text and compute hashes. Save the new manifest only after its corresponding vector-store update succeeds; otherwise the next run may skip work that never completed.

Top comments (1)

Collapse
 
ahmetozel profile image
Ahmet Özel •

Keying reuse on all three fields—contentHash, embeddingModel, and chunkerVersion—prevents the subtle bug where a chunker tweak or model bump leaves stale vectors mixed with freshly embedded documents. Separating the delta planner from database writes also makes dry-run reviews trivial before spending embedding compute.

One small operational guard to add when writing the updated manifest is updating each row atomically only after its vector upsert and stale-chunk deletion succeed. If a run crashes halfway through, a manifest written upfront would trick the next run into skipping documents that never finished indexing.