Concept lesson · Foundations
Keyword search and vector retrieval
Start here
Definition
Keyword search retrieves documents by matching searchable terms extracted from text; vector retrieval finds documents whose numeric embeddings are close to the query embedding under a chosen similarity measure. Retrieval selects candidates, ranking orders them, and hybrid search combines term-based and vector signals.
Why it matters: Users may type exact identifiers or describe the same idea with different words. The system needs efficient candidate selection without confusing similarity with correctness or permission.
The lexical example finds exact analyzed terms; the vector example compares directions. Neither establishes truth or access permission.
Read the diagram step by step
- For reset AND access, intersect reset={D2,D4} and access={D1,D4} to retrieve D4.
- The vector example uses Q=(1,0), D1=(0.98,0.20), and D2=(0.60,0.80). Cosine similarity is about 0.98 for D1 and 0.60 for D2.
- The vector drawing is two-dimensional intuition, not a map of real language dimensions.
- Authorize the exact content version before sending private text to a reranker or model. Rank permitted candidates and check release permissions; Birch private D3 must not leak into Acme results.
Worked example
For reset access, the reset posting list is [D2,D4] and access is [D1,D4], so AND returns D4. Vector retrieval can additionally connect “lost phone” with D1’s “recover authenticator” wording.
Key takeaways
- An inverted index maps terms to documents; an embedding represents similarity numerically.
- Approximate nearest-neighbor search (ANN) saves work by allowing missed neighbors; measure the tradeoff.
- Ranking cannot recover missing candidates, and similarity does not grant authorization.
You will learn to
- Construct a small inverted index and explain a query.
- Distinguish semantic similarity from factual truth and exact matching.
- Evaluate retrieval quality, freshness, latency, and permissions.
Practice in this chapter
8 interview questions with model answers and follow-ups.
Go to interview practiceUseful foundations: Database indexes: B-trees, composite keys and query access · Data partitioning and sharding · Authentication, authorization, and tenant isolation
Workload and timing examples are interview assumptions.
Dotted concept links open the relevant explanation in a new tab.
01Keyword search, vector retrieval, and ranking: definitions
Keyword search retrieves documents by matching searchable terms extracted and normalized from text. Vector retrieval finds documents whose numeric representations, called embeddings, are close to a query embedding under a chosen similarity measure. Retrieval selects candidates, ranking orders them, and hybrid search combines lexical (term-based) and vector signals. The source database preserves business facts. A search index is a derived, lookup-optimized representation of those records; asynchronous indexing means a successful source write need not be immediately searchable.
Use separate tests for lexical relevance, semantic relevance, freshness, and authorization. For query reset MFA phone lost (MFA means multi-factor authentication), Acme document D1 describes authenticator recovery, while D2 includes “reset MFA” but describes a different administrative procedure. Birch’s private runbook D3 must remain excluded. This dataset illustrates retrieval and access constraints without making either a substitute for the other.
Treat relevance, freshness and access as separate acceptance criteria. A highly similar result can still describe an obsolete procedure or belong to another tenant.
02Inverted index, tokenization, postings, and BM25
An inverted index maps a term to the documents containing it. A tokenizer splits text into searchable units; an analyzer may normalize case, handle language, or apply stemming. Exact product codes and identifiers often need a separate exact-match field because ordinary text analysis can alter punctuation or structure.
A posting here is a document ID. Green D1 appears in both lists, so it satisfies the AND query.
Remember: AND keeps IDs present in both term lists.
Read the diagram
- Find the shared document ID for green AND chair.
- green maps to D1 and D3; chair maps to D1 and D2.
- Their intersection is D1, the document green chair.
Try from memoryWhat would green OR chair return from these lists?
The union is D1, D2 and D3, with D1 included once. AND returns only the intersection, D1.
Suppose the analyzed documents are D1: recover access authenticator lost, D2: admin reset mfa, and D4: reset phone access. Their small index includes:
| Term | Posting list |
|---|---|
| access | D1, D4 |
| reset | D2, D4 |
| lost | D1 |
| mfa | D2 |
For an AND query reset access, intersect the posting lists and obtain D4. An OR query can return D1, D2, and D4, then rank them. Positions support phrase matching; document and term statistics support ranking. BM25 is a common lexical ranking function that rewards useful term matches while accounting for frequency and document length. Its score is not a probability that the answer is true.
BM25 combines three ideas: a match on a rarer term carries more information, repeated occurrences of one term have diminishing benefit, and document-length normalization stops long documents winning merely because they contain more words. In the tiny corpus, mfa appears in one document while access appears in two; their document-frequency signals differ. Phrase positions, required terms and exact identifier fields remain separate query controls, rather than guarantees supplied by a high BM25 score.
03Embeddings and cosine similarity
A two-dimensional schematic illustrates cosine similarity. Production embeddings often use many dimensions and model-specific geometry.
Remember: Dot product divided by both lengths measures direction similarity.
Read the diagram
- A is (1,1); B is (2,1); their dot product is 3.
- Their lengths are sqrt(2) and sqrt(5); cosine similarity is 3/sqrt(10), about 0.949.
- 2A is (2,2), on the same ray as A. Positive scaling does not change the angle to B.
Try from memoryDoes doubling A double its cosine similarity with B?
No. The dot product and A’s length both double, so their ratio is unchanged.
For intuition, imagine two-dimensional vectors: query Q=(1,0), D1=(0.98,0.20), and D2=(0.60,0.80). After accounting for normalization, cosine similarity to Q is approximately 0.98 for D1 and 0.60 for D2. Real systems often use hundreds or thousands of dimensions; the two-dimensional numbers only illustrate relative direction.
Semantic retrieval can connect “phone lost” with “recover authenticator” without identical words. It can also retrieve a similar-sounding wrong procedure. Exact IDs, dates, negation, and small wording differences may matter more than broad similarity. Keep lexical matching and metadata constraints when they serve the query contract.
Cosine similarity compares the directions of two nonzero vectors: dot(Q,D) / (length(Q) * length(D)). The dot product multiplies corresponding coordinates and adds the products. A vector’s length is the square root of the sum of its squared coordinates. Normalizing a vector divides every coordinate by that length, giving a unit-length vector. For D1, the denominator is sqrt(0.98^2 + 0.20^2) ≈ 1.0002, so similarity is about 0.9798; D2 has unit length and scores 0.60. With unit-normalized vectors, dot product and cosine produce the same ranking, and squared Euclidean distance is 2 - 2*cosine. Without normalization these metrics can rank candidates differently. A zero vector needs an explicit handling policy because cosine is undefined.
04Search ingestion and query lifecycle
- Ingest Acme document D1 version 7 with its ID, title, tenant, access policy, source version, and location.
- Split long content into coherent chunks, retaining permissions and provenance on each chunk.
- Build term postings and embeddings with recorded analyzer and model versions. Record which source version is indexed.
- Authenticate the query request, derive its allowed tenant/document scope, analyze the query, and embed it using the compatible query model.
- Retrieve scoped candidate IDs. Check each candidate against the source system’s current permissions, obtaining the exact content version and policy revision that were authorized; fetch that immutable version. On a version/policy mismatch, reauthorize or discard the candidate.
- Fuse lists or rerank only content authorized by that decision. Before returning snippets, enforce the policy for when permission revocations take effect and withhold or retry any candidate whose required policy revision no longer matches.
- Reauthorize a later source-document request. A search hit does not grant permanent access.
- 1 → 2versioned ingestionD1 v7 + Acme permissions → Term index + vector index
- 3 → 4query terms and embeddingQuery + verified tenant scope → Scoped candidate IDs
- 2 → 4eligible candidatesTerm index + vector index → Scoped candidate IDs
- 4 → 5authorize + fetch exact versionsScoped candidate IDs → Fusion / bounded reranking
- 5 → 6enforce release policy revisionFusion / bounded reranking → Permitted snippet + source
05Exact nearest neighbors, ANN, HNSW, and vector memory
Exact nearest-neighbor search returns the true nearest eligible vectors under the chosen metric. A simple exact baseline scores every eligible vector; an exact index may prune candidates only when it can prove they cannot change the answer. Exhaustive scoring is often useful as an evaluation baseline, but exactness is a result guarantee, not a requirement to scan every vector. Approximate nearest-neighbor search, ANN, uses an index to examine fewer candidates, trading some retrieval recall for latency and resource savings. Hierarchical Navigable Small World (HNSW) is a graph-based ANN approach: search navigates connections among nearby vectors rather than scanning all vectors.
For 10 million vectors with 768 float32 components, raw vectors consume 10,000,000 × 768 × 4 bytes = 30.72 GB in decimal units. Graph links, metadata, text, replicas, and indexing overhead add more. Quantization can reduce vector storage, with a quality and implementation tradeoff that must be measured.
HNSW uses a hierarchy: sparse upper layers provide long-range navigation, then the search descends to denser layers and explores a bounded candidate set near the query. Retaining more candidates generally improves recall at additional query work; adding graph connections costs memory and construction work. Tuning must include filtered queries and updates, not only unfiltered reads.
An inverted-file (IVF) index offers another tradeoff: train a set of coarse clusters, assign vectors to lists, and probe selected nearby lists at query time. Searching too few lists can omit the true neighbors. Product quantization is a separate compression technique that represents vector subvectors with compact codes; it can save memory while introducing distance error. Index navigation and numeric compression are different sources of approximation.
06Hybrid search, reciprocal rank fusion, and reranking
| Retrieval approach | Useful query | Benefit | Limit |
|---|---|---|---|
| Keyword/inverted index | Exact IDs, names, and required terms | Clear lexical matches and controllable term rules | Different wording may miss relevant documents |
| Exact vector search | Similar meaning in a small eligible collection | Finds exact neighbors under the chosen metric | Exact scoring or safely pruned search can be costly; metric relevance is not truth |
| Approximate vector search | Similarity over a large collection | Lower search work and latency | Can miss neighbors; filtering affects recall |
| Hybrid retrieval plus reranking | A mix of precise terms and paraphrases | Broader candidates and more careful final ordering | Extra compute and tuning; missing candidates remain missing |
A simple hybrid strategy runs lexical and vector retrieval, deduplicates by document or chunk identity, and fuses their ranked lists. Do not add arbitrary raw scores without calibration: a BM25 score of 12 and a cosine score of 0.8 have different scales.
One way to avoid incompatible score scales is to combine each candidate’s position in the retrieved lists. Reciprocal rank fusion gives larger contributions to higher-ranked candidates and adds the contributions across lists. It does not require BM25 and cosine scores to mean the same thing.
Reciprocal rank fusion uses each item's rank, for example a contribution of 1/(60 + rank) from each list. If D1 is rank 1 in vector search and rank 4 in lexical search, its combined contribution is 1/61 + 1/64 ≈ 0.0320. The constant 60 is an illustrative choice, not a universal best setting. A reranker can then compare the query with a bounded candidate set more carefully, at additional latency and compute cost.
Deduplicate overlapping chunks, diversify where the task requires distinct sources, and preserve exact-match boosts for identifiers. The final page should contain useful evidence, not ten slightly different chunks of the same paragraph. Decide ranking behavior with evaluated queries, not the sophistication of the algorithm name.
07Precision, recall, index freshness, and authorization
Precision asks what fraction of returned documents are relevant. Recall asks what fraction of all relevant eligible documents were returned. The @k notation evaluates only the first k results, so both metrics need an explicit cutoff and a labeled set of relevant documents.
Assume a labeled query has five relevant authorized documents. The returned top five contain three of them. Precision@5 is 3/5 = 60%; recall@5 is 3/5 = 60% in this example. If there were ten relevant documents instead, precision would remain 60% but recall would be 30%. Rank-sensitive measures such as nDCG also value putting highly relevant results near the top.
Filled green squares are relevant results returned. White squares are relevant documents missed. Orange squares are irrelevant results returned.
Remember: Precision asks “of what I returned?” Recall asks “of everything relevant?”
Read the diagram
- Count the 8 hits, 12 misses and 2 irrelevant results.
- Precision is 8 relevant returned divided by 10 returned = 80%.
- Recall is 8 relevant returned divided by 20 relevant = 40%.
Try from memoryIf all 20 relevant documents were returned along with 80 irrelevant ones, what would the scores be?
Recall would be 100% (20/20), while precision would be 20% (20/100).
Measure how long indexing, deletions and permission changes take, alongside p95 latency, empty results and cost. If revocation must take effect immediately, old index metadata cannot be the only access check. Track document versions, propagate deletion markers and check current permission before returning content. Build and validate a replacement index separately, then switch readers while retaining a rollback option. Updating the live index piece by piece can mix incompatible versions.
Start with the simplest search setup that meets measured needs. PostgreSQL full-text search and pgvector can keep search close to source records and permissions; measure exact vector search first. Add HNSW or IVFFlat when the speed benefit justifies their recall and resource costs. Filtering approximate results may leave too few matches, while searching further costs work. A separate service such as Elasticsearch or Azure AI Search can scale search independently, but its copied index still needs a freshness and access-control policy.
An index migration must move a compatible set of components together: query embedding model, stored embeddings, analyzer, chunking and ranking configuration must remain compatible. Record the serving generation on each request and evaluate the replacement on the same relevance and permission tests before switching traffic.
Precision and recall count useful results but do not distinguish where they appear within the evaluated list. Moving the best answer from first to fifth can make the experience worse without changing either count. Rank-sensitive measures evaluate that ordering; choose one that reflects whether the user needs a first useful answer or a useful result list.
Mean reciprocal rank (MRR) measures how early the first relevant result appears. For each query, use 1 / rank of its first relevant result, or zero if none appears within the evaluation cutoff; then average across queries. First hits at ranks 1, 4 and absent give (1 + 0.25 + 0) / 3 ≈ 0.417. MRR suits “find one good answer” tasks but ignores the quality of later results.
Normalized discounted cumulative gain (nDCG) sums graded relevance with lower weight at later ranks, then divides by the ideal ordering’s score at the same cutoff. It measures the quality of the ranked list, rather than only the first hit. State relevance labels, cutoff and the convention for queries with no relevant documents; do not compare scores from different evaluation sets as though they were interchangeable.
Practise the interview questions
Say your answer aloud before opening the model answer. Then answer the follow-up and compare the reasoning.
What is an inverted index? If reset maps to {D2,D4} and access to {D1,D4}, how does reset AND access execute?
Reveal a model answer
An inverted index maps a term to the documents containing it. Here reset maps to D2 and D4, while access maps to D1 and D4. Intersecting the posting lists returns D4 without scanning every document body. Positions support phrases and term statistics support ranking.
Interviewer follow-up
How is that different from vector retrieval?
Reveal the follow-up answer
Vector retrieval compares compatible numeric embeddings under a similarity measure and can match related wording without identical terms. It does not replace exact identifier fields or prove that a document is correct or authorized.
What the answer must demonstrate: Build the two lists and distinguish lexical matching from similarity.
When does vector search help?
Reveal a model answer
“It helps retrieve semantically related wording, such as lost phone matching authenticator recovery. It is weaker for some precise identifiers and does not establish truth or permission, so I evaluate it alongside lexical search and metadata filters.”
Interviewer follow-up
Can I change embedding models without rebuilding vectors?
Reveal the follow-up answer
Only with an explicitly compatible representation contract. Otherwise stored and query vectors no longer share a meaningful space and need migration.
What the answer must demonstrate: Similarity is a retrieval signal.
What does approximate nearest-neighbor search trade away?
Reveal a model answer
Approximate search can miss neighbors that an exact result would include, in exchange for less work on suitable workloads. I compare it with an exact baseline under the same metric and eligibility filters, then tune latency, memory and recall together. Exactness does not require a full scan if an index can safely prove which candidates cannot win.
Interviewer follow-up
Does 99% neighbor recall imply 99% useful answers?
Reveal the follow-up answer
No. It measures approximation relative to the chosen vector metric, not whether the model or document collection captures user relevance.
What the answer must demonstrate: Separate approximation quality from semantic quality.
Estimate raw storage for ten million 768-dimensional float32 vectors.
Reveal a model answer
“Each vector is 768 × 4 = 3,072 bytes. Ten million require 30.72 GB in decimal units before graph links, metadata, text, and replicas. I would size those separately and benchmark any quantization loss.”
Interviewer follow-up
Does adding two replicas double or triple total copies?
Reveal the follow-up answer
Two additional replicas plus the original means three copies; clarify terminology before multiplying.
What the answer must demonstrate: Keep units and overhead explicit.
Why not add a keyword score directly to a cosine score?
Reveal a model answer
“Their scales and distributions differ. I can calibrate a learned combination or start with rank fusion, then evaluate. Reciprocal rank fusion uses positions in each result list and avoids pretending unlike raw scores have the same meaning.”
Interviewer follow-up
What does a reranker change?
Reveal the follow-up answer
It spends more compute comparing the query with a smaller candidate set; it cannot recover a relevant document that never became a candidate unless another retrieval stage adds it.
What the answer must demonstrate: Candidate recall bounds reranking.
Why can filtering the final top twenty return no useful result?
Reveal a model answer
“All twenty may belong to another tenant even though relevant authorized documents exist deeper in the collection. I apply an eligible-document retrieval strategy and evaluate selective filters. In every case I enforce authorization before content leaves the trusted retrieval boundary.”
Interviewer follow-up
Can filtering only displayed citations secure an assistant?
Reveal the follow-up answer
No. Unauthorized snippets may already have entered its context and influenced the answer.
What the answer must demonstrate: Distinguish candidate starvation from data exposure.
Three of five returned documents are relevant; ten relevant documents exist. What are precision and recall?
Reveal a model answer
“Precision@5 is 3/5, or 60%. Recall@5 is 3/10, or 30%. I also measure ranking quality because users often inspect only the first results.”
Interviewer follow-up
What query set should the evaluation include?
Reveal the follow-up answer
Realistic exact IDs, paraphrases, rare cases, language variation, empty-result cases, and permissions—not just easy queries chosen to flatter the system.
What the answer must demonstrate: Use the correct denominator.
A document was deleted but remains searchable. How do you fix the contract?
Reveal a model answer
Send versioned deletion markers to the index and measure cleanup delay. To block access immediately, do not rely only on that delayed index update. Check current source permissions for the exact document and policy version before fetching its body or sending it to a model. Fetch that fixed content version; if versions differ, check permission again. Apply the promised access check when releasing the response too.
Interviewer follow-up
How would you migrate the embedding model?
Reveal the follow-up answer
Build and validate a versioned replacement index with matching query embeddings, switch traffic deliberately, and retain a compatible rollback path.
What the answer must demonstrate: Treat freshness and authorization as explicit guarantees.
Blank-page exercise · 20 minutes
Build the answer yourself
Build search over ten million support documents for multiple tenants. Explain lost-phone recovery, an exact error code, and an immediate permission revocation.
- Show postings and one vector-similarity example.
- Estimate vector memory and name extra overhead.
- Choose and evaluate candidate retrieval and ranking.
- Trace permissions, version changes, and delete propagation.
Check that each component and design decision follows from your requirements and workload.
Recall the key ideas
Answer from memory before opening each card. Explain why the choice works and what it costs. Revisit missed cards tomorrow.
Keyword search and vector retrievalThe search index finds a relevant document. May the service return it immediately?Recall first, then reveal
Only after checking that the caller may read the exact content version being returned. Old index permissions may no longer be valid.
Find candidates → check access → return permitted content.
Return to lessonKeyword search and vector retrievalLexical / vectorRecall first, then reveal
Lexical matches terms; vectors match learned similarity; hybrid combines evidence.
Exact words and related meaning.
Return to lessonKeyword search and vector retrievalPrecision / recallRecall first, then reveal
Precision: relevant among returned. Recall: returned among all relevant.
Precision: how useful are the results? Recall: how much was found?
Return to lessonFinal revision
Summary and interview notes
Search uses an index copied from source data. Define relevance, update delay and access rules separately. Measure exact keyword/vector search first; add approximation when its savings justify the missed results. Check access to the exact content version before passing it to a reranker or assistant.
Remember these points
- An inverted index maps terms to postings; BM25 combines rarity, saturating frequency and document-length normalization.
- Embedding model and metric must be compatible; cosine measures direction, not truth or permission.
- Exact search is a result guarantee; ANN navigation and vector compression can each introduce different errors.
- Rank fusion combines candidate lists, while a reranker cannot recover a relevant item that was never retrieved.
- Precision, semantic recall, ANN neighbor recall and authorization correctness measure different properties.
Interview tips
- Build a tiny posting intersection and calculate one similarity before naming a search engine.
- Compare ANN against an exact eligible-set baseline, including very selective tenant filters.
- Trace one permission change through index, content fetch, reranker and final response with version checks.
Important qualifications
- Ten million 768-dimensional float32 vectors consume 30.72 decimal GB before index, metadata and replica overhead.
- Changing an embedding model can require a new compatible index and query-serving bundle; matching vector length is insufficient.
- A signed or cached search hit never grants permanent access to the source document.
Technical references
- Elastic: how full-text search worksAnalysis, inverted indexes, and lexical ranking.
- Azure hybrid searchA concrete implementation of lexical/vector retrieval and rank fusion.
- Azure vector query filtersFilter placement affects eligible-candidate recall and query cost.
- Microsoft secure multitenant RAGPermission boundaries before retrieved content enters model context.
- Elastic: Similarity settingsBM25 saturation and length normalization; no universal score threshold is implied.
- Malkov and Yashunin: HNSWPrimary hierarchical graph-search mechanism.
- pgvector documentationExact baseline, HNSW/IVFFlat alternatives and filtered approximate-query limits; no latest-version claim is made.
- Faiss: Research foundationsOfficial index of underlying IVF and product-quantization research; distinguishes navigation from lossy vector compression.
- Elasticsearch ranking evaluation metricsOfficial definitions of reciprocal-rank and discounted-gain evaluation; the three-query arithmetic is illustrative.
Practice marks stay in this browser.