Velamuvi AIAcademy

Lesson 7 of 16 · Ingestion

Embedding and Indexing

Build a RAG index: embed chunks in batches, give them stable IDs and metadata, update only changed content with hashes and delete removed chunks.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Embed chunks in batches and store them with useful metadata
  • Give chunks stable IDs so re-indexing never creates duplicates
  • Update only changed chunks using content hashes, and delete removed ones
  • Plan for changing the embedding model

From chunks to an index

The first time, indexing is simple: embed everything and upsert it. The hard part comes later, when documents change every day. A good indexing step:

  1. Gives every chunk a stable ID.
  2. Embeds in batches (embedding APIs accept many texts per request).
  3. Stores metadata for filtering and citations.
  4. Re-embeds only changed chunks and deletes chunks that no longer exist.

Stable IDs and content hashes

If chunk IDs are random, every re-index adds a second copy of every chunk. Build IDs from the document and the chunk's position instead, like handbook.pdf:12. Then an upsert with the same ID replaces the old version.

Here's a nightly sync that uses both ideas:

Try it yourselfPython
import hashlib

def fingerprint(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]   # short content hash

def chunks_of(doc_id, text):
    """Stable IDs: the same document and position always give the same ID."""
    parts = [p.strip() for p in text.split("\n") if p.strip()]
    return {f"{doc_id}:{i}": part for i, part in enumerate(parts)}

# What the vector database holds after last night's sync: chunk ID -> content hash
stored = {
    "leave:0": fingerprint("Employees get 25 days of paid annual leave."),
    "leave:1": fingerprint("Up to 5 unused days can be carried over."),
    "leave:2": fingerprint("Holiday requests need two weeks' notice."),
    "travel:0": fingerprint("Book work trips in the travel portal."),
}

# Today's version of the documents ("leave" changed; "travel" did not)
documents = {
    "leave": "Employees get 25 days of paid annual leave.\nUp to 8 unused days can be carried over.",
    "travel": "Book work trips in the travel portal.",
}

current = {}
for doc_id, text in documents.items():
    current.update(chunks_of(doc_id, text))

to_embed = [cid for cid, text in current.items() if stored.get(cid) != fingerprint(text)]
unchanged = [cid for cid, text in current.items() if stored.get(cid) == fingerprint(text)]
to_delete = [cid for cid in stored if cid not in current]

print("Embed and upsert:", to_embed)
print("Skip (unchanged):", unchanged)
print("Delete:", to_delete)

Only one chunk needed embedding; two were skipped; one stale chunk is deleted so the old “5 days” rule can never be retrieved again. On a large knowledge base, this turns hours of re-embedding into seconds.

Metadata worth storing

FieldUsed for
source, page or urlCitations and “open the original” links
title, headingsShowing results; adding context to prompts
doc_id, chunkUpdating and deleting a document's chunks
updated_at or versionPreferring current documents
access (groups, tenant)Filtering what each user may see
hashSkipping unchanged chunks
embedding_modelKnowing which vectors can be compared

Embedding in batches

Embedding APIs accept a list of texts per request, so send chunks in batches of, say, 100, as in the Vector Databases course. With an OpenAI-style embeddings API, one batch looks like this:

def embed_batch(texts):
    response = client.embeddings.create(model="EMBEDDING_MODEL", input=texts)
    return [item.embedding for item in response.data]

Embedding models have an input limit (often a few thousand tokens), so very long chunks may be cut off or rejected. Keep chunks well under it.

Common mistakes

Practice exercise

Prepare chunks for upserting: give each a stable ID and the metadata you will need later for citations and re-indexing.

Your solutionPython
source = "handbook.pdf"
model = "embed-model-v2"
chunks = ["Employees get 25 days of paid annual leave.",
          "Up to 5 unused days can be carried over.",
          "Book work trips in the travel portal."]

records = []
# For each chunk, add a record like:
# {"id": "handbook.pdf:0", "text": ..., "metadata": {"source": ..., "chunk": 0, "model": ...}}

for r in records:
    print(r["id"], r["metadata"])
Knowledge check

Why do RAG pipelines store a content hash with each chunk?

Summary

  • Indexing embeds chunks and stores vectors with their text and metadata.
  • Use stable chunk IDs and upserts, so re-indexing replaces instead of duplicating.
  • Content hashes show what changed; re-embed only those chunks and delete removed ones.
  • Store source, position, dates, access and the embedding model, and embed in batches.

Next: retrieval techniques beyond plain top-k.

Finished reading? Tick it off to track your progress.