FAISS
Fast search.
FAISS is a library from Meta for searching vectors very fast. It handles millions of vectors on one computer, and it's free. Lots of RAG systems use it directly, or inside other tools.

- From Meta
- Millions of vectors
- Free and fast
Searching with FAISS
Index flat IP compares the question with every vector using the dot product, which is cosine similarity for our normalised vectors. Add puts all the chunk vectors in. Search returns the scores and positions of the best matches. Run it. The top result is the rentals page.
from rag_kit import load_docs, make_chunks, embed
import faiss
chunks = make_chunks(load_docs())
vectors = embed([c["text"] for c in chunks])
index = faiss.IndexFlatIP(vectors.shape[1])
index.add(vectors)
scores, ids = index.search(embed(["How much does it cost to rent an e-bike for a week?"]), 3)
for s, i in zip(scores[0], ids[0]):
print(round(float(s), 2), chunks[i]["source"], "|", chunks[i]["text"][:50])0.69 rentals.md | You can rent bikes from our Leeds and York stores. 0.67 servicing.md | ## Service plans The Basic service costs £49 and i 0.54 finance.md | You can spread the cost of any bike over £400 with
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]FAISS basics
FAISS only stores vectors, and returns positions. We keep the chunks in a list, and look them up by position. Flat indexes are exact. Other index types trade a little accuracy for big speed ups, which we'll see soon.
| key | value |
|---|---|
| Stores | vectors only |
| Returns | scores + positions |
| Flat | exact search |
| Others | faster, approximate |
Summary
FAISS searches vectors fast. Add vectors, search with a question vector, and look up chunks by position. Next, saving an index.
Key takeaways- IndexFlatIP
- index.add
- index.search