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
- 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:
- Gives every chunk a stable ID.
- Embeds in batches (embedding APIs accept many texts per request).
- Stores metadata for filtering and citations.
- 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:
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
| Field | Used for |
|---|---|
source, page or url | Citations and “open the original” links |
title, headings | Showing results; adding context to prompts |
doc_id, chunk | Updating and deleting a document's chunks |
updated_at or version | Preferring current documents |
access (groups, tenant) | Filtering what each user may see |
hash | Skipping unchanged chunks |
embedding_model | Knowing 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
Prepare chunks for upserting: give each a stable ID and the metadata you will need later for citations and re-indexing.
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"])
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.