AI Hints
Home›RAG Tutorial›Speed, Cost and Freshness
RAG · Lesson 96 of 120

Keeping the Index Fresh

Re-index what changed.

⏱ 2 min read▶ Video at 1:34:50🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Help pages change every week. Rebuilding the whole index each time is slow and costly. Instead, we fingerprint each file, and re-index only the files whose fingerprint changed.

Keeping the Index Fresh
From the video: Keeping the Index Fresh
  • Pages change
  • Don't rebuild everything
  • Re-index what changed

Finding changed files

A fingerprint is a hash of the file's text. Any change to the text changes the hash. We save the hashes, edit the shipping page, and compare. Run it. Only the shipping page needs re-indexing.

fresh.pypython
import hashlib, shutil
from pathlib import Path

shutil.copytree("data/rag/northwind", "docs")
fingerprint = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
before = {p.name: fingerprint(p) for p in Path("docs").glob("*.md")}

page = Path("docs/shipping.md")
page.write_text(page.read_text().replace("£4.99", "£5.49"))

after = {p.name: fingerprint(p) for p in Path("docs").glob("*.md")}
changed = [name for name in after if before.get(name) != after[name]]
print("changed:", changed)
print("unchanged:", len(after) - len(changed), "files")
Output
changed: ['shipping.md']
unchanged: 13 files

An update job

On a schedule, scan the documents. Hash each file. Compare with the saved hashes. Remove old chunks for changed or deleted files. And add new chunks for changed and new files.

  1. Scan
  2. Hash
  3. Compare
  4. Remove old
  5. Add new
An update job
From the video: An update job

Summary

Fingerprint files with a hash, and re-index only what changed. Next, duplicates and old versions.

Key takeaways
  • Hash each file
  • Compare
  • Re-index changes
Next up: Duplicates and Old Versions — one truth