The Simplest Retriever
Matching words.
A retriever takes a question, and returns the most useful text. The simplest one counts shared words. Whichever page shares the most words with the question wins.

- Question in
- Best text out
- Count shared words
Counting shared words
Words turns text into a set of lower case words. For each page, we count how many question words it contains, and sort the pages by that score. Run it. For a question about renting an e-bike, the rentals page scores highest.
import re
from kb import load_docs
def words(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
def retrieve(question, docs, k=2):
q = words(question)
scored = [(len(q & words(d["text"])), d["source"]) for d in docs]
return sorted(scored, reverse=True)[:k]
print(retrieve("How much does it cost to rent an e-bike for a week?", load_docs()))[(8, 'rentals.md'), (7, 'warranty.md')]
Also uses kb.py
from pathlib import Path
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]Good and bad
Word matching is fast, and easy to understand. But it only sees exact words. A question that says charge won't match a page that says charging, unless they share other words. Common words like the, and is, add noise too. We'll fix these problems step by step.
| key | value |
|---|---|
| Good | simple and fast |
| Bad | exact words only |
| Noise | common words count |
| Fix | better retrievers later |
Summary
The simplest retriever ranks pages by shared words. It works sometimes, but it misses meaning. Next, your first complete RAG app.
Key takeaways- Words to sets
- Count the overlap
- Sort and take the top