RAG with FAISS

Build and persist a FAISS index with an ID mapping, and use it for retrieval in a RAG pipeline.

Last Updated:

Module 7 · Lesson 3 of 8 · Intermediate

RAG with FAISS

Build and persist a FAISS index with an ID mapping, and use it for retrieval in a RAG pipeline.

FAISS (Facebook AI Similarity Search) is a fast, free library for vector search that runs inside your Python process. It is a great fit for RAG applications that run on one machine, offline batch jobs and prototypes that need to scale to millions of vectors. Because FAISS stores only vectors and integer IDs, you need to manage the chunk text and metadata yourself. This lesson builds a complete, persistent FAISS-based RAG application that does exactly that.

What you will learn

  • How to build a FAISS index with your own IDs using IndexIDMap
  • How to store chunk text and metadata alongside the index
  • How to save, load, add to and delete from a FAISS index
  • How to answer questions with retrieved chunks

Prerequisites

pip install faiss-cpu numpy sentence-transformers anthropic

The design

  • A FAISS IndexIDMap wrapped around an exact inner-product index (IndexFlatIP), so every vector has an integer ID we choose.
  • A JSON docstore mapping each integer ID to the chunk text and metadata.
  • Both saved side by side on disk, and loaded together.

The complete application

faiss_rag.py
"""RAG with FAISS: persistent index + JSON docstore."""
import json
from pathlib import Path

import faiss
import numpy as np
from rag_helpers import ask, embed

class FaissStore:
    def __init__(self, folder: str = "faiss_store", dim: int = 384):
        self.folder = Path(folder)
        self.index_path = self.folder / "index.faiss"
        self.docs_path = self.folder / "docstore.json"
        if self.index_path.exists():
            self.index = faiss.read_index(str(self.index_path))
            self.docs = {int(k): v for k, v in json.loads(self.docs_path.read_text(encoding="utf-8")).items()}
        else:
            self.index = faiss.IndexIDMap(faiss.IndexFlatIP(dim))    # cosine via normalised vectors
            self.docs = {}
        self.next_id = max(self.docs, default=-1) + 1

    def add(self, texts: list[str], metadatas: list[dict]) -> list[int]:
        vectors = embed(texts).astype("float32")
        ids = np.arange(self.next_id, self.next_id + len(texts), dtype="int64")
        self.index.add_with_ids(vectors, ids)
        for i, text, meta in zip(ids, texts, metadatas):
            self.docs[int(i)] = {"text": text, "metadata": meta}
        self.next_id += len(texts)
        return ids.tolist()

    def delete_source(self, source: str) -> int:
        ids = [i for i, d in self.docs.items() if d["metadata"].get("source") == source]
        if ids:
            self.index.remove_ids(np.array(ids, dtype="int64"))
            for i in ids:
                del self.docs[i]
        return len(ids)

    def search(self, query: str, k: int = 4) -> list[dict]:
        q = embed(query, query=True).astype("float32")
        scores, ids = self.index.search(q, k)
        return [{**self.docs[int(i)], "score": float(s)} for s, i in zip(scores[0], ids[0]) if i != -1]

    def save(self) -> None:
        self.folder.mkdir(exist_ok=True)
        faiss.write_index(self.index, str(self.index_path))
        self.docs_path.write_text(json.dumps(self.docs), encoding="utf-8")


def chunk(text: str, size: int = 800) -> list[str]:
    paragraphs, chunks, current = [p.strip() for p in text.split("\n\n") if p.strip()], [], ""
    for p in paragraphs:
        if current and len(current) + len(p) > size:
            chunks.append(current)
            current = ""
        current = f"{current}\n\n{p}" if current else p
    return chunks + ([current] if current else [])


def index_folder(store: FaissStore, folder: str) -> None:
    for path in sorted(Path(folder).glob("*.txt")):
        source = path.as_posix()
        removed = store.delete_source(source)                   # replace old version
        chunks = chunk(path.read_text(encoding="utf-8"))
        store.add(chunks, [{"source": source, "chunk": i} for i in range(len(chunks))])
        print(f"{source}: {len(chunks)} chunks (replaced {removed})")
    store.save()


def answer(store: FaissStore, question: str) -> str:
    hits = store.search(question)
    sources = "\n\n".join(f'<source id="{n}" file="{h["metadata"]["source"]}">\n{h["text"]}\n</source>'
                          for n, h in enumerate(hits, start=1))
    return ask(f"<sources>\n{sources}\n</sources>\n\nAnswer from the sources only, citing ids "
               f"like [1]. Say so if they do not contain the answer.\n\nQuestion: {question}")


if __name__ == "__main__":
    store = FaissStore()
    index_folder(store, "docs")
    print(f"{store.index.ntotal} vectors in the index")
    print(answer(store, "What is the hotel limit in metro cities?"))
docs/expenses.txt: 1 chunks (replaced 0)
docs/leave-policy.txt: 2 chunks (replaced 0)
docs/remote-work.txt: 1 chunks (replaced 0)
4 vectors in the index
Hotel costs are covered up to 6,000 rupees per night in metro cities [1].

Run it again: each file's old chunks are removed and replaced, so the vector count stays the same.

How the code works

  • IndexIDMap lets us assign our own 64-bit IDs and later remove them with remove_ids. A plain IndexFlatIP would number vectors 0, 1, 2... by position.
  • Inner product on normalised vectors equals cosine similarity; embed() returns normalised vectors.
  • The docstore keeps text and metadata keyed by the same integer IDs; FAISS returns -1 for empty result slots, which we skip.
  • write_index / read_index persist the index; always save and load the docstore together with it.

Scaling up

For more than a few hundred thousand vectors, replace IndexFlatIP with an HNSW or IVF index (Vector Index Types). HNSW indexes in FAISS do not support removing vectors, so for frequent deletes either rebuild periodically or use an IVF index (which supports remove_ids) or a vector database. For filtering by metadata, retrieve extra results and filter in Python, or move to a database with built-in filters.

Common errors and troubleshooting

  • AssertionError on add: vectors must be float32 and a 2-D array of the index's dimension.
  • Wrong results after changing models: delete faiss_store/ and rebuild with the new dimension.
  • Docstore and index out of sync: save both after every change; never edit one alone.
  • GPU: faiss-gpu builds exist for CUDA; on Windows, the CPU package is the simplest option.

Key takeaways

  • FAISS is a fast in-process vector index; you manage text and metadata yourself.
  • Use IndexIDMap for your own IDs and deletions; normalise vectors for cosine similarity.
  • Persist the index and the docstore together; move to HNSW/IVF or a database as you scale.

Frequently asked questions

FAISS or a vector database?

FAISS for single-process apps, batch jobs and research; a database when you need concurrent users, filters, updates and operations features.

Is LangChain's FAISS wrapper the same?

It uses FAISS underneath and adds a docstore for you. This lesson shows what such wrappers do.

Practice exercises

  1. Switch to faiss.IndexHNSWFlat and measure search time on 100,000 random vectors.
  2. Add a source filter by retrieving 20 results and keeping the first 4 that match.

Related tutorials