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

When Keywords Win

Codes and names.

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

Keyword search and embeddings each have strengths. Let's put them side by side on three questions, and see which one wins where.

When Keywords Win
From the video: When Keywords Win
  • Two methods
  • Three questions
  • Who wins where

Side by side

Our keyword class wraps BM25, with the same search method as our index. For each question we print the top source from both. Run it. Keywords win on the code and the scheme name. Embeddings win on the question with no shared words.

side_by_side.pypython
from rag_kit import load_docs, make_chunks, Index
from keyword_search import Keyword

chunks = make_chunks(load_docs())
dense, sparse = Index(chunks), Keyword(chunks)

for q in ["What does E03 mean?", "What is the APR?",
          "How long until my money comes back?"]:
    print(q)
    print("  meaning: ", dense.search(q, 1)[0][1]["text"][:45])
    print("  keywords:", sparse.search(q, 1)[0][1]["text"][:45])
Output
What does E03 mean?
  meaning:  # E-bike display error codes  These codes app
  keywords: E01: the battery is not connected properly. R
What is the APR?
  meaning:  # Paying monthly
  keywords: You can spread the cost of any bike over £400
How long until my money comes back?
  meaning:  ## Refund timing Refunds go back to the origi
  keywords: E09: the brake sensor is stuck on. Squeeze bo
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]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()
Also uses keyword_search.py
import re
from rank_bm25 import BM25Okapi

def words(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class Keyword:
    def __init__(self, chunks):
        self.chunks = chunks
        self.bm25 = BM25Okapi([words(c["text"]) for c in chunks])

    def search(self, query, k=3):
        scores = self.bm25.get_scores(words(query))
        top = sorted(range(len(scores)), key=lambda i: -scores[i])[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses hybrid.py
from rag_kit import Index
from keyword_search import Keyword
from sentence_transformers import CrossEncoder

def rrf(*ranked_lists, k=60):
    scores, chunks = {}, {}
    for ranked in ranked_lists:
        for rank, chunk in enumerate(ranked):
            key = chunk["text"]
            scores[key] = scores.get(key, 0) + 1 / (k + rank + 1)
            chunks[key] = chunk
    return [chunks[t] for t in sorted(scores, key=lambda t: -scores[t])]

class Hybrid:
    def __init__(self, chunks):
        self.dense, self.sparse = Index(chunks), Keyword(chunks)

    def search(self, query, k=5):
        a = [c for _, c in self.dense.search(query, k=10)]
        b = [c for _, c in self.sparse.search(query, k=10)]
        return rrf(a, b)[:k]

reranker = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device="cpu")

def rerank(query, chunks, k=3):
    scores = reranker.predict([(query, c["text"]) for c in chunks])
    order = sorted(range(len(chunks)), key=lambda i: -scores[i])[:k]
    return [chunks[i] for i in order]

Two strengths

Keywords are great for exact codes, product names, and rare terms. Embeddings are great for meaning, when the customer uses different words. Real questions need both.

Keywords win

  • Error codesProduct namesRare terms

Embeddings win

  • Different wordsParaphrasesVague phrasing

Summary

Keywords win on codes and names. Embeddings win on meaning. Next, combining them with hybrid search.

Key takeaways
  • Codes: keywords
  • Meaning: embeddings
  • Use both
Next up: Hybrid Search — meaning plus keywords