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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Two ways to match

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.

AspectKeyword (lexical)Vector (semantic)
Matches onShared terms, weighted by rarityCloseness of embeddings
Strong atNames, codes, rare terms, exact phrasesParaphrases, concepts, cross-wording
Weak atSynonymsExact identifiers, negation, numbers
Explains a resultMatching termsA similarity score
Query and verified identityquestion, tenant, groups
Keyword searchfiltered by access
Vector searchfiltered by access
Other signalsrecency, authority
Fuse rankingsfor example 50 candidates
Rerank and selecta handful for the model
Wide and cheap first, narrow and careful afterward.

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.

Intermediate Models, indexes, hybrid search and filters

Choosing and evaluating an embedding model

CriterionQuestions
Quality on your dataRecall and ranking on your questions and documents
Languages and domainDoes it handle your languages, jargon and code?
Input lengthDoes your chunk fit without silent truncation?
DimensionsStorage and speed; can they be shortened?
Query and document modesDoes it expect different prefixes or settings?
HostingHosted API or self-run; data location; cost; rate limits
LifecycleVersion 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 familyIdeaTrade-off
FlatCompare everythingExact, cost grows with size
HNSWNavigate a layered neighbor graphFast and accurate, memory hungry
IVFSearch only the nearest clustersCompact, needs representative training
QuantizationStore compressed vectorsMuch 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.
Even counts and snippets leak

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.

Expert Reranking, databases and tuning

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.

SettingRaise it toCost
Candidates retrievedGive the reranker more chancesLatency and reranking charges
Results keptCover multi-part questionsContext tokens and distraction
Score thresholdRefuse weak evidenceMore "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 typeExamplesStrengthWatch for
Extension to your databasepgvectorOne system, joins and transactionsIndex memory and filtered recall
Search engine with vectorsOpenSearch, Elasticsearch, VespaMature keyword search and rankingOperating effort and licensing
Dedicated vector databaseQdrant, Milvus, Weaviate, PineconeVector features and scaleAnother system to secure and sync
Embedded library or file storeChroma, LanceDB, FAISSQuick start, local useConcurrency 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.

RequirementWhat to verify
Hybrid searchNative, or your own fusion code
FilteringRecall under selective filters
Multi-tenancyNamespaces, partitions, limits
Access controlRoles, row or collection level
FreshnessDelay from write to searchable
DeletionImmediate invisibility and space reclaim
QuantizationOptions and rescoring
OperationsBackup, upgrade, monitoring
CostAt your size, query rate and replicas
ExitExport of vectors and metadata

Tuning in a disciplined order

  1. Build the question set, including exact-code, paraphrase, multi-part and unanswerable questions.
  2. Measure keyword search alone as a baseline.
  3. Add vector search and fusion; compare.
  4. Check filtered recall with restricted users.
  5. Add reranking; measure ranking quality and latency.
  6. Only then adjust chunking or models, one at a time.
Illustrative example: the missing part numbers

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.

StageWhat drives timeTypical lever
Query embeddingNetwork call and model sizeCache repeated queries, batch parts of a decomposed question
Index searchCollection size, search width, memoryTune width, keep the index in memory, partition
FilteringSelectivity and engine strategyIndexes on filter fields, per-tenant partitions
RerankingCandidate count and passage lengthFewer or shorter candidates, smaller model
Fetching textSeparate record lookupsReturn 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

  1. Confirm the right passage exists in the index and is visible to this user.
  2. Check its rank in keyword results and in vector results separately.
  3. If it is in neither candidate list, look at chunking, the query wording and filters.
  4. If it is a candidate but ranks low after fusion, adjust weights or candidate counts.
  5. If the reranker demotes it, inspect passage length and whether context such as the title is missing.
  6. 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

Next steps