Why Vector Search Misses Exact Matches: Building Better RAG Retrieval with Hybrid Search
Imagine building an AI assistant for your company's internal documentation. An employee asks: What changed in API version v2.4.1? Your RAG system searches the knowledge base and returns documents about API upgrades,
Imagine building an AI assistant for your company's internal documentation.
An employee asks:
What changed in API version v2.4.1?
Your RAG system searches the knowledge base and returns documents about API upgrades, version compatibility, and release procedures.
Everything looks relevant.
But the actual release notes for v2.4.1 are missing.
The document exists. It's indexed. The embedding model works correctly.
So why didn't the retriever find it?
Because semantic similarity and exact matching solve different problems.
Vector search is excellent at finding related concepts, but it isn't always reliable when questions contain exact identifiers, error codes, product names, or version numbers.
This is one reason hybrid search has become an important part of production RAG systems.
I've worked on an Enterprise RAG Knowledge Assistant using PostgreSQL, pgvector, hybrid search, and reranking.
Let's look at how hybrid retrieval works, how to implement it, and what to measure before adding more complexity to your RAG pipeline.
1. Why Vector Search Isn't Always Enough
Vector search converts text into numerical representations called embeddings.
These embeddings help identify documents with similar meanings, even when they don't share the same words.
For example, a user might ask:
How can I reset my password?
A document titled "Recovering access to your account" could be a good match even though the wording is different.
This is where semantic search shines.
But consider another query:
How do I fix error ERR_AUTH_4017?
The exact error code matters more than general semantic similarity.
A vector search might return authentication troubleshooting guides without finding the specific document containing ERR_AUTH_4017.
The same issue appears with:
- API versions and endpoint names.
- Invoice and order identifiers.
- Technical error codes.
- Configuration parameters.
- Product model numbers.
- Internal project names.
Embeddings are useful for understanding meaning, but they aren't designed to guarantee exact identifier matching.
That doesn't mean vector search is broken.
It means we're asking one retrieval technique to solve two different problems.
2. What Hybrid Search Actually Does
Hybrid search combines two retrieval strategies.
Semantic search finds documents based on meaning.
Lexical search finds documents based on words, terms, and text-matching rules.
For example, consider this hypothetical knowledge base:
| Document | Content |
|---|---|
| A | How to troubleshoot authentication failures |
| B | ERR_AUTH_4017: Token validation failure |
| C | Common API authentication errors |
| D | Understanding OAuth access tokens |
For the query ERR_AUTH_4017, semantic search might consider A, C, and D relevant because they're about authentication.
Lexical search can identify B because it contains the exact error code.
Hybrid search combines both result sets so the application can benefit from semantic understanding and precise term matching.
The basic architecture looks like this:
User Question
|
+-------+-------+
| |
v v
Vector Search Keyword Search
| |
v v
Semantic Results Lexical Results
| |
+-------+-------+
|
v
Rank Fusion
|
v
Reranking
|
v
Retrieved Context
|
v
LLM
The goal isn't to return more documents.
It's to return the documents most likely to contain the information needed to answer the question.
3. Implement Both Searches in PostgreSQL
PostgreSQL is a convenient option because it supports full-text search natively and vector similarity through pgvector.
Let's create a simplified document table.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE document_chunks (
id BIGSERIAL PRIMARY KEY,
content TEXT NOT NULL,
embedding vector(1536),
search_vector TSVECTOR GENERATED ALWAYS AS (
to_tsvector('english', content)
) STORED
);
The embedding dimension must match the model generating your vectors.
The search_vector column stores a text-search representation of each chunk.
We can add indexes for both retrieval strategies.
CREATE INDEX idx_chunks_fts
ON document_chunks
USING GIN (search_vector);
CREATE INDEX idx_chunks_embedding
ON document_chunks
USING hnsw (embedding vector_cosine_ops);
The GIN index supports full-text search.
The HNSW index supports approximate vector similarity search using cosine distance.
Neither index guarantees that a particular document will be retrieved for every query. Retrieval behavior still depends on candidate limits, query structure, and data distribution.
Semantic retrieval
With a query embedding supplied by the application:
SELECT id, content
FROM document_chunks
WHERE embedding IS NOT NULL
ORDER BY embedding <=> $1::vector
LIMIT 20;
Here, <=> is pgvector's cosine-distance operator.
Smaller distances indicate greater similarity.
Lexical retrieval
PostgreSQL also supports ranked text search:
SELECT id, content
FROM document_chunks
WHERE search_vector @@
websearch_to_tsquery('english', $1)
ORDER BY ts_rank_cd(
search_vector,
websearch_to_tsquery('english', $1)
) DESC
LIMIT 20;
This returns chunks matching the text-search query, ordered by a relevance score.
One caveat matters for our original example: PostgreSQL full-text search tokenizes and normalizes text. Identifiers containing underscores, hyphens, or punctuation may not be treated as indivisible strings.
For identifiers that must match exactly, add an explicit field or exact-match lookup alongside full-text search.
That's especially important for API versions, error codes, and customer-facing reference numbers.
References: PostgreSQL Full-Text Search and pgvector Documentation.
4. Combine Results Using Reciprocal Rank Fusion
Now we have two ranked result lists.
How should we combine them?
A tempting approach is adding similarity scores to keyword relevance scores.
But those scores don't necessarily share the same scale.
A vector distance of 0.2 isn't directly comparable to a text-search relevance score of 0.2.
One practical alternative is Reciprocal Rank Fusion (RRF).
Instead of combining raw scores, RRF combines ranking positions.
The formula is:
[
RRF(d) = \sum_{r \in R} \frac{1}{k + rank_r(d)}
]
Here, rank is the document's one-based position in a result list, and k is a smoothing constant.
A commonly used starting value is 60, but it isn't universally optimal.
Here's a simple Python implementation:
from collections import defaultdict
def reciprocal_rank_fusion(
ranked_lists: list[list[int]],
k: int = 60,
) -> list[tuple[int, float]]:
scores = defaultdict(float)
for results in ranked_lists:
for rank, document_id in enumerate(results, 1):
scores[document_id] += 1 / (k + rank)
return sorted(
scores.items(),
key=lambda item: (-item[1], item[0]),
)
The function expects each list to contain document IDs ordered from most relevant to least relevant, without duplicates within an individual list.
For example:
vector_results = [12, 7, 31, 5]
keyword_results = [31, 12, 9, 7]
combined = reciprocal_rank_fusion(
[vector_results, keyword_results]
)
Documents that rank well across both searches receive stronger combined scores.
A document appearing in only one list can still rank well if its position is sufficiently strong.
This is useful because we don't need to calibrate two unrelated scoring systems before combining their results.
However, RRF doesn't automatically guarantee better retrieval quality. Candidate depth, document relevance, and rank-fusion parameters still matter.
5. Why Reranking Is Still Useful
After merging both result sets, we might have 30 or 40 unique candidates.
Passing every candidate to the language model isn't necessarily a good idea.
It increases token usage and may introduce irrelevant or conflicting information.
This is where reranking helps.
A reranker evaluates the relationship between the query and individual candidate documents, then produces a more focused ordering.
A practical workflow might look like this:
Vector search: top 20
Keyword search: top 20
|
v
Merge and deduplicate
|
v
Reciprocal Rank Fusion
|
v
Rerank top candidates
|
v
Select final 5 chunks
|
v
Send context to LLM
The numbers are illustrative and should be tuned against evaluation data.
Reranking adds latency and may introduce additional inference costs.
For simple applications, hybrid search without a separate reranker might already provide sufficient results.
I wouldn't add reranking automatically. I'd first measure whether it improves retrieval quality enough to justify the extra processing.
6. Don't Forget Metadata Filtering
Hybrid search isn't only about keywords and vectors.
Real applications need access controls and metadata filtering.
For an enterprise knowledge assistant, a user should only retrieve documents they're authorized to access.
That means both retrieval paths must apply the same authorization rules.
For example:
SELECT id, content
FROM document_chunks
WHERE organization_id = $1
AND embedding IS NOT NULL
ORDER BY embedding <=> $2::vector
LIMIT 20;
This assumes the table includes an organization_id column and the application has independently verified the caller's authorization for that organization.
The lexical search should apply the same restrictions.
There's also a pgvector performance detail worth understanding.
With approximate vector indexes, selective filters may be applied after the initial index scan, potentially returning fewer matches than requested.
Depending on workload and pgvector version, iterative index scans, partitioning, or an alternative indexing strategy may help.
See pgvector's filtering documentation.
Security filtering is not something to fix after retrieval.
Unauthorized documents should never be passed to a model or reranker that isn't permitted to process them.
7. How to Know If Hybrid Search Is Better
Adding keyword search, rank fusion, and reranking makes a pipeline more complicated.
Before calling it an improvement, we need evidence.
I would build a small evaluation dataset containing questions with known relevant documents.
Include several categories:
| Question type | Example |
|---|---|
| Semantic | How can employees recover account access? |
| Exact identifier | What causes ERR_AUTH_4017? |
| Version-specific | What changed in API v2.4.1? |
| Mixed intent | How do I resolve the token error introduced in v2.4.1? |
| Unanswerable | What is the policy for an undocumented feature? |
Then compare three retrieval strategies:
- Vector search only.
- Keyword search only.
- Hybrid search with rank fusion.
Useful measurements include Recall\@K, which checks whether relevant documents appear within the first K results, and MRR, which rewards placing a relevant result near the top.
For production use, I'd also monitor retrieval latency, token usage, and total cost per successfully answered question.
And remember: retrieval success isn't the same as answer correctness.
A system can retrieve the right document and still generate an unsupported answer.
For that reason, retrieval evaluation and answer-grounding evaluation should remain separate.
8. When Hybrid Search Isn't Worth It
Hybrid search is useful, but it isn't always necessary.
If your application searches a small, highly structured knowledge base with predictable questions, a straightforward lexical or SQL lookup might be enough.
If queries are mostly conceptual and exact identifiers rarely matter, semantic search alone could perform well.
And if a user enters a known invoice ID, you probably shouldn't use vector search at all.
A direct indexed database query is simpler and more reliable.
This leads to another useful design approach: query routing.
You can detect certain structured query types and send them directly to deterministic lookup tools.
Other questions can use semantic or hybrid retrieval.
The important point is that retrieval should match the user's information need rather than forcing every request through the same pipeline.
Final Thoughts
Vector search is powerful, but similarity doesn't guarantee relevance.
When questions contain exact identifiers, specific versions, or technical terminology, semantic retrieval can miss documents that keyword-based methods find easily.
Three lessons stand out:
- Combine meaning with exact matching. Semantic search and lexical search solve complementary problems.
- Use rank fusion carefully. RRF provides a practical way to merge result lists without directly comparing incompatible scores.
- Evaluate retrieval before adding complexity. Hybrid search and reranking are only improvements when they help users find the correct information.
Building a reliable RAG system isn't about adding more retrieval techniques.
It's about choosing the right technique for the question and proving that it works.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.