Updating, Deleting and Re-Indexing Vectors

Keep your vector index in sync with changing source documents.

Last Updated:

Module 6 · Lesson 11 of 13 · Intermediate

Updating, Deleting and Re-Indexing Vectors

Keep your vector index in sync with changing source documents.

Documents change. Policies are revised, pages are deleted and new files arrive daily. If the index does not follow, your RAG system confidently answers from outdated text. This lesson shows how to keep a vector index in sync with its sources: stable IDs, change detection, deleting stale chunks, and safely rebuilding the whole index when needed.

Stable, predictable IDs

Every chunk needs an ID that you can compute again later, so you can find and replace it. A good pattern is {document_id}:{chunk_index}, where the document ID is a stable identifier such as the file path or the URL, not a random UUID. Store the document ID as metadata too, so you can delete all of a document's chunks with one filter.

Change detection with content hashes

Keep a small manifest that maps each document ID to a hash of its content. On every sync run, compare the current hashes with the manifest:

  • New document: index it.
  • Changed hash: delete its old chunks, then index the new version.
  • Missing from the source: delete its chunks.
  • Unchanged: skip.

Deleting old chunks before inserting new ones matters: a revised document may produce fewer chunks than before, and leftover chunks with high indexes would otherwise stay in the index forever.

sync_index.py
import hashlib
import json
from pathlib import Path
import chromadb
from chunkers import recursive_split          # from the chunking module
from rag_helpers import embed

MANIFEST = Path("index_manifest.json")
collection = chromadb.PersistentClient(path="chroma_db").get_or_create_collection("docs")

def file_hash(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()

def index_document(doc_id: str, text: str) -> int:
    chunks = recursive_split(text, 1000)
    collection.upsert(
        ids=[f"{doc_id}:{i}" for i in range(len(chunks))],
        documents=chunks,
        embeddings=embed(chunks).tolist(),
        metadatas=[{"doc_id": doc_id, "chunk_index": i} for i in range(len(chunks))],
    )
    return len(chunks)

def delete_document(doc_id: str) -> None:
    collection.delete(where={"doc_id": doc_id})

def sync(folder: str) -> None:
    old = json.loads(MANIFEST.read_text()) if MANIFEST.exists() else {}
    current = {p.as_posix(): file_hash(p) for p in Path(folder).rglob("*.txt")}

    for doc_id in old.keys() - current.keys():
        delete_document(doc_id)
        print("deleted ", doc_id)

    for doc_id, h in current.items():
        if old.get(doc_id) == h:
            continue                                   # unchanged
        if doc_id in old:
            delete_document(doc_id)                    # remove stale chunks first
        n = index_document(doc_id, Path(doc_id).read_text(encoding="utf-8"))
        print("updated " if doc_id in old else "added   ", doc_id, f"({n} chunks)")

    MANIFEST.write_text(json.dumps(current, indent=2))   # only after all changes succeeded

if __name__ == "__main__":
    sync("docs")

Run this script on a schedule (cron, a CI job, or a task queue), or trigger it from webhooks when your content system reports a change. Combine it with the embedding cache so that unchanged chunks inside a changed document are not re-embedded.

Upsert versus insert

Upsert means "insert, or replace if the ID exists". Always prefer it in sync code: re-running a failed sync then produces the same result instead of duplicates. Chroma, Qdrant, Pinecone, Weaviate and Milvus all support upserts; in PostgreSQL use INSERT ... ON CONFLICT DO UPDATE.

Deletes and index health

Many ANN indexes do not remove deleted vectors immediately; they mark them as deleted and clean up later. Heavy churn can therefore degrade search speed or recall until the database compacts or optimises the index. Check your database's documentation for its vacuum or optimisation process, and monitor recall over time.

Full rebuilds without downtime

Some changes require re-embedding everything: a new embedding model, a new chunking strategy or a schema change. Do not rebuild the live index in place. Use a blue-green switch:

  1. Build a new collection (for example docs_v2) alongside the live one.
  2. Run your evaluation set against both.
  3. Point the application at the new collection, ideally through an alias or a configuration value.
  4. Keep the old collection for a while so you can roll back, then delete it.

Qdrant, Milvus, Elasticsearch and OpenSearch support collection aliases, which make step 3 an atomic switch.

Record versions

Store the embedding model name, chunker version and indexing date in each chunk's metadata. When an answer is questioned later, you can tell exactly how its sources were processed (see Data Freshness, Versioning and Audit Trails).

Key takeaways

  • Use stable chunk IDs (doc_id:index) and store doc_id as metadata.
  • Detect new, changed and deleted documents with content hashes and a manifest.
  • Delete a document's old chunks before indexing its new version; use upserts everywhere.
  • Rebuild for model or chunking changes in a new collection and switch with an alias.