Forward Deployed EngineeringAI EngineeringSemantic Search
What are embeddings, and how do they make semantic search work?
Question 21 of 73 · Updated
On this page
- Interview-ready answer
- 1. What does an embedding represent?
- Token embeddings versus document embeddings
- 2. Intuitive example: meaning rather than exact words
- 3. Cosine similarity, dot product and Euclidean distance
- Dot product
- Cosine similarity
- Euclidean distance
- 4. How semantic search works end-to-end
- Indexing
- Query time
- 5. Semantic search versus keyword search
- 6. Tested Python example: exact semantic ranking
- 7. Vector indexes and search at scale
- 8. Choosing an embedding model
- 9. How to evaluate semantic search
- 10. Practical FDE scenario
- 11. Production failures and trade-offs
- Likely interviewer follow-ups
Interview-ready answer#
An embedding is a learned numerical representation of an input, such as a word, sentence, document or image, in a vector space. An embedding model maps inputs into vectors of a fixed dimension so that inputs related under its training objective tend to have similar representations.
Semantic search uses this property to retrieve information by meaning rather than relying only on exact word matches. For example, a search for "I cannot sign in" may retrieve an article titled "Reset your password" even if the query and article share few keywords. During indexing, we embed document chunks and store their vectors with source metadata. At query time, we embed the query using a compatible model and retrieve the nearest document vectors using cosine similarity, dot product or another supported distance metric.
As an FDE, I would choose an embedding model and indexing strategy based on customer-domain retrieval evaluations, not only generic benchmark scores. I would combine semantic retrieval with keyword search where exact identifiers matter, enforce document permissions before exposing results, and measure retrieval quality, latency, freshness and cost. Embeddings improve candidate retrieval; they do not guarantee relevance, factual accuracy or authorization.
1. What does an embedding represent?#
A text embedding is typically a dense vector of real-valued numbers, for example a vector with 384, 768 or 1,536 dimensions, depending on the model and its configuration. These are examples of possible dimensions, not universal defaults.
A tokenizer first converts text to token IDs. A neural encoder processes those tokens, and a pooling or other readout mechanism can produce a single vector representing the input. Some models use different mechanisms, including multiple vectors per input. A dense single-vector retrieval model is the focus here.
Unlike a hand-designed feature vector, individual embedding dimensions generally do not correspond to named concepts such as "password", "positive sentiment" or "finance". Meaningful patterns emerge across the vector through training.
For retrieval, models often learn from query-document pairs or related examples. Contrastive objectives can encourage relevant query-document pairs to have high similarity and unrelated or hard-negative pairs to have lower similarity. The exact objective, training corpus, architecture and input formatting vary.
Token embeddings versus document embeddings#
| Representation | Purpose |
|---|---|
| Token embedding | Maps a token ID to an initial learned representation inside a model |
| Contextual token representation | Represents a token in its surrounding context |
| Sentence or document embedding | Represents an entire input or passage for comparison, clustering or retrieval |
| Multi-vector representation | Retains several representations per input, enabling finer-grained matching at additional cost |
An LLM's token embedding table is not automatically a suitable document search model. Use a representation designed or evaluated for the retrieval task.
2. Intuitive example: meaning rather than exact words#
Suppose a support knowledge base contains three documents. For illustration, imagine the vectors below in a two-dimensional space. They are hand-picked toy vectors, not real embedding model outputs.
| Input | Illustrative vector |
|---|---|
| Query: I cannot sign in | (1, 0) |
| Reset your password | (3, 1) |
| Password recovery instructions | (2, 1) |
| Download your invoice | (0, 1) |
The first two documents point in a direction close to the query. The invoice document points in a perpendicular direction. A cosine-based search ranks the password-related documents higher.
Real embeddings live in much higher-dimensional spaces. A two-dimensional illustration is useful for explaining similarity, but actual relevance is learned and must be evaluated. A high similarity score does not prove that the document answers the question.
3. Cosine similarity, dot product and Euclidean distance#
Dot product#
Multiply matching coordinates and add the products.
For q = (1, 0) and d = (3, 1), the dot product is 1 × 3 + 0 × 1 = 3.
Dot product reflects both vector direction and magnitude. Some retrieval models are trained to use it directly, and the magnitude may convey useful information. Do not normalize such vectors without checking the model's intended scoring method.
Cosine similarity#
Cosine similarity divides the dot product by the product of the vector norms:
It measures directional alignment and is defined for nonzero vectors. Its mathematical range is −1 to 1 for real-valued vectors.
For q = (1, 0) and d = (3, 1), cosine similarity is 3 / sqrt(10), approximately 0.9487.
| Candidate | Cosine similarity | Dot product |
|---|---|---|
| Reset your password: (3, 1) | 0.9487 | 3 |
| Password recovery: (2, 1) | 0.8944 | 2 |
| Download your invoice: (0, 1) | 0.0000 | 0 |
A cosine score of 0.9487 is not a 94.87% probability that the passage is relevant. Scores and usable thresholds vary by model, corpus and task.
Euclidean distance#
Euclidean distance measures the straight-line distance between vectors. For unit-normalized vectors u and v:
Consequently, maximizing cosine similarity, maximizing dot product and minimizing Euclidean distance produce equivalent rankings for unit-normalized vectors, apart from ties and numerical differences. Without normalization, the rankings can differ.
Use the metric recommended for the embedding model and supported by the vector index. Check whether the database returns a similarity to maximize or a distance to minimize; a cosine-distance result is not necessarily a cosine-similarity score.
4. How semantic search works end-to-end#
Indexing#
Parse documents, split them into meaningful chunks, and encode each chunk. Store vectors together with document identifiers, source versions, chunk locations, access metadata and embedding model/configuration identifiers. Persist or reference the original passage so it can be retrieved and cited.
Query time#
Authenticate the user and determine their permitted data scope. Encode the query in the same compatible vector space as the documents. Search within authorized candidates, retrieve the corresponding source passages, and optionally rerank them with a model that considers the query and passage jointly.
An asymmetric retrieval model may use distinct query and document encoders or task-specific prefixes. They must be trained or configured to produce mutually compatible vectors. Identical vector dimensionality alone does not make embeddings from unrelated models comparable.
If this is part of RAG, the selected passages become context for a generator. The generator still needs separate evaluation for answer accuracy, evidence support and abstention.
5. Semantic search versus keyword search#
| Dimension | Keyword retrieval (e.g., BM25) | Dense semantic retrieval |
|---|---|---|
| Main signal | Lexical term matching and term statistics | Learned vector similarity |
| Strong cases | Exact identifiers, error codes, product names, rare terms | Paraphrases, related concepts, vocabulary mismatch |
| Typical weakness | Misses relevant documents with little lexical overlap | May confuse semantically similar but distinct facts or identifiers |
| Infrastructure | Inverted index | Vector index, embedding computation |
| Explainability | Matched terms are often easy to inspect | Similarity is less directly interpretable |
For example, a semantic search may retrieve password reset instructions for "I cannot log in", while keyword search is particularly useful for an exact error code such as AUTH-1042. Neither approach always wins.
Hybrid retrieval combines candidates from both search methods, often with rank fusion or a calibrated scoring approach. A reranker can then score the strongest candidates with richer query-passage interactions. Do not blindly add raw BM25 scores and cosine similarities: their scales and distributions differ.
6. Tested Python example: exact semantic ranking#
This educational example assumes vectors have already been generated. It implements cosine similarity and brute-force ranking without calling a model or an external API.
PYTHONimport math def cosine(a,b): if not a or len(a)!=len(b) or any(not math.isfinite(x) for x in (*a,*b)): raise ValueError('Nonempty finite vectors of equal dimension required') na,nb=math.hypot(*a),math.hypot(*b) if not na or not nb or not math.isfinite(na) or not math.isfinite(nb): raise ValueError('Finite nonzero norms required') return max(-1.0,min(1.0,math.fsum((x/na)*(y/nb) for x,y in zip(a,b)))) def rank(query, documents, k): if k<1: raise ValueError('k must be positive') scores=[(doc_id,cosine(query,vec)) for doc_id,vec in documents.items()] return sorted(scores,key=lambda item:(-item[1],item[0]))[:k] docs = { 'reset': (3,1), 'password': (2,1), 'invoice': (0,1), 'opposite': (-1,0), } print(rank((1,0),docs,3)) # reset: 0.948683..., password: 0.894427..., invoice: 0.0
The inputs are finite numeric sequences, documents maps unique string IDs to vectors, and k is a positive integer. The example rejects zero vectors and dimension mismatches. Ties in computed scores are broken by document ID. An empty corpus returns an empty result.
For N documents with d dimensions, computing every score takes O(Nd) time; sorting all results adds O(N log N) time and O(N) score storage. The similarity helper uses O(d) temporary space because it constructs a tuple for input validation. Production systems can use pre-normalized matrices, batched operations, top-k selection and specialized indexes.
Local verification: 15,387 test cases passed: 15,376 ordered pairs of nonzero integer 3D vectors with coordinates from −2 through 2, six invalid-vector cases, and five ranking cases covering expected ordering, empty corpus, ties, invalid k and oversized k. Similarity was compared against an independent dot-product/norm calculation. The example uses synthetic vectors; these checks do not validate any actual embedding model's semantic quality, ANN recall or live infrastructure.
7. Vector indexes and search at scale#
Exact search is a useful correctness baseline. It compares the query against every eligible vector. At large scale, approximate nearest-neighbor (ANN) indexes can reduce search work while trading some exact-neighbor recall for speed.
| Index approach | Core idea | Trade-off |
|---|---|---|
| Flat / exact | Score every eligible vector | Exact ranking under the metric; higher query work as the corpus grows |
| HNSW | Traverse a hierarchical proximity graph | Often strong latency/recall balance; graph memory, build cost and update behavior matter |
| IVF | Assign vectors to clusters and probe selected clusters | Fewer vectors scanned; requires tuning cluster count and probes |
| Product quantization | Compress vectors using subvector codebooks | Lower memory and bandwidth; approximation error can reduce ranking quality |
These techniques can be combined. For HNSW, search breadth and graph construction settings influence recall, speed and memory. For IVF, increasing the number of probed clusters generally examines more candidates and may improve recall at higher cost. Actual behavior depends on the implementation and data distribution.
Metadata filtering must be considered during index selection. A naive global ANN search followed by tenant filtering can both waste the candidate budget and create unsafe intermediate exposure if the application boundary is poorly designed. Use supported filtered search or appropriate tenant partitioning, enforce permissions again before returning source text, and evaluate selective-filter workloads.
A raw float32 vector payload of one million vectors with 768 dimensions is 3,072,000,000 bytes (about 2.86 GiB), before graph structures, metadata, text, replicas and other overhead. This is an illustrative capacity calculation, not a complete storage or cloud-cost estimate.
8. Choosing an embedding model#
I would compare candidate models using the customer's actual search workload:
- Domain fit: Technical documents, legal language, customer support, code, and multilingual text have different relevance patterns.
- Input limits and formatting: Use the intended tokenizer, query/document prefixes, pooling, normalization and truncation behavior.
- Vector dimension and metric: Evaluate the quality, memory and compute implications of the supported representation.
- Latency and throughput: Measure query encoding separately from vector search and reranking. Consider batch embedding for ingestion.
- Deployment constraints: Data residency, confidential inputs, model licensing, endpoint availability, retention and cost.
Freeze the model revision and preprocessing configuration for reproducible indexing. When changing embedding models, rebuild or migrate to a separate compatible index and validate the new query path before switching traffic. Avoid mixing incomparable vector spaces in the same search. Retain rollback capability while ensuring deleted or revoked content cannot reappear.
9. How to evaluate semantic search#
Build a labeled set of customer questions and relevant source passages. Include paraphrases, exact identifiers, multilingual requests, rare domain terminology, negation, multi-evidence questions and cases with no authorized relevant document.
| Metric | What it measures |
|---|---|
| Recall@k | Fraction of required relevant evidence retrieved among the first k results |
| MRR@k | How early the first relevant result appears, averaged across applicable queries |
| nDCG@k | Ranking quality with graded relevance |
| ANN recall@k | Overlap with the exact nearest-neighbor top k under the same metric and eligible corpus |
| Final-context recall | Evidence retained after reranking, expansion and context packing |
| Operational metrics | Query encoding latency, retrieval p95, throughput, indexing lag, memory and cost |
ANN recall and semantic relevance are not the same. An approximate index can perfectly reproduce the embedding model's nearest neighbors even if those neighbors are not the correct evidence. Measure both independently.
Compare lexical, dense and hybrid baselines using the same corpus, permission rules, test questions and candidate/context budgets. Evaluate no-answer cases separately, and calibrate rejection or escalation thresholds from labeled results rather than assuming a universal cosine threshold. For RAG, additionally evaluate factual correctness, groundedness and citations.
10. Practical FDE scenario#
Imagine an enterprise support team searching a knowledge base containing login instructions, API error documentation and product policies in multiple languages. Operators frequently describe problems in different words from the official documents.
I would first inspect query logs with appropriate permission and collect a representative relevance-labeled dataset. I would index structure-aware passages with document version and access metadata, evaluate a dense embedding model alongside a lexical baseline, and measure which failures each approach rescues.
If dense retrieval handles paraphrased login questions but misses exact error codes, I would test hybrid candidate generation and reranking. If performance degrades only for restrictive permission filters, I would inspect index filtering and candidate budgets. If the correct passage is found but the final RAG answer is wrong, I would inspect context construction and generation instead of changing embeddings again.
This is a hypothetical deployment example, not a measured customer outcome.
11. Production failures and trade-offs#
| Symptom | Likely issue and response |
|---|---|
| Unrelated but superficially similar results | Inspect model relevance, hard negatives, chunk boundaries and reranking |
| Exact identifiers missing | Add or improve lexical retrieval and structured filters |
| Long documents lose key details | Respect embedding input limits; use structure-aware chunks |
| Search breaks after model upgrade | Check vector-space compatibility and index version |
| Search leaks restricted documents | Enforce authorization at retrieval and source fetch; test negative and positive access cases |
| Stale search results | Monitor source synchronization, deletion and re-embedding |
| Low ANN recall | Compare with exact search and tune index/search parameters |
| High query latency | Profile query encoding, filtered retrieval, network and reranking separately |
Embedding vectors are derived customer data, not inherently anonymous or safe to expose. Restrict access, protect storage and transport, and apply retention and deletion policies to vectors, original text, metadata and caches. Access control is an application and infrastructure responsibility; semantic similarity must never be used as a permission check.
Likely interviewer follow-ups#
Why not use keyword search alone? It is strong for exact terms but can miss relevant paraphrases. Dense retrieval can bridge vocabulary mismatch; hybrid retrieval often complements both.
What does a high cosine score mean? The vectors are directionally aligned. It does not guarantee relevance, factual truth or a calibrated probability.
Can I use two different embedding models for query and documents? Only when their outputs are designed to be compatible, such as a paired query/document encoder. Matching dimension is insufficient.
What is the difference between an embedding model and a reranker? A typical dense retriever encodes query and documents independently for scalable candidate search. A cross-encoder reranker considers them jointly and can improve relevance at higher per-candidate cost.
How do you decide whether HNSW is working well? Compare ANN results with exact search under the same metric and access filters, and evaluate latency, memory and downstream labeled relevance.
Why can semantic search fail on negation or an exact product code? Embeddings can emphasize broad semantic relatedness while missing a critical distinction. Add appropriate lexical/structured retrieval, reranking and task-specific evaluation.
References
- 1.
- 2.
- 3.
- 4.
- 5.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models