Embeddings, Vector and Hybrid Search, Reranking
The search layer of a retrieval agent, from the first embedding to a measured pipeline with permission filters and a reranker.
Keyword search finds exact words and codes. Vector search finds similar meaning. Hybrid search runs both and merges the rankings, and a reranker then reorders a short candidate list more carefully. Apply permission filters inside the search, choose embedding models and databases by testing on your own questions, and add each stage only if the measurements improve.
What you will learn: embeddings, how to choose and evaluate a model, vector indexes, BM25, rank fusion, permission-aware filtering, reranking and how to compare databases.
Prerequisites: RAG Explained and Agentic RAG and Document Ingestion, Parsing and Chunking.
Words and meaning
Ask for "E-4042" and you want documents containing exactly that code. Ask "I forgot my sign in details" and you want the page about resetting credentials, although it shares few words. One kind of search does not do both well.
| Aspect | Keyword (lexical) | Vector (semantic) |
|---|---|---|
| Matches on | Shared terms, weighted by rarity | Closeness of embeddings |
| Strong at | Names, codes, rare terms, exact phrases | Paraphrases, concepts, cross-wording |
| Weak at | Synonyms | Exact identifiers, negation, numbers |
| Explains a result | Matching terms | A similarity score |
Embeddings in plain terms
An embedding model maps a piece of text to a list of numbers, perhaps a few hundred to a few thousand of them. Training arranges that texts with related meaning point in similar directions. Cosine similarity or a dot product measures that closeness. If vectors are normalized to length one, cosine similarity, dot product and Euclidean distance rank results in the same order. A score has meaning only relative to other scores from the same model; 0.8 from one model is not comparable with 0.8 from another.
Choosing and evaluating an embedding model
| Criterion | Questions |
|---|---|
| Quality on your data | Recall and ranking on your questions and documents |
| Languages and domain | Does it handle your languages, jargon and code? |
| Input length | Does your chunk fit without silent truncation? |
| Dimensions | Storage and speed; can they be shortened? |
| Query and document modes | Does it expect different prefixes or settings? |
| Hosting | Hosted API or self-run; data location; cost; rate limits |
| Lifecycle | Version pinning and deprecation notice |
Public leaderboards such as MTEB are useful for shortlisting. They do not know your documents. Collect fifty or more real questions with the passages that answer them, embed with each candidate and compare recall at the number of results you will actually use. Some models are trained so that the leading dimensions work on their own (the Matryoshka approach), which lets you trade a little accuracy for much smaller storage. Changing models later means embedding the whole collection again.
Vector search fundamentals
Exact search compares the query with every vector. It is simple and perfectly accurate, and quite fast up to many thousands of items, especially after filtering. Approximate nearest neighbor indexes skip most comparisons and accept missing a few true neighbors.
| Index family | Idea | Trade-off |
|---|---|---|
| Flat | Compare everything | Exact, cost grows with size |
| HNSW | Navigate a layered neighbor graph | Fast and accurate, memory hungry |
| IVF | Search only the nearest clusters | Compact, needs representative training |
| Quantization | Store compressed vectors | Much smaller, some accuracy lost, often rescored |
Index settings control how widely the search looks. Measure recall against exact search on a sample, then choose settings that meet your target at acceptable latency.
Hybrid search
BM25 is the standard keyword scoring method. It rewards terms that are rare in the collection, with diminishing returns for repetition and an adjustment for document length. Its scores and cosine similarities live on different scales, so adding them directly is fragile. Reciprocal rank fusion sidesteps this: each list contributes one divided by a constant plus the item's position, commonly with a constant of 60.
"""Permission filter, BM25, meaning search and reciprocal rank fusion."""
import math
import re
from collections import Counter
DOCS = [ # id, groups, text
("d1", {"staff"}, "Error E-4042 means the invoice export timed out"),
("d2", {"staff"}, "Resetting your login credentials in the portal"),
("d3", {"staff"}, "How to export invoices to a spreadsheet"),
("d4", {"hr"}, "Resetting salary records after a login audit"),
("d5", {"staff"}, "Password rules: length and rotation"),
]
# A hand-made stand-in for an embedding model: words share a concept
CONCEPT = {"password": "auth", "login": "auth", "credentials": "auth",
"sign": "auth", "reset": "reset", "resetting": "reset",
"forgot": "reset", "export": "export", "download": "export",
"invoice": "invoice", "invoices": "invoice", "bills": "invoice"}
def tokens(t):
return re.findall(r"[a-z]+-?\d*", t.lower())
def bm25(query, docs, k1=1.5, b=0.75):
bags = {d[0]: Counter(tokens(d[2])) for d in docs}
avg = sum(sum(c.values()) for c in bags.values()) / len(bags)
scores = {}
for q in set(tokens(query)):
n = sum(q in c for c in bags.values())
idf = math.log(1 + (len(bags) - n + 0.5) / (n + 0.5))
for doc_id, c in bags.items():
if q in c:
length = k1 * (1 - b + b * sum(c.values()) / avg)
scores[doc_id] = scores.get(doc_id, 0) + idf * c[q] * (k1 + 1) / (c[q] + length)
return sorted(scores, key=lambda d: -scores[d])
def meaning(query, docs):
def vec(t):
return Counter(CONCEPT[w] for w in tokens(t) if w in CONCEPT)
q = vec(query)
def cos(v):
norm = math.sqrt(sum(x * x for x in q.values()) * sum(x * x for x in v.values()))
return sum(q[k] * v[k] for k in q) / norm if norm else 0.0
scored = [(cos(vec(d[2])), d[0]) for d in docs]
return [d for s, d in sorted(scored, key=lambda p: (-p[0], p[1])) if s > 0]
def rrf(*rankings, k=60):
total = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, 1):
total[doc_id] = total.get(doc_id, 0) + 1 / (k + rank)
return sorted(total, key=lambda d: (-total[d], d))
def search(query, groups):
visible = [d for d in DOCS if d[1] & groups] # filter BEFORE ranking
lexical, semantic = bm25(query, visible), meaning(query, visible)
return lexical, semantic, rrf(lexical, semantic)
for query in ("E-4042", "forgot my sign in password", "download bills"):
lexical, semantic, fused = search(query, {"staff"})
print(f"{query!r}\n keyword {lexical}\n meaning {semantic}\n fused {fused[:3]}")
print("HR sees:", search("reset login", {"staff", "hr"})[2][:3])
Output:
'E-4042'
keyword ['d1']
meaning []
fused ['d1']
'forgot my sign in password'
keyword ['d5', 'd2']
meaning ['d2', 'd5']
fused ['d2', 'd5']
'download bills'
keyword []
meaning ['d1', 'd3']
fused ['d1', 'd3']
HR sees: ['d2', 'd4', 'd5']
The code query is found only by keywords, and "download bills" only by meaning, since no document uses those words. The tiny concept table stands in for an embedding model, which would learn such relationships from data. For the HR user the restricted record appears; for staff it never entered either ranking.
Weighting
Fusion can weight one list more heavily, or you can route: queries that look like identifiers favor keywords. Tune on a test set that contains both kinds of question, or you will optimize one and damage the other.
Metadata filtering and access control
Filters narrow by product, language, date or status. Permission filters are special: they must be correct every time.
- Derive filter values from authenticated identity in your code.
- Apply them inside the search engine, before ranking and before any text reaches a model, reranker or log.
- Do not retrieve the top results and then drop forbidden ones: you may end with none, and restricted text has already traveled.
- Check how your engine combines filters with approximate indexes. Some filter after candidate selection, so selective filters reduce recall unless you enable iterative scanning, partition or build partial indexes.
- Test with a user who may see very little.
Autocomplete, facet counts, "no access" messages naming a title and cached results can all reveal restricted information. Apply the same rules to every path.
RAG Security, Freshness and Cost covers permission synchronization.
Reranking
An embedding model reads the query and each document separately, which makes search fast but coarse. A cross-encoder reranker reads query and passage together and scores their relevance more precisely. It is too slow for a whole collection and well suited to the best few dozen candidates. Late-interaction models sit between the two. A language model can also rerank, at higher cost.
| Setting | Raise it to | Cost |
|---|---|---|
| Candidates retrieved | Give the reranker more chances | Latency and reranking charges |
| Results kept | Cover multi-part questions | Context tokens and distraction |
| Score threshold | Refuse weak evidence | More "not found" answers |
A reranker cannot recover a passage that was never among the candidates. Check candidate recall first, then ranking quality. In Anthropic's contextual retrieval experiments, adding reranking to contextual embeddings and keyword search reduced retrieval failures further, a useful hint that the stages complement each other.
Comparing vector databases for agentic retrieval
An agent may search several times per task, with narrow filters, soon after writing new data. That shapes what to test.
| Option type | Examples | Strength | Watch for |
|---|---|---|---|
| Extension to your database | pgvector | One system, joins and transactions | Index memory and filtered recall |
| Search engine with vectors | OpenSearch, Elasticsearch, Vespa | Mature keyword search and ranking | Operating effort and licensing |
| Dedicated vector database | Qdrant, Milvus, Weaviate, Pinecone | Vector features and scale | Another system to secure and sync |
| Embedded library or file store | Chroma, LanceDB, FAISS | Quick start, local use | Concurrency and access control |
A feature matrix to fill in
Product features change quickly, so a printed matrix goes out of date. Copy this one and fill it from current documentation and your own tests.
| Requirement | What to verify |
|---|---|
| Hybrid search | Native, or your own fusion code |
| Filtering | Recall under selective filters |
| Multi-tenancy | Namespaces, partitions, limits |
| Access control | Roles, row or collection level |
| Freshness | Delay from write to searchable |
| Deletion | Immediate invisibility and space reclaim |
| Quantization | Options and rescoring |
| Operations | Backup, upgrade, monitoring |
| Cost | At your size, query rate and replicas |
| Exit | Export of vectors and metadata |
Tuning in a disciplined order
- Build the question set, including exact-code, paraphrase, multi-part and unanswerable questions.
- Measure keyword search alone as a baseline.
- Add vector search and fusion; compare.
- Check filtered recall with restricted users.
- Add reranking; measure ranking quality and latency.
- Only then adjust chunking or models, one at a time.
A maintenance assistant built on vector search alone often returns the manual for a similar part. Adding keyword search with fusion fixes part-number questions. The team then notices that technicians at small sites get few results, traces it to post-filtering in their index and enables partitioning by site.
Latency and capacity
An agent that searches five times pays the search latency five times, in sequence unless the searches are independent. Give each stage a budget and measure the slow end of the distribution, not only the average.
| Stage | What drives time | Typical lever |
|---|---|---|
| Query embedding | Network call and model size | Cache repeated queries, batch parts of a decomposed question |
| Index search | Collection size, search width, memory | Tune width, keep the index in memory, partition |
| Filtering | Selectivity and engine strategy | Indexes on filter fields, per-tenant partitions |
| Reranking | Candidate count and passage length | Fewer or shorter candidates, smaller model |
| Fetching text | Separate record lookups | Return needed fields in one request |
Run keyword and vector searches in parallel, and set timeouts with a defined fallback, for example returning fused results without reranking if the reranker is slow, while recording that it happened. Capacity planning must include rebuilds: an embedding change or index maintenance can need a second copy of the index for a while.
Diagnosing a bad result
- Confirm the right passage exists in the index and is visible to this user.
- Check its rank in keyword results and in vector results separately.
- If it is in neither candidate list, look at chunking, the query wording and filters.
- If it is a candidate but ranks low after fusion, adjust weights or candidate counts.
- If the reranker demotes it, inspect passage length and whether context such as the title is missing.
- If it reaches the model and the answer is still wrong, the problem is generation, not search.
Store these stage-by-stage ranks in traces. They turn "search is bad" into a specific, fixable statement.
Keeping results stable
Pin model and index settings, version the fusion weights and record them with each trace. Approximate indexes and ties can reorder results between runs, so compare sets and metrics, not exact lists, when you test a change.
Common mistakes
- Vector search only, with identifiers all over the documents.
- Comparing scores from different models or engines.
- Filtering after retrieval.
- Adding a reranker without checking candidate recall.
- Choosing a database from a benchmark that ignores filters.
Checklist
- A labeled question set exists and is versioned.
- The embedding model was compared on your data and pinned.
- Approximate search recall is measured against exact search.
- Keyword and vector results are fused.
- Permission filters run inside the search and are tested.
- Reranking is justified by measurements.
- Latency and cost are tracked per stage.
Frequently asked questions
Is keyword search obsolete?
No. It remains strong for exact terms and is cheap and explainable. Many good systems combine it with vector search.
How many results should reach the model?
As few as answer the question reliably. Test several values and watch both answer quality and input tokens.
Should I fine-tune an embedding model?
Consider it after trying hybrid search, better chunks and reranking, and only with enough labeled pairs and a held-out test set.
Do I need a similarity threshold?
Some way to recognize weak evidence is essential. Thresholds on reranker scores are often more stable than raw similarity, but calibrate them either way.
References and further reading
- Reimers and Gurevych: Sentence-BERT
- Muennighoff et al.: MTEB benchmark
- Kusupati et al.: Matryoshka representation learning
- Malkov and Yashunin: HNSW
- Cormack et al.: Reciprocal rank fusion
- pgvector documentation, including filtering
- Anthropic: Introducing Contextual Retrieval
Next steps
Query Rewriting, Multi-Hop, SQL and Multimodal RAG
Rewrite queries, hop across sources and query databases.
RAG Evaluation, Grounding and Debugging
The metrics behind every choice above.
Multimodal, Embedding and Reranking Models
More about the models themselves.