Advanced Vector Databases and Semantic Search with ChromaDB, BM25, MMR and Hybrid Retrieval | AI Engineering Series #4

Welcome to Part 4 of the AI Engineering Series.

In the previous article, we built a Conversational RAG Document Assistant using LangChain, LangGraph, Gemini, PostgreSQL and ChromaDB.

Our AI assistant can already upload PDF documents, generate embeddings, store vectors, retrieve relevant information and answer questions using conversation history.

However, retrieving documents based only on vector similarity may not always provide the most relevant information.

In this article, we will improve our existing RAG application by implementing advanced retrieval techniques, including semantic search, metadata filtering, MMR, BM25, hybrid search and Reciprocal Rank Fusion.

1. What Is a Vector Database?

A vector database stores numerical representations of data called embeddings.

Embeddings represent the semantic meaning of text, images or other information.

For example:

  • Employee leave policy
  • Annual vacation benefits
  • Paid time off

Although these sentences use different words, they have related meanings.

An embedding model converts them into numerical vectors, allowing a vector database to identify related information.

Popular vector databases include:

  • ChromaDB
  • Pinecone
  • Qdrant
  • Weaviate
  • Milvus
  • PostgreSQL with pgvector

We will continue using ChromaDB from our previous implementation.

2. What Is Semantic Search?

Traditional keyword search retrieves information based on matching words.

Semantic search retrieves information based on meaning.

For example, consider the following document content:

Full-time employees receive 24 working days of annual leave per calendar year.

A user asks:

How much vacation time do employees receive?

Even though the words are different, semantic search can identify the relevant document.

This is one of the important capabilities behind modern RAG applications.

3. What Are We Building?

We will extend our existing AI Smart Assistant with the following capabilities:

  • Semantic search with distance scores
  • Metadata filtering
  • Distance threshold filtering
  • Maximum Marginal Relevance (MMR)
  • BM25 keyword search
  • Hybrid search
  • Reciprocal Rank Fusion (RRF)
  • Configurable retrieval strategies
  • Advanced document search API
  • Conversational RAG integration

Our objective is to improve retrieval quality before sending document context to the LLM.

4. Technologies Used

Technology Purpose
Python Backend development
FastAPI REST API development
LangChain AI application development
LangGraph AI workflow orchestration
Gemini Text generation
Gemini Embeddings Text-to-vector conversion
ChromaDB Persistent vector storage
PostgreSQL Conversation memory
BM25 Keyword-based retrieval
RRF Combining retrieval rankings
NumPy Numerical operations

5. Understanding the Architecture

User Question | v Conversational Query Rewriting | v Advanced Retrieval Engine | +-----------------------+ | | v v Semantic Search Keyword Search Gemini + ChromaDB BM25 | | +-----------+-----------+ | v Reciprocal Rank Fusion | v Top Relevant Chunks | v Gemini LLM | v Answer with Sources 

PostgreSQL continues to manage conversation memory.

ChromaDB stores document embeddings, while BM25 retrieves documents using keyword matching.

Our hybrid retrieval engine combines the results from both search techniques.

6. Install Required Dependencies

Activate the existing Python virtual environment.

venv\Scripts\activate 

Install the additional dependencies:

pip install rank-bm25 numpy 

Verify the installation:

python -c "from rank_bm25 import BM25Okapi; import numpy; print('Dependencies installed successfully')" 

We already installed ChromaDB, LangChain and Gemini dependencies in the previous articles.

7. Verify Existing Vector Storage

In Part 3, we uploaded two sample PDF documents:

  • Employee Leave Policy
  • Enterprise Policy

The documents were divided into smaller chunks and stored in ChromaDB.

Verify the existing document chunks:

python -c "from app.vector_store import vector_store; print('Total chunks:', len(vector_store.get()['ids']))" 

Output from our sample implementation:

Total chunks: 6 

Because ChromaDB uses persistent storage, we do not need to upload the documents again unless the collection is missing or empty.

8. Configure Retrieval Settings

File: .env

Action: Add the following configuration to the existing environment file.

RETRIEVAL_STRATEGY=hybrid RETRIEVAL_TOP_K=3 RETRIEVAL_FETCH_K=10 RETRIEVAL_MAX_DISTANCE= MMR_LAMBDA=0.5 RRF_K=60 

Understanding the configuration:

Setting Description
RETRIEVAL_STRATEGY Default search technique
RETRIEVAL_TOP_K Number of final results
RETRIEVAL_FETCH_K Number of candidate results
RETRIEVAL_MAX_DISTANCE Optional maximum vector distance
MMR_LAMBDA Balance between relevance and diversity
RRF_K Rank fusion constant

We will use hybrid search as our default retrieval strategy.

9. Understanding Vector Similarity and Distance

Vector databases use mathematical techniques to compare embeddings.

Common techniques include:

Cosine similarity

Measures the similarity between vector directions.

Euclidean distance

Measures the distance between two vectors.

Dot product

Measures vector alignment and magnitude.

ChromaDB uses squared Euclidean distance by default unless another distance metric is configured when creating the collection.

For distance-based retrieval:

  • Lower distance generally means a closer vector match.
  • Higher distance generally means a less similar vector.

A distance score is not an accuracy percentage or a probability.

10. Implement Semantic Search with Scores

Our previous implementation retrieved documents without returning their distance scores.

Let's improve it.

File: app/retriever.py

Action: Keep the existing code and append the following function.

def search_with_scores( question: str, k: int = 3 ): results = vector_store.similarity_search_with_score( query=question, k=k ) return [ { "content": doc.page_content, "file_name": doc.metadata.get("source"), "page_number": doc.metadata.get("page_number"), "distance": float(score) } for doc, score in results ] 

The function returns the document content, source filename, page number and vector distance.

11. Test Semantic Search

Execute the following command:

python -c "from app.retriever import search_with_scores; import json; print(json.dumps(search_with_scores('How many annual leaves do employees get?'), indent=2))" 

The actual distance scores returned during our implementation were:

Rank Retrieved information Page Distance
1 Annual, sick and casual leave 1 0.6084
2 Unpaid leave and exceptions 2 0.6366
3 Approval process and special leave 2 0.6562

The first document chunk contains the correct answer:

Full-time employees receive 24 working days of annual leave per calendar year.

Although the other chunks belong to the same document, they are less relevant to the specific question.

This demonstrates why retrieval quality matters in RAG applications.

12. Implement Metadata Filtering

Metadata filtering allows us to restrict document retrieval based on specific attributes.

For example:

  • Filename
  • Document ID
  • Page number
  • Document category

In Part 3, we stored metadata alongside each document chunk.

File: app/retriever.py

Action: Append the following function.

def search_by_metadata( question: str, file_name: str, k: int = 3 ): return vector_store.similarity_search( query=question, k=k, filter={ "source": file_name } ) 

Test the implementation:

python -c "from app.retriever import search_by_metadata; print(search_by_metadata('What is the notice period?', 'sample_enterprise_policy.pdf'))" 

The search will retrieve chunks only from sample_enterprise_policy.pdf.

Metadata filtering is especially useful when enterprise applications contain multiple documents.

13. Implement Distance Threshold Filtering

Sometimes a vector database returns documents even when they are not sufficiently relevant.

Distance threshold filtering helps remove distant matches.

File: app/retriever.py

Action: Append the following function.

def search_with_threshold( question: str, max_distance: float, k: int = 3 ): results = vector_store.similarity_search_with_score( query=question, k=k ) return [ doc for doc, distance in results if distance <= max_distance ] 

Test the implementation:

python -c "from app.retriever import search_with_threshold; print(search_with_threshold('How many annual leaves do employees get?', 0.62))" 

Based on our earlier search results:

Document chunk Distance Result
Annual leave 0.6084 Accepted
Unpaid leave 0.6366 Rejected
Special leave 0.6562 Rejected

The threshold of 0.62 is an experimental value for this particular question.

Distance thresholds should be evaluated using multiple queries before applying them globally.

14. Understanding Maximum Marginal Relevance (MMR)

Maximum Marginal Relevance is a retrieval technique that balances relevance and diversity.

Traditional similarity search may return multiple chunks containing similar information.

MMR attempts to retrieve relevant chunks while reducing redundancy.

For example, when a user asks:

Explain employee leave benefits.

Normal similarity search might return:

Annual leave information Annual leave rules Annual leave approval 

MMR may retrieve a more diverse set:

Annual leave information Sick leave information Special leave information 

These are illustrative examples. Actual results depend on the available document chunks and embeddings.

15. Implement MMR Search

File: app/retriever.py

Action: Add the following import.

import os 

Append the following function:

def search_with_mmr( question: str, k: int = 3 ): return vector_store.max_marginal_relevance_search( query=question, k=k, fetch_k=max( k, int(os.getenv("RETRIEVAL_FETCH_K", "10")) ), lambda_mult=float( os.getenv("MMR_LAMBDA", "0.5") ) ) 

Understanding the lambda value:

Lambda Behaviour
0.0 Prioritizes diversity
0.5 Balances relevance and diversity
1.0 Prioritizes relevance

Test MMR search:

python -c "from app.retriever import search_with_mmr; print(search_with_mmr('Explain employee leave benefits'))" 

MMR is useful when we want broader document coverage and less repetitive context.

16. What Is BM25 Keyword Search?

BM25 stands for Best Matching 25.

It is a ranking algorithm commonly used in information retrieval systems.

BM25 considers factors such as:

  • Term frequency
  • Inverse document frequency
  • Document length
  • Query term matching

Semantic search is effective for understanding meaning, but keyword search can be particularly useful for exact terms such as:

HR-001 Employee ID Policy reference number Medical certificate SMTP configuration 

Combining keyword search with semantic search allows us to benefit from both techniques.

17. Implement BM25 Keyword Search

File: app/keyword_search.py

Action: Create a new file and add the following code.

import re from rank_bm25 import BM25Okapi from langchain_core.documents import Document from app.vector_store import vector_store def tokenize(text: str): return re.findall( r"\b\w+\b", text.lower() ) def keyword_search( question: str, k: int = 3, metadata_filter: dict | None = None ): filters = {} if metadata_filter: filters["where"] = metadata_filter data = vector_store.get( include=["documents", "metadatas"], **filters ) documents = [ Document( page_content=content, metadata=metadata or {}, id=doc_id ) for doc_id, content, metadata in zip( data["ids"], data["documents"], data["metadatas"] ) if content and tokenize(content) ] if not documents: return [] tokenized_documents = [ tokenize(doc.page_content) for doc in documents ] bm25 = BM25Okapi(tokenized_documents) query_tokens = tokenize(question) if not query_tokens: return [] scores = bm25.get_scores(query_tokens) query_terms = set(query_tokens) ranked_indices = sorted( ( i for i, tokens in enumerate( tokenized_documents ) if query_terms.intersection(tokens) ), key=lambda i: scores[i], reverse=True )[:k] return [ documents[index] for index in ranked_indices ] 

Here, we retrieve existing document content from ChromaDB, tokenize the text, calculate BM25 scores and return ranked document chunks.

We do not need another database for this implementation.

18. Test BM25 Keyword Search

Search using a policy reference number:

python -c "from app.keyword_search import keyword_search; print(keyword_search('HR-001'))" 

Search using specific keywords:

python -c "from app.keyword_search import keyword_search; print(keyword_search('medical certificate'))" 

The expected relevant information is:

A medical certificate is required for 3 or more consecutive working days of sick leave.

BM25 helps retrieve information based on matching terms rather than embedding similarity.

19. Understanding Hybrid Search and RRF

Hybrid search combines semantic search and keyword search.

Semantic Search + BM25 Keyword Search = Hybrid Search 

However, semantic distance scores and BM25 scores use different scales.

Instead of directly combining their scores, we can combine their ranking positions using Reciprocal Rank Fusion.

The RRF formula is:

RRF Score = Sum of 1 / (K + Rank) 

Where:

  • K is a ranking constant.
  • Rank is the position of a document in a retrieval result.
  • Higher RRF scores indicate higher combined rankings.

For example, using K = 60:

Chunk Semantic rank BM25 rank RRF score
A 1 3 0.03227
B 2 1 0.03252
C 3 2 0.03200

Chunk B receives the highest combined ranking.

RRF allows us to combine different retrieval techniques without directly comparing their original score scales.

20. Implement Hybrid Search

File: app/hybrid_search.py

Action: Create a new file.

import os from app.vector_store import vector_store from app.keyword_search import keyword_search def get_document_key(document): return ( document.metadata["document_id"], document.metadata["chunk_id"] ) def hybrid_search( question: str, k: int = 3, metadata_filter: dict | None = None ): fetch_k = max( k, int(os.getenv("RETRIEVAL_FETCH_K", "10")) ) rrf_k = int(os.getenv("RRF_K", "60")) semantic_results = vector_store.similarity_search( query=question, k=fetch_k, filter=metadata_filter ) keyword_results = keyword_search( question=question, k=fetch_k, metadata_filter=metadata_filter ) scores = {} documents = {} for results in [ semantic_results, keyword_results ]: for rank, document in enumerate( results, start=1 ): key = get_document_key(document) documents[key] = document scores[key] = scores.get( key, 0.0 ) + 1 / (rrf_k + rank) ranked_keys = sorted( scores, key=scores.get, reverse=True ) return [ documents[key] for key in ranked_keys[:k] ] 

The hybrid search implementation performs the following operations:

  1. Retrieves semantic search results.
  2. Retrieves BM25 keyword search results.
  3. Identifies duplicate document chunks.
  4. Calculates RRF scores.
  5. Sorts the combined results.
  6. Returns the top-ranked chunks.

Test the implementation:

python -c "from app.hybrid_search import hybrid_search; docs=hybrid_search('HR-001 medical certificate requirements'); print('\n\n'.join(doc.page_content for doc in docs))" 

21. Integrate All Retrieval Strategies

Instead of calling separate retrieval functions throughout the application, we will create a common retrieval interface.

File: app/retriever.py

Action: Add the following imports and replace the existing retrieve_documents() function. Keep the diagnostic search functions created earlier.

import os from app.vector_store import vector_store from app.keyword_search import keyword_search from app.hybrid_search import hybrid_search def retrieve_documents( question: str, k: int | None = None, strategy: str | None = None, file_name: str | None = None ): k = k if k is not None else int( os.getenv("RETRIEVAL_TOP_K", "3") ) strategy = strategy or os.getenv( "RETRIEVAL_STRATEGY", "hybrid" ) metadata_filter = ( {"source": file_name} if file_name else None ) if strategy == "hybrid": return hybrid_search( question, k=k, metadata_filter=metadata_filter ) if strategy == "keyword": return keyword_search( question, k=k, metadata_filter=metadata_filter ) if strategy == "mmr": return vector_store.max_marginal_relevance_search( query=question, k=k, fetch_k=max( k, int(os.getenv( "RETRIEVAL_FETCH_K", "10" )) ), lambda_mult=float( os.getenv("MMR_LAMBDA", "0.5") ), filter=metadata_filter ) if strategy == "semantic": results = ( vector_store.similarity_search_with_score( query=question, k=k, filter=metadata_filter ) ) threshold = os.getenv( "RETRIEVAL_MAX_DISTANCE", "" ).strip() return [ doc for doc, distance in results if not threshold or distance <= float(threshold) ] raise ValueError( f"Unsupported retrieval strategy: {strategy}" ) 

Our application now supports four retrieval strategies through a single function.

The optional distance threshold currently applies only to the semantic retrieval strategy.

22. Create Document Search API Schemas

We will expose our retrieval engine through a dedicated REST API.

File: app/schemas.py

Action: Add the following import and classes. Keep the existing chat request and response schemas unchanged.

from typing import Literal from pydantic import BaseModel, Field class DocumentSearchRequest(BaseModel): question: str = Field( min_length=1, max_length=5000 ) strategy: Literal[ "semantic", "keyword", "mmr", "hybrid" ] = "hybrid" k: int = Field( default=3, ge=1, le=20 ) file_name: str | None = None class DocumentSearchResponse(BaseModel): question: str strategy: str total_results: int results: list[dict] 

These schemas allow users to select a retrieval strategy, specify the number of results and optionally filter by filename.

Important: Add these classes to schemas.py, not state.py. The LangGraph state definition remains unchanged.

23. Create the Advanced Document Search API

File: app/main.py

Action: Add the following imports.

from app.retriever import retrieve_documents from app.schemas import ( DocumentSearchRequest, DocumentSearchResponse ) 

Append the following endpoint:

@app.post( "/documents/search", response_model=DocumentSearchResponse ) def search_documents( request: Doc...
Source:https://dev.to/jayakrishna_chadalawada/advanced-vector-databases-and-semantic-search-with-chromadb-bm25-mmr-and-hybrid-retrieval-ai-5ih