Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Embeddings vs keyword search: meaning or exact terms?
Search for an exact error code and a pure embedding index can return five semantically-similar-but-wrong results. Search in plain language for something that shares no words with the right document and pure keyword search finds nothing. Neither failure is rare — which is why almost no serious system picks only one.
The one distinction that decides everything
Keyword search (classically BM25) matches on lexical term overlap, weighted by term frequency and document length — it finds documents that literally contain your words. Embedding search converts both query and documents into vectors and matches on geometric closeness — it finds documents about the same meaning, even if they share zero words with the query.
Does the right answer depend on an exact token — an error code, a SKU, a version number, a name? Keyword search. Does it depend on meaning that could be phrased many different ways? Embeddings.
Head to head
| Dimension | Embeddings | Keyword Search |
|---|---|---|
| Matches on | Meaning | Exact terms / stems |
| Synonyms ("car" vs "automobile") | Handled naturally | Missed unless explicitly expanded |
| Exact codes, IDs, rare terms | Weak — can miss exact matches | Strong — this is its specialty |
| Explainability | Opaque similarity score | Exactly why it matched, visible |
| Index cost | Needs an embedding model + ANN index | Cheap inverted index, mature tooling |
| Typo / OOV tolerance | Naturally somewhat robust | Poor without fuzzy matching added |
| Classic failure | Missing an exact-term match | Vocabulary mismatch — right idea, wrong words |
When to use each
Reach for keyword search
- Exact-match-critical domains: log/error-code search, legal citations, SKUs
- Explainability matters — you must show why it matched
- Low-resource setups without embedding infrastructure
- Queries will share vocabulary with the documents
Reach for embeddings
- Natural-language queries over unstructured content
- "Find similar" or conceptual search
- Cross-lingual search
- Queries won’t share vocabulary with the documents
The answer is almost always "both, fused"
Hybrid search — running both a keyword index and an embedding index, then fusing the two ranked lists (commonly with reciprocal rank fusion) — is the modern default in production RAG systems, precisely because the two failure modes don't overlap. Embeddings recover queries with zero lexical overlap; keyword search recovers exact terms embeddings smooth over. Fusing them costs little beyond running both indexes, and closes each one's blind spot with the other.
If you're only going to build one retrieval path today, build keyword search first — it's cheaper, more explainable, and a known quantity. Add an embedding index once you've observed queries that share no vocabulary with your documents.
Why exact terms are embeddings’ real blind spot
The mechanical reason embeddings can lose to keyword search on exact terms isn't a training bug — it's what the representation is optimized for. An embedding model is trained to place semantically similar text near each other in vector space, which means it learns to treat near-synonyms and paraphrases as "close" on purpose. That same pressure that makes it good at meaning also smooths over the fine-grained token-level differences that make an exact-match query exact: v2.3.1 and v2.3.2 are extremely close in embedding space (they're nearly the same string, in nearly the same context), which is exactly wrong when the user needed the ONE document about the specific version with the bug, not "a document about roughly this version."
BM25 has no such smoothing — it's counting literal token overlap with frequency weighting, so it is, structurally, incapable of confusing "v2.3.1" with "v2.3.2" the way a vector-similarity match can. This is why the two methods aren't just "different," they fail in genuinely complementary ways: embeddings' strength (generalizing past exact wording) is mechanically the same property that causes its exact-match weakness.
The smoothing that lets embeddings find "the same idea, different words" is the identical mechanism that lets them blur "the same idea, different exact version" — you can't have one without risking the other from a single index.
A worked scenario: a dev-tool documentation search bar
Users of a developer tool's docs search bar type two very different kinds of queries. Natural questions like "why is my build slow" need semantic understanding — the right doc might be titled "Optimizing Compile Times" and share almost no words with the query, a case only embeddings handle well. But the same search bar also gets queries like the exact error string ERR_CONNECTION_RESET or a specific flag name, where the user needs the ONE doc that contains that exact token, and a pure embedding search risks surfacing several plausible-sounding-but-wrong pages about "connection issues" generally instead.
A hybrid retriever — BM25 for lexical precision, embeddings for semantic recall, fused into one ranked list — handles both query shapes from the same search bar, which is why it's the standard architecture rather than a compromise: neither index alone covers the actual distribution of real queries a documentation search bar receives.
Any search surface serving both natural-language questions and exact technical tokens (error codes, IDs, versions) needs both retrieval methods — the query mix, not a size threshold, is what decides.
The picture: two retrieval paths, one fused list
Worked example: BM25, cosine and fusion on three documents
Query: car repair. Three documents, each three words long. BM25 uses the Lucene-style IDF ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 = 1.2, b = 0.75. Every document has the average length and every matched term appears once, so the length and frequency factors both come out to exactly 1 and each matched term adds just its IDF. With N = 3: “car” is in one document, so IDF = 0.981; “repair” is in two, so IDF = 0.470. For the vector side, take illustrative 3-dimensional embeddings with axes [vehicle, fixing, other]: query [0.7, 0.7, 0.1], D1 [0.6, 0.7, 0.3], D2 [0.7, 0.6, 0.0], D3 [0.3, 0.8, 0.2]. Real models use hundreds to thousands of dimensions, and nobody labels them.
| Doc | Text | Query terms it contains | BM25 | Cosine | Rank: BM25 / vector | RRF, k = 60 |
|---|---|---|---|---|---|---|
| D1 | car repair shop | car, repair | 0.981 + 0.470 = 1.451 | 0.974 | 1 / 2 | 1/61 + 1/62 = 0.0325 |
| D2 | automobile maintenance guide | none | 0 (not returned) | 0.992 | — / 1 | 1/61 = 0.0164 |
| D3 | bike repair kit | repair | 0.470 | 0.905 | 2 / 3 | 1/62 + 1/63 = 0.0320 |
Three things the numbers show. First, BM25 weights rare words up: “car” is worth about twice as much as “repair” here only because fewer documents contain it. On a real corpus that is what makes an error code, which appears in a handful of documents, dominate the score. Second, D2 is the best match by meaning (0.992) and does not exist as far as BM25 is concerned, because it shares no token with the query. That is the vocabulary-mismatch failure, in one row. Third, look at the fused order: D1, D3, D2. Reciprocal rank fusion uses only positions, so a document in both lists beats one in a single list. A document at rank r in both lists outscores a rank-1 document in one list whenever 2/(60 + r) > 1/61, which holds for every r < 62. So agreement dominates. The win from hybrid here is that D2 is in the results at all. If the order among the top few matters, a reranker or a weighted fusion fixes that next.
Cost and trade-offs: what each index charges you
| Case | Time | Space | Why |
|---|---|---|---|
| BM25 inverted index | Walk the postings list of each query term; common terms cost more, rare terms are cheap | About one entry per (term, document) pair; compresses well | No model. Adding a document appends to postings. Every score is explainable term by term. |
| Exact vector scan | O(N · d) multiply-adds per query | N · d floats: 1M docs × 768 dims × 4 bytes = 3.07 GB | Exact top-k. Fine at modest N, and the baseline you measure ANN recall against. |
| ANN index (e.g. HNSW) | Sub-linear: visits a small fraction of the vectors | The vectors plus graph links per vector, ideally in RAM | Approximate: can miss a true neighbour. A search-breadth setting trades recall for latency. |
| Embedding the query | One model forward pass per query | The model, on your hardware or behind an API | Latency BM25 never pays. Cache the vectors of frequent queries. |
| Changing the embedding model | Re-embed the whole corpus | A second index while you switch over | Vectors from two models are not comparable. Keyword search has no equivalent cost. |
| Hybrid with RRF | Both searches, run in parallel, then an O(k) merge | Both indexes | Latency is roughly the slower of the two; the merge itself is trivial. |
The asymmetry is the point. Keyword search is cheap to build, cheap to update and easy to explain. Embedding search moves cost into a model and a memory-hungry index, and it adds a full rebuild every time you change the model. Hybrid pays both bills, which is why it is worth adding the second path only after you have seen the queries the first one fails.
Common mistakes
- Adding raw scores together
BM25 scores are unbounded and depend on corpus statistics (1.451 above; much larger on long queries), while cosine sits in
[−1, 1]. Summing them lets BM25 swamp the vector score on some queries and vanish on others. Fuse by rank (RRF), or normalise each list per query before you weight them. - Querying with a different model than the index
Encode the query with a new model and search vectors built by the old one, and nothing errors: the arrays have the same shape. The results are just quietly wrong. Store the model name and version with every vector, and re-embed the whole corpus on an upgrade rather than only new documents.
- One vector per long document
A single embedding for a 30-page document averages every topic in it into one point that is close to nothing in particular. Many embedding models also have a maximum input length and drop the text past it, often without a warning. Split documents into passages and embed each one.
- Trusting the default analyzer with codes
Keyword search matches the tokens the analyzer produced, not the string you typed. Analyzers lowercase, stem and split on punctuation, which can break an ID like
ERR_CONNECTION_RESETorv2.3.1into pieces that match other documents. Check how your exact tokens are indexed (search engines expose an analyze call for this) and keep a separate untokenized field for IDs. - Judging by a handful of hand-typed queries
Build a labelled set from your real query log and split it by query type: exact tokens versus natural language. Measure recall@k per slice. An overall average hides exactly the failure this page is about, because each method fails on a different slice and the slices are rarely the same size.
Where this shows up in production and interviews
- RAG retrieval
The retrieval step decides which chunks an LLM gets to read. Hybrid retrieval is the usual first stage, often followed by a reranker. A missed exact term here does not look like a search failure: the model answers fluently from the wrong document.
- One engine or two
Hybrid does not require two systems. Elasticsearch and OpenSearch run BM25 and vector k-nearest-neighbour search in the same engine, and Postgres has built-in full-text search alongside the pgvector extension. Pick the engine you already operate before adding a new one.
- Product and docs search boxes
The mixed query stream the page describes, SKUs and error strings next to plain questions, is the normal case. A common pattern is to detect ID-shaped queries with a pattern match and send them to exact lookup first, then fall through to hybrid search for everything else.
- The interview version
“Design semantic search” questions probe four things: why pure vector search misses exact terms, how you fuse two result lists (and why adding the scores is wrong), how you evaluate (recall@k per query type), and what happens when you change the embedding model (re-embed, build a second index, switch over).
Which would you pick?
Three situations. Pick the side you'd actually build — the explanation follows.
Users search a product catalogue by exact SKU codes like "MTX-4471-B", and complain results are wrong.
A SKU carries no semantics to embed — its meaning is that it matches exactly or it does not. Vector similarity will happily return a *nearly* identical code, which is precisely the wrong behaviour when a customer is ordering a part. Lexical matching is not the primitive tool here; it is the correct one.
A help centre where users type "my card got declined" and the article is titled "Payment authorisation failures".
This is the vocabulary-mismatch problem embeddings exist to solve: the query and the answer mean the same thing while sharing barely a word. A synonym list can patch the pairs you thought of, which is fine until the phrasing you did not anticipate arrives — and it always does.
Your semantic search works well, but users occasionally search for a rare product name and get plausible-looking but wrong results.
Rare exact terms are the known weak spot of dense retrieval and the known strength of lexical search, which is why hybrid is the standard answer rather than a compromise. Raising the threshold trades those failures for silent misses on the queries that were working, and reverting throws away every vocabulary-mismatch query you had just fixed.
Quick answers
Embeddings or keyword search — which should I use?
Use keyword search when exact terms matter (error codes, SKUs, IDs) and use embeddings when meaning matters more than exact wording. Most real search surfaces get both kinds of query, which is why hybrid search — running both and fusing the results — is the common production default.
Why does pure embedding search sometimes miss exact matches?
Embedding models are trained to place semantically similar text close together, which means they naturally smooth over small token-level differences like version numbers or exact codes — the same property that makes them good at meaning makes them weaker at exact-term precision.
What is hybrid search?
Running both a keyword index (like BM25) and an embedding index against the same query, then fusing the two ranked result lists — commonly with reciprocal rank fusion — so the final ranking benefits from both exact-term precision and semantic recall.
Is BM25 obsolete now that embeddings exist?
No. BM25 counts literal token overlap, which makes it structurally incapable of confusing similar-but-distinct exact terms the way vector similarity can. It remains the more reliable method whenever exact-match precision matters, and is a standard component of hybrid retrieval.
Embeddings vs Keyword search: match the words, or the meaning?
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The RAG HandbookRetrieval-augmented generation end to end — why LLMs need it, chunking, embeddings and vector search, hybrid retrieval, two-stage reranking, grounded generation with citations, and how to evaluate a RAG system so a quietly-drifting index never fools you.Read →
- The Vector Databases HandbookHow vector search actually works — why brute-force kNN doesn't scale, distance metrics, approximate nearest neighbor, the HNSW, IVF and product-quantization indexes and their recall/latency/memory tradeoffs, metadata filtering, updates, scaling, and when you need a dedicated vector DB vs pgvector.Read →
- RAG vs Fine-TuningThe most common wrong turn in AI engineering — reaching for fine-tuning when you needed retrieval, or vice versa. The one distinction that decides it (knowledge vs behavior), a head-to-head table, when to use each, and why the strongest systems combine them: fine-tune for behavior, RAG for knowledge.Read →
- The Embeddings HandbookMeaning as geometry: how text and images become vectors so that similar meaning lands nearby, why cosine similarity measures direction not length, how L2-normalization makes the dot product equal cosine (so vector databases just take dot products), the curse of dimensionality, and how it all powers semantic search and RAG — with worked math and runnable code.Read →
- The Data Engineering for AI HandbookThe pipeline that turns raw documents into usable data for RAG and training — ingest, chunk, deduplicate, quality-filter. How overlapping chunking works, why deduplication restores diversity, and why the usable dataset is a compounding fraction of the raw pile (raw × dedup-rate × quality-rate) — because quality beats quantity for both retrieval and training. With worked yield math and a runnable pipeline.Read →
- RAG vs Long ContextA 1M-token window makes it tempting to skip retrieval entirely — but bigger context doesn’t mean the model reads it evenly, and it isn’t cheap. The "lost in the middle" attention problem, cost-at-scale math, and the retrieve-then-go-long pattern that combines both.Read →