flowchart TD Q[Query] --> S[Semantic search<br/>cosine similarity] Q --> K[Keyword search<br/>BM25] S --> N[Normalise and<br/>combine] K --> N N --> R[Ranked chunks]
RAG workshop series. I prepared these notebooks for the RAG day of AI Innovation & Product Development, a three-day workshop I ran for final-year B.Tech AI & Data Science students.
- When to use RAG, and when a long context window is enough
- Basic RAG from scratch
- Hybrid search: BM25, embeddings and a reranker
- RAG on real documents: query rewriting, chunking, metadata and Chroma
- Agentic RAG: corrective, adaptive and ReAct
All notebooks: github.com/Zilch123/ai-workshop
In Part 2, plain vector search ranked Lambda above SQS for “Which AWS service can help decouple applications?”. The right chunk only reached the LLM because we sent the top 2.
Embeddings capture meaning, but they’re weak on exact terms: product codes, error codes, acronyms. Keyword search is the opposite. This notebook adds three things:
- BM25, the classic keyword ranking
- Hybrid search, which combines BM25 and vector scores
- Reranking, where a cross-encoder re-scores the top candidates
BM25
BM25 (Best Matching 25) scores a chunk by the query words it contains. It has three parts:
- Term frequency: a word that appears more often counts more, with diminishing returns.
- Inverse document frequency (IDF): rare words count more than common ones.
- Length normalisation: long chunks don’t win just because they have more words.
With the rank_bm25 library it’s a few lines:
from rank_bm25 import BM25Okapi
tokenized_chunks = [chunk.lower().split() for chunk in chunks]
bm25 = BM25Okapi(tokenized_chunks)
scores = bm25.get_scores(question.lower().split())Why BM25 also picked Lambda
On the decouple question, BM25 got it wrong too:
| Chunk | BM25 score |
|---|---|
| Lambda | 1.190 |
| S3 | 0.828 |
| SQS | 0.780 |
| DynamoDB | 0.000 |
Scoring each query word on its own shows why. It’s the tokenizer. .split() splits on spaces only, so punctuation stays attached to words:
- The query word is
applications?, with the question mark. It matches nothing. serviceonly matches S3. In the SQS and Lambda chunks the word isservice., with a full stop.awsonly appears in the Lambda chunk (“AWS Lambda”, “AWS executes”). The other chunks say “Amazon”. So in this tiny corpus “aws” is a rare word, and BM25 rewards rare words.decoupleis the only word pointing at SQS, and it’s worth 0.780.
Stripping punctuation (re.findall(r"\w+", text.lower())) moves SQS up to second and S3 drops to 0.137. Lambda still wins, though, because of “aws”. Neither fix is wrong. BM25 does exactly what it’s told. Tokenization is part of your retrieval quality, and on a small corpus IDF can reward words that carry no meaning.
Hybrid search
The two score types are on different scales (cosine is between −1 and 1, BM25 is unbounded), so we min-max normalise each one to 0–1 and take a weighted sum:
semantic_norm = (semantic - semantic.min()) / (semantic.max() - semantic.min())
bm25_norm = (bm25_scores - bm25_scores.min()) / (bm25_scores.max() - bm25_scores.min())
hybrid = semantic_weight * semantic_norm + keyword_weight * bm25_normWith equal weights, on the AWS question:
| Chunk | Hybrid | Semantic | BM25 |
|---|---|---|---|
| Lambda | 1.000 | 1.000 | 1.000 |
| SQS | 0.543 | 0.431 | 0.655 |
| S3 | 0.460 | 0.225 | 0.695 |
| DynamoDB | 0.000 | 0.000 | 0.000 |
When both methods make the same mistake, combining them doesn’t fix it.
Also notice that min-max always gives the top chunk 1.0 and the bottom one 0.0, however close the raw scores were. On 4 chunks that stretches small differences a lot. Reciprocal rank fusion, which combines ranks instead of raw scores, is a common way to avoid this.
To show hybrid search when it works, we switched to five short incident reports and asked “Why is the application running out of memory?”. Both methods agreed on the upload memory issue (1.000), well ahead of the next one (0.343).
Reranking
Embedding search uses a bi-encoder: the question and each chunk are embedded separately and then compared. That’s fast, because chunk vectors are computed once, ahead of time. But the model never sees the question and the chunk together.
A cross-encoder reads the question and a chunk as one input and outputs a relevance score. It’s much better at judging relevance, but it has to run once per (question, chunk) pair at query time. That’s why you don’t use it to search everything. You use it to re-order the top few candidates from a cheaper search.
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
def rerank(question, results, top_k=2):
scores = reranker.predict([(question, r["text"]) for r in results])
for r, s in zip(results, scores):
r["reranker_score"] = float(s)
return sorted(results, key=lambda r: r["reranker_score"], reverse=True)[:top_k]Hybrid search for the top 4, then rerank to the top 2:
| Chunk | Reranker score |
|---|---|
| SQS | 2.552 |
| Lambda | 2.543 |
SQS is finally first, but only by 0.009. A reranker improves the order, but the scores are close, and on a corpus this small and this similar, nothing separates the two cleanly. The fix for that is better data, not another model.
Some rerankers you’ll see in production:
| Reranker | Type | Typical use |
|---|---|---|
| Cohere Rerank | Hosted API | Teams that want managed infrastructure |
| BGE Reranker | Open weights | Self-hosted RAG, a popular open-source choice |
| Jina Reranker | Hosted and open | Multilingual or document-heavy workloads |
| Voyage Rerank | Hosted API | High-quality managed retrieval |
| Qwen Reranker | Open weights | Larger models when quality matters most |
A small LLM can also be used as a reranker, if you can afford the extra latency and cost.
What’s next
So far we’ve improved the search itself. Part 4 works on what goes in and out of it: rewriting the query, chunking real documents properly, filtering by metadata, and keeping vectors in a database so they survive a restart.
Notebook: hybrid_search_RAG.ipynb · Open in Colab