AI Hints
Home›RAG Tutorial›Working with Indexes
RAG · Lesson 34 of 120

Saving an Index

Build once, load later.

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

Embedding thousands of chunks takes time, and API embeddings cost money. So we build the index once, save it to disk, and load it whenever the app starts.

Saving an Index
From the video: Saving an Index
  • Embedding takes time
  • Build once
  • Load at start

Save, then load

We build a FAISS index, and save it with write index. The chunks go into a JSON file, because FAISS only keeps vectors. Later, read index and JSON load bring both back, without embedding the chunks again. Run it. The loaded index finds the right chunk.

save_index.pypython
import json
from rag_kit import load_docs, make_chunks, embed
import faiss

chunks = make_chunks(load_docs())
index = faiss.IndexFlatIP(384)
index.add(embed([c["text"] for c in chunks]))
faiss.write_index(index, "help.faiss")
json.dump(chunks, open("help_chunks.json", "w"))

loaded = faiss.read_index("help.faiss")
saved_chunks = json.load(open("help_chunks.json"))
scores, ids = loaded.search(embed(["Do you deliver bikes to France?"]), 1)
print(loaded.ntotal, "vectors loaded")
print(saved_chunks[ids[0][0]]["text"])
Output
44 vectors loaded
## International delivery We ship parts and accessories to Ireland, France and Germany
in 5 to 9 working days for £12. We do not ship complete bikes outside the UK.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

What to save

Save the vectors, the chunk text, the metadata, and the name of the embedding model. If you change the model or the chunking, rebuild the index, because old vectors won't match new questions.

keyvalue
Vectorsfaiss file
ChunksJSON
Model namewrite it down
Changed modelrebuild

Summary

Build the index once, save the vectors and chunks, and load them at start up. Next, filtering by metadata.

Key takeaways
  • write_index
  • read_index
  • Chunks in JSON
Next up: Metadata Filters — search only what matches