codeWithYoha logo
Code with Yoha
HomeArticlesAboutContactSupport ☕
Vector Embeddings

Scaling Vector Search: Chunking, Reranking, and Hybrid Retrieval for RAG

CodeWithYoha
CodeWithYoha
18 min read
Scaling Vector Search: Chunking, Reranking, and Hybrid Retrieval for RAG

Introduction: The Imperative of Scalable Retrieval for LLMs

The advent of Large Language Models (LLMs) has revolutionized how we interact with information, enabling sophisticated applications from intelligent chatbots to automated content generation. However, a fundamental limitation of these models is their knowledge cutoff and occasional propensity to "hallucinate" information not present in their training data. This is where Retrieval Augmented Generation (RAG) steps in.

RAG systems enhance LLMs by providing them with relevant external knowledge at inference time. At the heart of most RAG architectures lies vector search, a powerful technique that transforms textual data into numerical representations (vector embeddings) and allows for semantic similarity comparisons. While conceptually elegant, deploying vector search at scale – across vast, dynamic datasets – introduces significant challenges. Simply generating embeddings and throwing them into a vector database is often insufficient for achieving high-precision, low-latency, and cost-effective retrieval.

This comprehensive guide delves into three critical techniques that elevate vector search from a basic concept to a production-ready solution for enterprise-grade RAG systems: intelligent chunking strategies, sophisticated reranking models, and robust hybrid retrieval combining vector search with traditional keyword-based methods like BM25. By mastering these components, developers can unlock the full potential of LLMs, delivering more accurate, contextually relevant, and reliable responses.

The Foundation: Understanding Vector Embeddings in RAG

Vector embeddings are dense numerical representations of text (words, sentences, paragraphs, or entire documents) in a high-dimensional space. Models like OpenAI's text-embedding-ada-002, Google's PaLM, or open-source alternatives like BGE (BAAI General Embedding) are trained to map semantically similar pieces of text to vectors that are close to each other in this space. This proximity allows for efficient semantic search: given a query, we find its embedding and then locate document embeddings that are geometrically closest.

In a RAG pipeline, documents are first broken down into smaller, manageable units (chunks), each of which is then converted into a vector embedding. These embeddings are stored in a vector database (e.g., Pinecone, Chroma, Weaviate, Milvus). When a user poses a query, the query is also embedded, and the vector database returns the top-k most similar document chunks. These chunks are then passed to the LLM as context to formulate a grounded response.

The Challenge of Scale: Why Basic Vector Search Falls Short

While powerful, a naive vector search implementation often faces several hurdles at scale:

  1. Contextual Granularity: A single large document might contain many topics. Embedding the entire document loses fine-grained information. Conversely, very small chunks might lack sufficient context.
  2. Semantic Mismatch: Vector search excels at semantic similarity but can struggle with exact keyword matches, proper nouns, or highly specific technical terms that might be rare in the embedding model's training data.
  3. Noise and Irrelevance: The top-k results from a vector search can sometimes include chunks that are semantically related but not precisely relevant to the user's intent, leading to "good enough" but not "best" context for the LLM.
  4. Computational Cost: Generating and storing millions or billions of embeddings, and then performing high-dimensional similarity searches, can be computationally intensive and expensive.
  5. Latency: For real-time applications, retrieval speed is paramount. Complex indexing and search operations need to be optimized.

To address these challenges, we turn to advanced strategies for chunking, hybrid retrieval, and reranking.

1. Intelligent Chunking Strategies: Crafting Contextual Units

Chunking is the process of dividing larger documents into smaller, coherent segments before embedding them. The goal is to create chunks that are small enough to be semantically focused, yet large enough to retain sufficient context for the LLM. The optimal chunk size and strategy depend heavily on the nature of the data and the specific use case.

Why Chunking is Crucial

  • Context Preservation: Provides the LLM with focused, relevant information without overwhelming its context window.
  • Improved Relevance: Smaller, topic-specific chunks lead to more precise vector search results.
  • Reduced Cost: Fewer tokens sent to the LLM means lower API costs and faster processing.
  • Manageability: Easier to embed and index smaller units.

Basic Chunking Methods

  1. Fixed-size Chunking: Divides text into segments of a predetermined character or token count, often with an overlap to maintain continuity.
  2. Sentence-based Chunking: Splits text into individual sentences. While precise, a single sentence often lacks sufficient context.

Advanced Chunking Strategies

  1. Recursive Character Text Splitter: This is a widely used and highly effective strategy. It attempts to split text using a list of delimiters (\n\n, \n, , ``) in order, recursively trying smaller delimiters if a chunk is still too large. This helps preserve semantic units like paragraphs or sentences.

    python
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    
    text = """\n# My Awesome Document\n\nThis is the first paragraph of my document. It talks about various interesting things and sets the stage for what's to come.\n\n## Section 1: Key Concepts\n\nHere we introduce the key concepts. Concept A is very important. Concept B builds on Concept A. We need to explain them clearly.\n\n### Subsection 1.1: Concept A Details\n\nMore details about Concept A. It has several properties and applications. This is a very important point to remember.\n\nThis is a separate sentence that might be related but could also be part of a different thought. We want to ensure context is maintained.\n"""
    
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=200,          # Max characters per chunk
        chunk_overlap=20,        # Overlap between chunks
        length_function=len,     # Function to measure chunk length
        is_separator_regex=False # Use standard delimiters
    )
    
    chunks = text_splitter.split_text(text)
    
    for i, chunk in enumerate(chunks):
        print(f"Chunk {i+1}:\n---\n{chunk}\n---")
    
    # Example Output (truncated for brevity):
    # Chunk 1:
    # ---
    # # My Awesome Document
    # This is the first paragraph of my document. It talks about various interesting things and sets the stage for what's to come.
    # ---
    # Chunk 2:
    # ---
    # Section 1: Key Concepts
    # Here we introduce the key concepts. Concept A is very important. Concept B builds on Concept A. We need to explain them clearly.
    # ---
    # Chunk 3:
    # ---
    # ### Subsection 1.1: Concept A Details
    # More details about Concept A. It has several properties and applications. This is a very important point to remember.
    # ---
  2. Document-Aware Splitters: These splitters understand the structure of specific document types. For instance, a MarkdownHeaderTextSplitter will split text based on Markdown headers, ensuring that content under a specific heading stays together.

    python
    from langchain.text_splitter import MarkdownHeaderTextSplitter
    
    markdown_document = """# Title\n\n## Chapter 1\n\nThis is chapter 1 content. It talks about many things.\n\n### Section 1.1\n\nDetails for section 1.1. More text here.\n\n## Chapter 2\n\nThis is chapter 2 content.\n"""
    
    headers_to_split_on = [
        ("#", "Header1"),
        ("##", "Header2"),
        ("###", "Header3"),
    ]
    
    markdown_splitter = MarkdownHeaderTextSplitter(
        headers_to_split_on=headers_to_split_on
    )
    
    md_chunks = markdown_splitter.split_text(markdown_document)
    
    for i, chunk in enumerate(md_chunks):
        print(f"Chunk {i+1}:\n---\n{chunk.page_content}\nMetadata: {chunk.metadata}\n---")
    
    # Example Output (truncated):
    # Chunk 1:
    # ---
    # This is chapter 1 content. It talks about many things.
    # Metadata: {'Header1': 'Title', 'Header2': 'Chapter 1'}
    # ---
    # Chunk 2:
    # ---
    # Details for section 1.1. More text here.
    # Metadata: {'Header1': 'Title', 'Header2': 'Chapter 1', 'Header3': 'Section 1.1'}
    # ---
  3. Semantic Chunking (Concept-based): This advanced technique uses embeddings to identify semantic boundaries. Instead of fixed lengths, it groups sentences or paragraphs that are semantically similar. This often involves embedding sentences, then clustering or identifying points of high semantic divergence to determine chunk boundaries. This can create highly coherent chunks but is computationally more expensive.

Pure vector search, while excellent for semantic understanding, has inherent limitations:

  • Rare Word Problem: It struggles with unique identifiers, proper nouns, or highly specific jargon that might not have strong semantic neighbors in the embedding space.
  • Exact Match Failure: If a user queries for an exact phrase or keyword, vector search might return semantically similar but not literally matching documents.
  • Recency Bias: Embedding models are often trained on static datasets, potentially struggling with very new or evolving concepts.

This is where hybrid retrieval shines. It combines the strengths of semantic (vector) search with traditional keyword-based methods like BM25 (Best Match 25).

What is BM25?

BM25 is a ranking function used by search engines to estimate the relevance of documents to a given search query. It's a variant of the TF-IDF (Term Frequency-Inverse Document Frequency) model, accounting for:

  • Term Frequency (TF): How often a query term appears in a document.
  • Inverse Document Frequency (IDF): How rare a query term is across the entire corpus (rarer terms get more weight).
  • Document Length Normalization: Prevents longer documents from being unfairly favored by having higher term frequencies.

BM25 is excellent at finding documents that contain exact or near-exact matches of keywords in the query. It's fast, well-understood, and effective for lexical matching.

The Power of Hybrid Retrieval

By combining vector search and BM25, we get the best of both worlds:

  • Semantic Understanding: Vector search handles paraphrases, synonyms, and conceptual queries.
  • Keyword Precision: BM25 ensures that documents containing specific keywords are highly ranked.

Implementing Hybrid Retrieval with Reciprocal Rank Fusion (RRF)

One of the most effective ways to combine results from different retrieval methods is Reciprocal Rank Fusion (RRF). RRF doesn't require tuning weights or normalizing scores, making it robust and easy to implement. It works by assigning a score to each document based on its rank in each individual retriever's result set.

Given two ranked lists of documents, L1 and L2, for a document d:

RRF_Score(d) = Σ (1 / (rank_i(d) + k))

Where:

  • rank_i(d) is the rank of document d in list i (e.g., vector search results, BM25 results).
  • k is a constant (typically 60) to avoid division by zero and give some weight to lower-ranked results.

A document ranked highly by multiple retrievers will accumulate a higher RRF score.

python
from langchain_community.retrievers import BM25Retriever
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.docstore.document import Document
from langchain.retrievers import EnsembleRetriever

# --- 1. Create some sample documents ---
texts = [
    "The quick brown fox jumps over the lazy dog.",
    "Artificial intelligence is transforming industries globally.",
    "Quantum computing represents a paradigm shift in computation.",
    "The brown fox was very quick today.",
    "Machine learning is a subset of AI."
]

docs = [Document(page_content=t) for t in texts]

# --- 2. Initialize a Vector Store (Chroma for simplicity) ---
# In a real application, you'd use a persistent store and a larger dataset.
embeddings = OpenAIEmbeddings(model="text-embedding-ada-002")
vectorstore = Chroma.from_documents(docs, embeddings)
vector_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

# --- 3. Initialize a BM25 Retriever ---
bm25_retriever = BM25Retriever.from_documents(docs)
bm25_retriever.k = 3 # Number of results to return from BM25

# --- 4. Create an EnsembleRetriever using RRF ---
# The weights parameter (list of floats) controls the relative importance
# of each retriever. If omitted, RRF is used by default with equal weighting.
ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, vector_retriever], weights=[0.5, 0.5])

# --- 5. Perform a Hybrid Search ---
query = "fast animal"
results = ensemble_retriever.invoke(query)

print(f"\nQuery: '{query}'")
print("--- Hybrid Retrieval Results (RRF) ---")
for i, doc in enumerate(results):
    print(f"Doc {i+1}: {doc.page_content}")

query_bm25 = "brown fox"
results_bm25 = ensemble_retriever.invoke(query_bm25)

print(f"\nQuery: '{query_bm25}'")
print("--- Hybrid Retrieval Results (RRF) ---")
for i, doc in enumerate(results_bm25):
    print(f"Doc {i+1}: {doc.page_content}")

# Example Output (may vary slightly based on embedding model):
# Query: 'fast animal'
# --- Hybrid Retrieval Results (RRF) ---
# Doc 1: The quick brown fox jumps over the lazy dog.
# Doc 2: The brown fox was very quick today.
# Doc 3: Artificial intelligence is transforming industries globally.
#
# Query: 'brown fox'
# --- Hybrid Retrieval Results (RRF) ---
# Doc 1: The quick brown fox jumps over the lazy dog.
# Doc 2: The brown fox was very quick today.
# Doc 3: Artificial intelligence is transforming industries globally.

In this example, the EnsembleRetriever from LangChain abstracts the RRF logic, allowing you to easily combine multiple retriever types.

3. The Power of Reranking Models: Refining Relevance

Even after intelligent chunking and hybrid retrieval, the initial set of retrieved documents (the top-k candidates) might still contain some noise or documents that are less relevant than others for the specific query. This is where reranking comes into play.

Reranking is a post-retrieval step that takes the initial set of retrieved chunks and re-scores them based on a deeper, more nuanced understanding of their relevance to the query. Its primary goal is to improve the precision of the top results, ensuring that the most pertinent information is presented to the LLM.

Why Reranking is Necessary

  • Address Subtleties: Initial retrieval (especially with bi-encoder models) often captures broad semantic similarity. Rerankers, typically cross-encoder models, can understand fine-grained relationships and contextual nuances.
  • Improve Top-K Accuracy: Elevates truly relevant documents to higher ranks and pushes less relevant ones down.
  • Reduce LLM Hallucination: By providing a cleaner, more focused context, reranking reduces the chances of the LLM being misled by irrelevant information.
  • Handle Ambiguity: Can help disambiguate queries where initial retrieval might return multiple valid but different interpretations.

How Reranking Works

Reranking models are typically cross-encoders. Unlike bi-encoders (used for initial retrieval, where query and document are embedded independently), cross-encoders take both the query and each candidate document chunk as input simultaneously. This allows them to model the interaction between the query and the document directly, leading to a much richer and more accurate relevance score. The trade-off is that cross-encoders are computationally more expensive and cannot be pre-indexed, meaning they must process each (query, document) pair at query time.

Popular reranking models include:

  • Cohere Rerank API: A powerful, proprietary solution.
  • BGE-reranker: An open-source, high-performing cross-encoder.
  • MiniLM-L6-cross-encoder: A smaller, faster option for certain use cases.
python
from sentence_transformers import CrossEncoder

# --- 1. Assume we have a query and some retrieved documents ---
query = "What is the capital of France?"
retrieved_docs = [
    "Paris is the capital and most populous city of France.",
    "The Eiffel Tower is located in Paris.",
    "France is a country in Western Europe.",
    "Berlin is the capital of Germany.",
    "The Louvre Museum is a famous landmark in Paris."
]

# --- 2. Load a Cross-Encoder Reranking Model ---
# This model will score the relevance of each (query, document) pair.
# 'cross-encoder/ms-marco-MiniLM-L-6-v2' is a good general-purpose reranker.
model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

# --- 3. Prepare pairs for reranking ---
# Each pair consists of (query, document_content)
query_doc_pairs = [[query, doc] for doc in retrieved_docs]

# --- 4. Get relevance scores ---
scores = model.predict(query_doc_pairs)

# --- 5. Combine docs with scores and sort ---
scored_docs = sorted(zip(scores, retrieved_docs), key=lambda x: x[0], reverse=True)

print(f"\nQuery: '{query}'")
print("--- Reranked Results ---")
for score, doc in scored_docs:
    print(f"Score: {score:.4f}, Doc: {doc}")

# Example Output:
# Query: 'What is the capital of France?'
# --- Reranked Results ---
# Score: 9.3897, Doc: Paris is the capital and most populous city of France.
# Score: 2.1121, Doc: The Eiffel Tower is located in Paris.
# Score: 1.2505, Doc: The Louvre Museum is a famous landmark in Paris.
# Score: -0.9991, Doc: France is a country in Western Europe.
# Score: -6.5056, Doc: Berlin is the capital of Germany.

Notice how "Paris is the capital..." receives a very high score, while "Berlin is the capital of Germany" receives a very low (negative) score, effectively pushing it to the bottom despite its initial semantic relation to "capital city."

Putting It All Together: An End-to-End Scalable RAG Workflow

Let's visualize how these components integrate into a robust RAG pipeline:

  1. Document Ingestion: Raw documents (text, PDFs, web pages) are fed into the system.
  2. Intelligent Chunking: Documents are split into optimized chunks using strategies like RecursiveCharacterTextSplitter or MarkdownHeaderTextSplitter, ensuring contextual coherence and appropriate size.
  3. Embedding and Indexing: Each chunk is converted into a vector embedding using a high-quality embedding model (e.g., OpenAI, BGE). These embeddings, along with the original text and any relevant metadata, are stored in a vector database. For BM25, a separate index (e.g., in-memory, ElasticSearch, Solr) is also created from the chunked text.
  4. User Query: The user submits a natural language query.
  5. Hybrid Retrieval: The query is simultaneously used for:
    • Vector Search: Embedded and sent to the vector database to find semantically similar chunks.
    • BM25 Search: Processed for keywords and sent to the BM25 index to find lexically similar chunks. The results from both retrievers are then fused using RRF to produce an initial ranked list of candidate chunks.
  6. Reranking: The top-N (e.g., 20-50) candidate chunks from the hybrid retrieval step are passed to a cross-encoder reranking model. This model re-evaluates the relevance of each chunk to the query, producing a refined, highly precise top-K (e.g., 5-10) list of chunks.
  7. LLM Context Augmentation: The final, highly relevant chunks are concatenated and provided as context to the LLM along with the original user query.
  8. Response Generation: The LLM generates a grounded and accurate response based on the provided context.

This multi-stage approach ensures that the LLM receives the most relevant and focused information, minimizing hallucinations and maximizing the quality of its output.

Best Practices for Production-Ready RAG Systems

  • Iterate on Chunking: There's no one-size-fits-all chunking strategy. Experiment with different chunk_size, chunk_overlap, and splitter types. Evaluate the impact on retrieval quality.
  • Evaluate Retrieval Metrics: Use metrics like Recall@k, Precision@k, Mean Reciprocal Rank (MRR), and Normalized Discounted Cumulative Gain (NDCG) with a human-labeled evaluation dataset to quantitatively assess your retrieval pipeline.
  • Choose the Right Embeddings: Select an embedding model that is suitable for your domain and task. Newer, larger models often perform better but come with higher inference costs.
  • Monitor Latency and Cost: Hybrid retrieval and reranking add computational overhead. Benchmark performance and optimize where necessary. Consider caching strategies for frequently asked queries.
  • Metadata is King: Store rich metadata with your chunks (e.g., source document, author, date, section title). This can be used for filtering, targeted retrieval, and improving reranking.
  • Dynamic Reranking Thresholds: Instead of a fixed top-K for reranking, consider dynamic thresholds based on reranker scores to filter out genuinely irrelevant content.
  • Fine-tuning: For highly specialized domains, consider fine-tuning your embedding and/or reranking models on your specific data for superior performance.

Common Pitfalls to Avoid

  • Over-chunking or Under-chunking: Chunks that are too small lose context; chunks that are too large dilute relevance and exceed LLM context windows.
  • Ignoring Keyword Relevance: Relying solely on vector search can lead to missing documents that contain crucial keywords, especially for factual or specific queries.
  • Skipping Reranking for Critical Applications: For applications where high precision is paramount (e.g., legal, medical), reranking is not an optional luxury but a necessity.
  • Static Strategies: Not adapting chunking, retrieval, or reranking based on user feedback or evolving data can lead to degraded performance over time.
  • Neglecting Document Structure: Treating all text as a flat sequence (e.g., ignoring Markdown headers, tables, code blocks) can destroy valuable contextual cues.
  • Lack of Observability: Without proper logging and monitoring, it's hard to diagnose why certain queries perform poorly or to identify areas for improvement.

Real-World Use Cases

These techniques are vital for building sophisticated RAG systems across various domains:

  • Enterprise Knowledge Bases: Enabling employees to quickly find precise answers within vast internal documentation, policies, and reports.
  • Customer Support Chatbots: Providing accurate, context-aware responses to customer inquiries by drawing from product manuals, FAQs, and support tickets.
  • Legal Document Analysis: Assisting legal professionals in rapidly sifting through case law, contracts, and legal briefs to find relevant precedents or clauses.
  • Personalized Content Recommendation: Delivering highly relevant articles, products, or services by understanding both the semantic intent and specific keywords in user preferences and historical interactions.
  • Medical Information Retrieval: Helping healthcare providers and researchers access up-to-date medical literature and patient records with high accuracy.

Conclusion: The Future of Intelligent Information Access

Scaling vector embeddings for RAG systems is not merely about storing more data; it's about intelligently processing, retrieving, and refining information to ensure LLMs operate with peak accuracy and relevance. By strategically implementing advanced chunking, hybrid BM25 and vector retrieval, and powerful reranking models, developers can overcome the limitations of basic semantic search.

These techniques form the bedrock of robust, production-grade RAG applications, transforming how organizations and individuals access and utilize vast amounts of information. As LLMs continue to evolve, the sophistication of our retrieval pipelines will remain a critical determinant of their ultimate utility and trustworthiness. The journey towards truly intelligent information access is an iterative one, demanding continuous experimentation, evaluation, and optimization across all stages of the RAG pipeline.

Support CodeWithYoha

Enjoyed this deep dive? Buy me a coffee!

Every article on CodeWithYoha is 100% free, independent, and sponsor-free. If this guide saved you hours of debugging or helped you architect better software, consider supporting future guides with a coffee ($5, $10, or any amount of your choice).

CodewithYoha

Written by

CodewithYoha

Full-Stack Software Engineer with 7+ years of experience in Java, Spring Boot, and cloud architecture across AWS, Azure, and GCP. Writing production-grade engineering patterns for developers who ship real software.