BM25 vs Semantic Search vs Hybrid RAG: Benchmark Results
I built a RAG system that could search and explain software repositories using BM25, semantic embeddings, reciprocal rank fusion, and cross-encoder reranking.
I expected combining lexical and semantic retrieval to produce better results than using either one independently.
My benchmarks showed something more interesting.
Semantic retrieval alone outperformed my initial hybrid implementation. The hybrid pipeline became the strongest option only after I added cross-encoder reranking.
Here's how I built the system, what I measured, and what the results taught me about retrieval engineering.
1. The Problem: Understanding an Unfamiliar Codebase
When developers work with an unfamiliar repository, finding the right implementation can take longer than understanding the code itself.
A question such as:
How does authentication work in this application?
might require examining several different files:
- API endpoints
- Authentication services
- Dependency injection
- Security utilities
- Token validation
Traditional text search works when you already know which function or variable you're looking for.
But natural-language questions often describe behavior rather than exact identifiers.
For example, a developer might ask:
Where does the application check whether a user is logged in?
The actual implementation might use a function named decode_access_token.
Those are semantically related, but they don't share the same keywords.
I built AI Codebase Intelligence to address this problem.
The system indexes repositories and lets developers ask questions about their code. Instead of sending an entire repository to an LLM, it retrieves the most relevant source-code chunks and uses them to generate an answer with file and line-range citations.
2. The Architecture
The application uses Python and FastAPI for its backend, PostgreSQL for persistence, Redis and Celery for background processing, Pinecone for vector storage, and Ollama for local language-model inference.
The retrieval pipeline follows this structure:
Repository
|
v
Ingestion and Chunking
|
v
Structured Code Metadata
|
+------------------------+
| |
v v
BM25 Retrieval Semantic Embeddings
|
v
Pinecone
| |
+-----------+------------+
|
v
Reciprocal Rank Fusion
|
v
Cross-Encoder Reranking
|
v
Relevant Source Chunks
|
v
Local LLM (Ollama)
|
v
Answer + File Citations
Repository indexing runs asynchronously.
FastAPI creates a background job, Redis handles the Celery task queue, and the worker processes ingestion, chunking, metadata extraction, embeddings, and Pinecone indexing.
This separates longer-running indexing operations from normal API requests.
Once a repository is indexed, the retrieval pipeline can search its source-code chunks without reprocessing the entire repository for every question.
3. BM25: Lexical Retrieval
BM25 is a lexical ranking algorithm based on term matching.
In code retrieval, exact terminology can be particularly important.
Consider this query:
decode_access_token
If that identifier exists in the repository, lexical retrieval can match it directly.
BM25 is useful for searches involving:
- Function names
- Class names
- Variable names
- Technical identifiers
- Exact terminology
However, exact-term retrieval has a limitation.
If a developer describes what a function does rather than naming it, keyword overlap might be weak.
That's where semantic search becomes useful.
4. Semantic Search: Retrieving by Meaning
For semantic retrieval, the system converts code chunks into embeddings and stores them in Pinecone.
When a user submits a question, the system generates a query embedding using the same embedding model and retrieves relevant vectors.
This helps connect natural-language descriptions to source code, even when the wording differs.
For example:
Where does the application check
whether a user is logged in?
The semantic retrieval system can identify authentication-related code without requiring the user to know the function names in advance.
But semantic retrieval also has limitations.
Embeddings may not always preserve the importance of exact identifiers, unusual technical terms, or small differences in syntax.
This motivated the next experiment: combining lexical and semantic retrieval.
5. Combining BM25 and Semantic Search with RRF
BM25 and vector search use different scoring systems.
Their raw similarity scores cannot be combined directly without considering how those scores are distributed.
I used Reciprocal Rank Fusion (RRF) to combine the ranked results.
RRF works with each result's position rather than its original similarity score.
A common formulation is:
[ \operatorname{RRF}(d)=\sum_{r \in R}\frac{1}{k+\operatorname{rank}_r(d)} ]
Where:
dis a retrieved document or code chunk.Ris the collection of ranked result lists.rankis the position of the chunk in a particular list.kis a smoothing constant.
This formula illustrates the general RRF method, not a claim about the exact parameter settings used in my experiment.
The approach makes it possible to combine BM25 and semantic results into one ranking.
However, combining ranked lists does not guarantee better retrieval quality.
And my evaluation exposed exactly that problem.
6. Benchmarking the Retrieval Methods
To compare the approaches, I created a small ground-truth evaluation set.
I measured retrieval performance using two metrics.
Hit@5 measures whether at least one relevant result appears among the first five retrieved items.
MRR@5 (Mean Reciprocal Rank) measures how early the first relevant result appears within the top five results, averaged across evaluation queries.
Higher values are better for both metrics.
Benchmark Results
| Retrieval Method | Hit@5 | MRR@5 |
|---|---|---|
| BM25 | 0.750 | 0.500 |
| Semantic Search | 1.000 | 0.854 |
| Hybrid RRF | 0.875 | 0.692 |
| RRF + Cross-Encoder Reranking | 1.000 | 0.875 |
These are the recorded results from my project's retrieval evaluation, not benchmark scores on a standardized public dataset.
What Stood Out
Semantic retrieval achieved a Hit@5 of 1.000 and MRR@5 of 0.854.
Hybrid RRF reduced those scores to 0.875 and 0.692.
That was an important finding because I had added another retrieval component expecting a stronger result.
Instead, the system became more complex while its measured retrieval quality declined.
Adding more retrieval strategies had not automatically made the system better.
7. Why Didn't Hybrid Retrieval Win?
The initial hybrid system used equal-weight RRF, combining the lexical and semantic ranked lists.
The evaluation showed that this configuration performed worse than semantic search alone.
One plausible explanation is that blending the BM25 ranking into an already strong semantic ranking can move relevant results lower in the final list.
However, the recorded evaluation does not isolate the precise cause of the regression.
Confirming the cause would require further experiments with different fusion settings, query categories, and result-list depths.
The important lesson is that hybrid retrieval needs evaluation and tuning just like any other retrieval method.
It shouldn't be considered better simply because it combines two search approaches.
8. Adding Cross-Encoder Reranking
The next step was to add a cross-encoder reranker after RRF.
Unlike an embedding-based retrieval system that compares separately encoded representations, a cross-encoder evaluates the query and candidate text together.
This allows it to reconsider the relevance of each candidate before the final context is selected.
My pipeline became:
Question
|
v
BM25 + Semantic Search
|
v
RRF Candidate Fusion
|
v
Cross-Encoder Reranker
|
v
Top Code Chunks
|
v
LLM Context
The final results were:
| Metric | Semantic Only | RRF + Reranking |
|---|---|---|
| Hit@5 | 1.000 | 1.000 |
| MRR@5 | 0.854 | 0.875 |
Reranking maintained the perfect Hit@5 recorded by semantic retrieval while improving MRR@5 by 0.021.
In other words, the evaluated relevant results were generally positioned slightly better in the final ranking.
The gain was modest, but measurable.
For this evaluation, it gave me a concrete reason to use the additional reranking stage rather than relying on architectural intuition alone.
9. Turning Retrieval into Grounded Answers
Retrieval quality matters because the LLM's answer depends on which source-code chunks it receives.
In AI Codebase Intelligence, retrieved chunks are passed to a local LLM through Ollama.
The model is instructed to answer using the retrieved context and avoid inventing functions, files, classes, or behavior not supported by the source.
For example, consider:
How does authentication work
in this application?
The system can retrieve relevant code from files such as:
app/api/dependencies.py
app/core/security.py
app/api/auth.py
app/services/auth.py
The generated response includes source metadata, such as:
path: app/core/security.py
start_line: 1
end_line: 57
This lets a developer inspect the underlying implementation rather than relying entirely on the generated explanation.
The citations also make it easier to verify whether the retrieved evidence supports the response.
The system is designed for grounded answers, but the retrieval benchmarks measure ranking quality, not end-to-end answer factuality.
Those are separate evaluation problems.
10. The Backend Engineering Around RAG
Building the retrieval pipeline was only one part of the project.
The application also needed infrastructure for authentication, indexing, persistence, caching, and integration.
Asynchronous Indexing
Repository indexing can involve many expensive operations.
Celery workers handle ingestion, chunking, metadata extraction, embedding generation, and vector indexing.
The API returns a job identifier so clients can monitor indexing progress.
Redis Caching
The system caches repeated RAG requests using Redis.
The cache key incorporates:
repository
query
top_k
An identical request can retrieve a previously generated response without running the complete retrieval and generation pipeline again.
MCP Integration
The application exposes read-only tools through the Model Context Protocol (MCP):
search_code
get_file
list_symbols
ask_codebase
These tools allow compatible AI clients to search repositories, inspect files and symbols, and ask grounded questions.
The MCP interface intentionally avoids arbitrary shell execution and unrestricted file modification.
This matters because a useful RAG product is more than an embedding model connected to an LLM. It also needs appropriate application architecture and access controls.
11. Limitations of the Evaluation
The benchmark results are useful, but they should be interpreted within their scope.
Small evaluation set
The measurements came from a small ground-truth dataset. They are not evidence that this ranking would generalize to all repositories or programming languages.
Limited retrieval metrics
Hit@5 and MRR@5 describe retrieval quality for the tested queries. They do not directly measure generation accuracy, response latency, or user satisfaction.
Fusion parameters
Different retrieval weights, candidate depths, or RRF configurations could produce different results.
Reranking cost
Cross-encoder reranking adds another computation stage. The recorded evaluation does not establish whether the ranking improvement justifies the added latency or resource cost in every deployment.
These limitations are reasons to run more targeted evaluations, not reasons to ignore the existing findings.
12. What I Learned
The main lesson from this project was simple:
Retrieval quality should be measured, not assumed.
I started with the expectation that combining BM25 and semantic search would improve the results.
My own evaluation challenged that expectation.
Semantic retrieval performed better than the initial equal-weight hybrid fusion. Adding cross-encoder reranking then produced the strongest MRR@5 of the tested methods.
The experiment changed how I think about RAG engineering.
Instead of adding components because they sound useful, I want to know what measurable problem each component solves.
That applies to lexical retrieval, embeddings, fusion algorithms, rerankers, and even the LLM itself.
A more complicated architecture is not automatically a better architecture.
The better system is the one whose added complexity is supported by evidence.
Project: AI Codebase Intelligence
Technologies: Python, FastAPI, PostgreSQL, Redis, Celery, Pinecone, BM25, Sentence Transformers, Reciprocal Rank Fusion, Cross-Encoder Reranking, Ollama, Docker, MCP
Author: Borjan Ladinski