Embeddings & Retrieval · 90 minutes
Explain semantic and exact-match retrieval
Explain how embeddings and exact-term matching find candidates for a query, and why the top result is a ranking signal rather than a verified answer.
1.5 h
Used in interview rounds:
Technical Screen (Easy)Overview
Learn how an application finds relevant information before it shows search results or generates an answer. This guide introduces the vocabulary of retrieval interviews: embeddings, similarity, lexical and semantic search, top-k results, metadata filters, and the limits of retrieval scores.
Study time: 90 minutes
Interview format: Conceptual technical screen with a small ranking exercise
By the end you can
- Explain what an embedding is, and what it is not
- Compute cosine similarity for small vectors and check whether a higher or lower score ranks first
- Choose between lexical, dense, and hybrid search for a given type of query
- Explain how top-k, metadata filters, and access rules shape the returned set
- Explain why a retrieval score is a ranking signal, not confidence, relevance, or permission
Prerequisites
Helpful background: Basic programming and elementary arithmetic are enough. LLM Foundations is useful context but not required.
This topic finds and ranks candidates. RAG & Data Pipelines covers ingestion, grounding, citations, and the document lifecycle.
What retrieval produces
Retrieval selects candidate items from a collection for a query. The collection might contain help articles, code snippets, product descriptions, or document passages. A result usually contains an item identifier, a ranking score, and enough metadata to locate or display the item.
Suppose a learning platform receives the query “how to stop duplicate requests in React”. Its search might retrieve a lesson about request deduplication even when the lesson title uses different words. The retrieved lesson is a candidate source. Whether it actually solves the learner's problem still needs assessment.
Retrieval is also part of RAG, where selected material is supplied to a generator. This topic focuses on finding and ranking candidates. The RAG & Data Pipelines topic covers ingestion, grounding, citations, and the document lifecycle in greater depth.
Embeddings represent content numerically
An embedding model converts an input into a vector of numbers. A text embedding model is trained so that useful relationships between texts can be reflected in vector comparisons. The exact relationship depends on the training objective and model.
A vector can have hundreds or thousands of dimensions. Individual coordinates usually have no simple human-readable meaning. An embedding is not a list of keywords, and it is not a lossless encoding from which the original document can reliably be reconstructed.
Text with similar meaning may receive similar vectors, but the result can still confuse negation, identifiers, dates, or specialized vocabulary. Test the intended domain rather than assuming that semantic similarity guarantees relevance.
Query and document representations must be compatible
Stored document vectors and incoming query vectors must come from compatible representations. Equal dimensionality alone does not establish compatibility. Different models can assign completely different meanings to their coordinates.
Some retrieval models expect different instructions or encoders for queries and documents. Follow that model's supported query and document workflow. Store the embedding configuration with the index so a later query cannot accidentally use a different representation.
When the embedding model changes, document vectors generally need to be regenerated into a compatible index. Changing only the query encoder can make rankings meaningless even when the search engine accepts the vector length.
Similarity and distance
Three common comparisons are dot product, cosine similarity, and Euclidean distance. Dot product multiplies matching coordinates and sums them. Cosine divides the dot product by the two vector lengths, emphasizing direction. Euclidean distance measures straight-line separation.
Higher similarity usually ranks first, while lower distance usually ranks first. Verify the score convention of the actual engine. Some APIs return transformed distances, so the displayed number may not be the mathematical quantity named in a textbook.
For nonzero unit-length vectors, dot product equals cosine similarity. Normalization is therefore a meaningful configuration choice. Use the metric expected by the representation model, and apply normalization consistently.
A small numerical example
Predict the outcome
Rank three vectors by cosine similarity
Let the query be [1, 0]. All three document vectors below are unit vectors, so dot product and cosine similarity give the same score. Compute each score and rank the documents before you reveal the answers. These vectors are teaching fixtures: their two axes do not represent real language features.
| Document | Vector | Cosine similarity to [1, 0] | Rank |
|---|---|---|---|
| A | [1, 0] | ? | ? |
| B | [0.8, 0.6] | ? | ? |
| C | [0, 1] | ? | ? |
Lexical and semantic search
| Approach | Main signal | Often useful for | Potential weakness |
|---|---|---|---|
| Lexical search | Matching terms and their importance | Error codes, names, exact phrases | Paraphrases without shared terms |
| Dense semantic search | Similarity between learned vectors | Natural-language descriptions and paraphrases | Exact identifiers or subtle factual distinctions |
| Hybrid search | Evidence from multiple retrieval methods | Collections with varied query types | Additional tuning and evaluation |
BM25 is a common lexical ranking method. It considers factors including term frequency, term rarity, and document length. A basic term-overlap script is a useful teaching baseline, but it does not reproduce BM25.
Hybrid retrieval combines results from different methods. A useful candidate might appear in one method's results even when the other misses it. Combining methods still requires evaluation because additional candidates can introduce irrelevant material.
Indexes, top-k, and exact search
An index is a data structure used to search a collection efficiently. A vector index searches stored vectors. A full-text index supports lexical retrieval. A database may provide both capabilities alongside metadata storage.
Top-k means returning up to k ranked results. It does not mean that k relevant results exist. If the collection has no useful answer, nearest-neighbor search can still return the closest available vectors.
Exact vector search compares the query against every eligible vector according to the selected metric. Approximate nearest-neighbor (ANN) search trades some exactness for efficiency. Its effect depends on the index, configuration, data, and query distribution.
Metadata filters
Metadata can restrict results to a language, tenant, document type, or current publication state. For example, a learning platform may limit a query to published React lessons that the current learner can access.
Authorization constraints must be applied by trusted application logic. A query string should not grant access to private records. Filtering only after a very small candidate set is selected can also leave fewer than k results, even when additional eligible items exist elsewhere in the collection.
A search score expresses a ranking signal. It does not establish permission to display an item.
Documents and passages
A long document can be represented as smaller passages. Each passage should retain its parent identifier and useful context. A passage about cancellation may be useful even when the entire document covers many unrelated API features.
Passage boundaries affect retrieval. A fragment that omits the name of the function or the condition under which advice applies can be difficult to retrieve and interpret. Detailed chunking strategies belong in RAG & Data Pipelines, but candidates should recognize their effect on search quality.
Worked search scenario
Worked example
A small help center has four articles.
| ID | Article |
|---|---|
| D1 | Reset your password using the recovery link |
| D2 | Resolve E104 when a login token expires |
| D3 | Download a billing invoice |
| D4 | Change your profile display name |
Consider three queries against this collection: “I forgot the secret I use to sign in”, “E104”, and “shipping times”. The scenario asks for a reasoned prediction about which retrieval signal would find a useful article. It makes no claim about an actual embedding model's output.
Predict what each query should retrieve
Predict the outcome
Predict what each query should retrieve
For each query against the four articles in the worked scenario, decide which retrieval signal is likely to find a useful article and what a good result looks like, then reveal the answers.
| Query | Useful signal | Good result |
|---|---|---|
| I forgot the secret I use to sign in | ? | ? |
| E104 | ? | ? |
| shipping times | ? | ? |
Completion checklist
- Explain an embedding without treating it as stored factual knowledge.
- Rank the three numerical vectors correctly.
- Distinguish similarity, distance, and probability.
- Explain why exact terms and paraphrases need different evaluation cases.
- Describe how top-k, filters, and access rules affect the returned set.
Sources
- Sentence Transformers semantic search Explains embedding-based search and query and document encoding.
- Faiss metric types and distances Explains inner product, Euclidean distance, and cosine search on normalized vectors.
- Sentence Transformers retrieve and rerank Describes candidate retrieval followed by cross-encoder reranking.
- Elastic reciprocal rank fusion Documents combining ranked lists through reciprocal ranks.
The vectors, articles, queries, scores, timing budgets, exercises, and rubrics are original synthetic teaching material. They do not describe the measured performance of a named model or search engine. Study times and readiness thresholds are editorial estimates. Check the chosen embedding model's and search engine's current documentation before implementation.
Related on CodeSnatch
Lessons, problems, and articles that build the skills this question uses.
Community article
Explains what an embedding is and why cosine is common, with a section on where keyword search still wins.
Practice problem
Practice ranking by Euclidean distance and keeping the k nearest, the exact search this guide describes.
System Design
Its per-user search section shows an inverted index with BM25 ranking, the exact-term side of retrieval.
AI Engineering
Follows retrieved passages into a generated answer and shows why citing a real document does not make it right.
AI Engineering
Takes access filters from the signed-in session on every turn and decides when a turn should not retrieve.
Practice the interview question
Answer it in your own words before you look at the reference answer.
