AI Hints
Home›RAG Tutorial›Better Retrieval
RAG · Lesson 53 of 120

Keyword Search

BM25.

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

Before embeddings, search engines matched words. The best known method is called BM25. It scores chunks by shared words, and gives rare words more weight than common ones.

Keyword Search
From the video: Keyword Search
  • Match words
  • BM25
  • Rare words count more

How BM25 scores

A word that appears in the chunk adds to the score. Rare words, like E03, add a lot. Common words, like the, add almost nothing. And very long chunks are scored down a little, so they don't win just by being long.

keyvalue
Shared wordsraise the score
Rare wordscount a lot
Common wordscount little
Long chunksscaled down

BM25 in Python

The rank BM25 library does the scoring. Words lowercases text and splits it into words. BM25 okapi takes every chunk's words. Get scores scores the question against all chunks. Run it. The chunk that explains E03 is now first.

bm25.pypython
import re
from rank_bm25 import BM25Okapi
from rag_kit import load_docs, make_chunks

chunks = make_chunks(load_docs())
words = lambda text: re.findall(r"[a-z0-9]+", text.lower())
bm25 = BM25Okapi([words(c["text"]) for c in chunks])

scores = bm25.get_scores(words("What does E03 mean?"))
for i in sorted(range(len(chunks)), key=lambda i: -scores[i])[:3]:
    print(round(scores[i], 1), "|", chunks[i]["text"][:60])
Output
2.4 | E01: the battery is not connected properly. Remove the batte
2.3 | # Warranty  ## Frames All Northwind frames have a lifetime w
2.2 | You can rent bikes from our Leeds and York stores. Harrogate
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
faiss.omp_set_num_threads(1)
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]

Summary

BM25 scores chunks by shared words, weighting rare words most. It finds exact codes that embeddings miss. Next, when keywords win.

Key takeaways
  • BM25Okapi
  • Rare words count
  • Exact matches
Next up: When Keywords Win — codes and names