The user wants a search platform that uses a hybrid retrieval approach: Artificial Neural Networks (ANN) for semantic/dense retrieval and BM25 for lexical/sparse retrieval, followed by a re-ranking step. This is a common and effective architecture for modern search systems (e.g., Neural IR).
I need to define the components and the workflow.
Data Ingestion: Documents need to be processed.
Text needs to be stored for BM25.
Embeddings need to be generated for ANN.
Indexing:
Sparse Index (Lucene/Elasticsearch/OpenSearch) for BM25.
Dense Index (Vector DB like FAISS, Milvus, Pinecone, Weaviate) for ANN.
Query Processing:
The user query comes in.
It gets processed for BM25 (tokenization).
It gets processed for ANN (embedding generation).
Retrieval (Hybrid):
Retrieve top-k results from the BM25 index.
Retrieve top-k results from the ANN index.
Fusion/Reciprocal Rank Fusion (RRF):
Since the scores from BM25 and ANN are not directly comparable, we need a method to merge the lists. RRF is a standard, robust choice.
Re-ranking:
Take the fused list (usually a bit larger than the final desired output, e.g., top 100) and run a more computationally intensive model (like a Cross-Encoder) to precisely sort the top results.
Framework/Libraries:
Python is the standard language.
sentence-transformers for embeddings (Bi-Encoders for retrieval, Cross-Encoder for re-ranking).
rank_bm25 or pyserini for BM25.
faiss or chromadb for vector search.
numpy for math.
Let's structure the solution as a Python code example using popular, accessible libraries. I will create a class HybridSearchEngine.
__init__: Load models (Bi-Encoder for retrieval, Cross-Encoder for reranking). Initialize FAISS and BM25 holders.
index_documents(documents):
Create BM25 index.
Create Embeddings.
Create FAISS index.
Store mapping from internal IDs to document text.
search(query, k):
BM25 Search: Get top candidates.
ANN Search: Get top candidates.
Hybrid Fusion (RRF): Combine scores. Get top-N (e.g., 20) candidates.
Re-ranking: Use Cross-Encoder to score query vs. candidate text.
Sort and return top-k.
Refining the Hybrid Fusion (RRF):
RRF formula: score(d)=∑r∈Rk+r
Where is a constant (usually 60).
Refining Re-ranking:
The Cross-Encoder takes pairs (query, doc_text) and outputs a score. This is slower but much more accurate than dot product or BM25 alone.
Code Structure:
Setup/Dependencies.
The HybridSearch class.
Example usage with dummy data.
Self-Correction/Constraint Check:
Complexity: FAISS can be tricky to install on some systems. Maybe faiss-cpu is safer for a demo.
BM25:rank_bm25 is pure python, easy to use but slow for huge data. Good for a prototype. pyserini uses Java, which makes the environment setup harder. Stick to rank_bm25.
Embeddings:all-MiniLM-L6-v2 is fast and good enough for a demo.
Reranking:cross-encoder/ms-marco-MiniLM-L-6-v2 is a standard choice.
Let's write the code.
Steps:
Installation command: List pip installs.
Implementation:
Pre-processing (tokenization for BM25).
Embedding generation.
FAISS index building.
Search logic.
RRF implementation.
Re-ranking logic.
Example: Show it running.
Details on Hybrid Search Logic:
Dense search returns IDs and Distances. Convert distances to "ranks" (1st, 2nd, 3rd...).
Sparse search returns IDs and Scores. Convert scores to "ranks".
Merge two ranked lists using RRF.
Take top N (where N>k, e.g., N=50).
Pass these 50 docs + query to Cross-Encoder.
Sort by Cross-Encoder score.
Return top k (e.g., ).
Wait, does FAISS handle ID mapping?
Usually, you add vectors and FAISS assigns an internal sequential ID (0 to N-1). We can use index.add_with_ids if we want specific integer IDs. Or just rely on the fact that index.add uses 0-based indexing. I'll assume documents are a list, so index i in the list corresponds to ID i.
BM25 Tokenization:
Needs simple english tokenization.
Let's draft the response.
This requires building a pipeline that combines Lexical Search (BM25) with Semantic Search (ANN - Approximate Nearest Neighbor) and then uses a Cross-Encoder for re-ranking.
Here is a complete, runnable Python solution using sentence-transformers, rank_bm25, and faiss.
This script defines a HybridSearch class. It indexes documents, performs parallel retrieval, fuses the results using Reciprocal Rank Fusion (RRF), and finally re-ranks the top candidates.
python
How It Works
Indexing:
Lexical: We tokenize the text (split by space) and build an inverted index using rank_bm25.
Semantic: We use a Transformer (multi-qa-MiniLM...) to convert text into vectors (arrays of numbers). We store these in faiss.
Retrieval (The "Hybrid" part):
When a query comes in, we run two searches simultaneously.
BM25 looks for keyword overlaps (e.g., "ranking" matches "ranking").
ANN looks for conceptual similarity (e.g., "energy" is close to "powerhouse").
Fusion (RRF):
We cannot simply add a BM25 score (e.g., 14.5) to a Cosine Similarity score (e.g., 0.82). They are on different scales.
Reciprocal Rank Fusion (RRF) solves this by ignoring the raw score magnitude and looking only at the rank (position in the list).
Formula: Score(d)=∑
an
kr
(
d
)
1
k
k=5
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer, CrossEncoder
import faiss
import time
class HybridSearch:
def __init__(self,
embedding_model_name='multi-qa-MiniLM-L6-cos-v1',
cross_encoder_name='cross-encoder/ms-marco-MiniLM-L-6-v2',
use_gpu=False):
print("Loading models...")
# 1. Bi-Encoder: For fast vector search (ANN)
self.embedding_model = SentenceTransformer(embedding_model_name)
# 2. Cross-Encoder: For precise re-ranking
self.cross_encoder = CrossEncoder(cross_encoder_name)
# Data storage
self.documents = []
self.bm25 = None
self.faiss_index = None
# Dimension of the embedding model
self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension()
def tokenize(self, text):
"""Simple tokenization for BM25."""
return text.lower().split()
def index_documents(self, docs):
"""
Indexes documents for both BM25 (Lexical) and FAISS (Semantic).
"""
print(f"Indexing {len(docs)} documents...")
self.documents = docs
# --- A. BM25 Indexing (Lexical) ---
tokenized_corpus = [self.tokenize(doc) for doc in docs]
self.bm25 = BM25Okapi(tokenized_corpus)
# --- B. FAISS Indexing (Semantic/ANN) ---
# Encode all docs to vectors
embeddings = self.embedding_model.encode(docs, show_progress_bar=True, convert_to_numpy=True)
# Normalize vectors for Cosine Similarity (Inner Product on normalized vectors = Cosine Sim)
faiss.normalize_L2(embeddings)
# Create FAISS index (IndexFlatIP is exact search, but acts as a simple ANN baseline.
# For true ANN at scale, use IndexIVFFlat or HNSW)
self.faiss_index = faiss.IndexFlatIP(self.embedding_dim)
self.faiss_index.add(embeddings)
print("Indexing complete.")
def search(self, query, top_k=5, ann_k=25, rrf_k=60):
"""
Executes the Hybrid Search Pipeline:
1. BM25 Retrieval
2. ANN Retrieval
3. Reciprocal Rank Fusion (RRF)
4. Cross-Encoder Re-ranking
"""
# --- Step 1: Parallel Retrieval ---
# A. BM25 Search
tokenized_query = self.tokenize(query)
bm25_scores = self.bm25.get_scores(tokenized_query)
# Get top indices
bm25_top_indices = np.argsort(bm25_scores)[::-1][:ann_k]
# B. ANN (Vector) Search
query_embedding = self.embedding_model.encode([query])
faiss.normalize_L2(query_embedding)
distances, ann_top_indices = self.faiss_index.search(query_embedding, ann_k)
ann_top_indices = ann_top_indices[0] # Flatten
# --- Step 2: Hybrid Fusion (Reciprocal Rank Fusion) ---
# RRF Formula: score = sum(1 / (k + rank))
rrf_scores = {}
# Process BM25 results
for rank, idx in enumerate(bm25_top_indices):
if idx not in rrf_scores:
rrf_scores[idx] = 0
rrf_scores[idx] += 1 / (rrf_k + rank + 1)
# Process ANN results
for rank, idx in enumerate(ann_top_indices):
if idx not in rrf_scores:
rrf_scores[idx] = 0
rrf_scores[idx] += 1 / (rrf_k + rank + 1)
# Sort by fused score
fused_indices = sorted(rrf_scores.keys(), key=lambda x: rrf_scores[x], reverse=True)
# Select top candidates for re-ranking (usually slightly more than final top_k)
candidates = fused_indices[:top_k * 2]
# --- Step 3: Re-ranking (Cross-Encoder) ---
# Cross-Encoder takes (Query, Document) pairs and scores them precisely
cross_inp = [[query, self.documents[idx]] for idx in candidates]
cross_scores = self.cross_encoder.predict(cross_inp)
# Combine candidates and scores, then sort
results = sorted(zip(candidates, cross_scores), key=lambda x: x[1], reverse=True)
# --- Output Formatting ---
final_results = []
print(f"\n--- Query: '{query}' ---")
for rank, (idx, score) in enumerate(results[:top_k]):
print(f"Rank {rank+1}: [Score: {score:.4f}] \n\tDoc: {self.documents[idx][:100]}...")
final_results.append({
"id": idx,
"score": float(score),
"text": self.documents[idx]
})
return final_results
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# Sample Corpus
documents = [
"The mitochondria is the powerhouse of the cell.",
"Python is a popular programming language for machine learning.",
"Machine learning algorithms find patterns in data.",
"To be or not to be, that is the question.",
"The stock market fluctuates based on supply and demand.",
"Vector databases enable fast semantic search capabilities.",
"BM25 is a ranking function used by search engines to rank matching documents.",
"The capital of France is Paris.",
"Deep learning is a subset of machine learning based on artificial neural networks.",
"Retrieval Augmented Generation (RAG) improves LLM accuracy."
]
# Initialize System
search_engine = HybridSearch()
search_engine.index_documents(documents)
# Queries
queries = [
"How does a cell produce energy?", # Semantic match expected (Mitochondria)
"information retrieval ranking algorithm", # Lexical match expected (BM25)
"AI and neural networks" # Hybrid match (Deep learning / ML)
]
for q in queries:
search_engine.search(q, top_k=3)
k+rank(d)1
This allows documents that appear high in either list to bubble up to the top.
Re-ranking:
We take the top N documents from the fused list.
We feed the raw Query and the Document Text into a Cross-Encoder.
A Cross-Encoder allows full attention mechanism interaction between the query and document, resulting in a much more accurate "relevance score" than the vector similarity alone can provide. This step is computationally expensive, so we only do it for the final few candidates.