# Sparse vs Dense Embeddings

> Word matching against meaning matching, where each one wins, and how to combine them, for your AI interview.

**In short:** A sparse embedding has one slot for each word and is mostly zeros, so it matches exact words and codes. A dense embedding is a short list of numbers that captures meaning, so it matches ideas even when the words differ.

AI and LLM interview question Q154, Retrieval-augmented generation (RAG). Intermediate, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/sparse-vs-dense-embeddings

## Say it in 30 seconds

Sparse embeddings have one slot per term in a fixed word list, and most slots are zero, so they catch exact matches like a claim code or a product ID. Dense embeddings are a fixed list of numbers that capture meaning, so they find ideas even when the wording changes. Each one misses what the other catches, so I would run both and merge the results.

## Say it in 2 minutes

Think about searching a claims archive at a mid-size insurer. Staff type a claim code, like CL-4471, and expect exactly that note to come up. A sparse embedding handles this well. It is a word-level vector with one slot for each word in a fixed word list. Almost all of its slots are zero, and the few that are not zero mark the words in the note. Two texts that share the code share a slot, so the match is exact.

The trouble is wording. A customer might type dishwasher leak, while the note says appliance water damage. The words barely overlap, so a keyword search may miss the match. A dense embedding is a short, fixed list of numbers made by a model, and nearly every number carries a value. Texts with a similar meaning end up with similar numbers, so the search finds the idea even when the words differ.

Each one fails where the other works. Dense search can lose an exact code, and keyword search misses synonyms. So you can run both, a keyword search and a vector search, and merge the two lists. Microsoft's hybrid search does this with reciprocal rank fusion, a way to combine the rankings. In a claims search, the code finds the exact note and the meaning finds the rest.

Check the setup before you pick one. Measure both on your own questions, with real codes and real wording, and keep whatever wins on your data.

## What are sparse and dense embeddings, in plain words?

An embedding is a list of numbers that stands for a piece of text, so a computer can compare texts by their numbers. Sparse and dense are two styles of that list.

A sparse embedding has one slot for each word in a big word list. A text fills only the slots for its own words, so most slots stay at zero. A dense embedding is a short list of numbers that a model learns, and almost every number has a value. Its job is to put similar meanings close together.

Picture a claims clerk with a card index of claim numbers, and a senior adjuster who knows that water through a ceiling and a burst pipe upstairs are the same kind of loss. The clerk finds exact codes. The adjuster finds the idea. A good search needs both.

- **Sparse vector:** A long list, one slot per word, where almost every value is zero.
- **Dense vector:** A short fixed list of numbers, where almost every value is used.
- **Embedding:** A list of numbers that stands for a piece of text, made by a model or by a simple counting rule.
- **Hybrid search:** Keyword search and vector search run together, then merged into one list.

## How does each one turn text into numbers?

Google's machine learning glossary describes the sparse idea as bag of words: a representation of the words in a phrase or passage, irrespective of order. Each word is mapped to an index in a sparse vector, with one index for every word in the vocabulary (the full word list the model knows).

Classic keyword scoring, such as BM25 (a formula that ranks documents by their matching words), works on the same idea and adds sensible weights. Anthropic describes BM25 as a ranking function that uses lexical matching, which means it matches the words themselves. A rare word, like a claim code, counts for more than a common word.

Sparse does not have to mean old. Learned sparse models, such as SPLADE, still output a vector with one slot per vocabulary term, but a model learns the weight of each slot. The SPLADE paper aims for sparse representations that keep exact term matching and the efficiency of inverted indexes (lookup tables from each word to the texts that contain it).

> **Tip:** Sparse search is easy to explain to a user. The words that matched are the reason a note came back, which helps when someone has to check why a result showed up.

A model reads the text and returns a list of floating point numbers (decimal numbers a computer stores) with a fixed length. OpenAI's embeddings guide calls an embedding a vector, which is a list of floating point numbers, and says that a small distance between two vectors suggests high relatedness.

1. **Embed each note once, offline:** Store the vector of every chunk (a short piece of a document) in a vector index, a store built to find nearby vectors fast, so you don't pay to rebuild it for each query.
2. **Embed the question when it arrives:** The same model turns the question into a vector, in the same space as the notes.
3. **Find the nearest vectors:** The search returns the chunks whose vectors sit closest to the question's vector.
4. **Hand the best ones to the model:** The top chunks go into the prompt, and the model answers from them.

The model learns the numbers from many examples. Nobody types them in by hand, which is why two texts with the same idea and different words can still land close together.

## Where does each one win, and where does it fail?

- **Sparse wins: Exact codes and names.** Claim codes, product IDs, dates and rare jargon match word for word, and you can show which words matched.
- **Dense wins: Same idea, new words.** A question about a dishwasher leak can find a note about appliance water damage, even though the words barely overlap.
- **Both fail: The wrong setup.** Keyword search misses synonyms. Dense search can drop an exact code, because it reads the code as a loose idea.

> "A feature whose values are predominately zero or empty." (Google Machine Learning Glossary)
>
> "While embedding models excel at capturing semantic relationships, they can miss crucial exact matches." (Anthropic, on contextual retrieval)
>
> "Some scenarios, such as querying over product codes, highly specialized jargon, dates, and people's names, perform better with keyword search because it can identify exact matches." (Microsoft Learn, Azure AI Search)

Dense is not a free win. In 2020, Karpukhin and colleagues found that dense retrieval beat a strong BM25 system by 9 to 19 percentage points on top-20 passage accuracy, which is how often the right passage is in the top 20 results. The test used open-domain questions, meaning questions answered from a large collection, not one given passage. Their paper also says that sparse vector models, such as TF-IDF or BM25, are the de facto method. That was one benchmark, so measure on your own data.

## How do teams combine the two?

Microsoft describes hybrid search as combining vector search and keyword search. It runs full-text search and vector search in parallel, then merges the results with reciprocal rank fusion. Anthropic's contextual retrieval work uses two sub-techniques, contextual embeddings and contextual BM25, and combines their results with rank fusion after removing duplicates.

*Diagram, Hybrid search: one merged list: One question goes to a keyword search and a vector search at the same time. A merge step ranks the combined list, and the best chunks go to the model. Running two indexes costs more to build and to host, so prove the gain on your questions first.*
1. The question's words go to the keyword index.
2. The same question becomes a vector for the meaning index.
3. Keyword results arrive as one ranked list.
4. Vector results arrive as a second ranked list.
5. The merged top chunks go to the model.

## What does a worked example look like?

A mid-size insurer's claims team searches 40,000 notes and policy wordings. A staff member asks about claim CL-4471 and whether the excess is waived. The code is exact and the idea is loose. Here is a small made-up version, with two notes and hand-typed vectors, in plain Python.

```python
import math
from collections import Counter

# Made-up claim notes. Sparse = word counts. Dense = made-up 3-number vectors (a real model makes much longer ones).
NOTES = {
    "CL-4471 note": ("claim CL-4471 excess waived after review", [0.1, 0.9, 0.2]),
    "Burst pipe guide": ("water damage from a burst pipe, excess applies", [0.9, 0.3, 0.1]),
}
QUERY = "CL-4471 excess waived?"
QUERY_VEC = [0.9, 0.4, 0.1]  # made-up meaning vector for the question

def words(text):
    return Counter(text.lower().replace(",", "").replace("?", "").split())

def sparse_score(query, text):
    a, b = words(query), words(text)
    return sum(min(a[w], b[w]) for w in a)  # shared words, counted

def dense_score(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

for name, (text, vec) in NOTES.items():
    print(f"{name}: sparse {sparse_score(QUERY, text)}, dense {dense_score(QUERY_VEC, vec):.3f}")
print("Sparse picks:", max(NOTES, key=lambda k: sparse_score(QUERY, NOTES[k][0])))
print("Dense picks:", max(NOTES, key=lambda k: dense_score(QUERY_VEC, NOTES[k][1])))
```

Output:

```text
CL-4471 note: sparse 3, dense 0.512
Burst pipe guide: sparse 1, dense 0.995
Sparse picks: CL-4471 note
Dense picks: Burst pipe guide
```

The code note scores 3 on shared words and 0.512 on meaning. The burst pipe guide scores 1 on words and 0.995 on meaning. The keyword route picks the exact code, and the meaning route picks the general guide. The meaning route scores each pair with cosine similarity, which measures how closely two vectors point the same way.

*Diagram, One question, two routes: The same question takes two routes. The keyword route finds the code note, the meaning route finds the burst pipe guide, and each one misses what the other catches.*
1. The keyword route takes the words of the question as they are.
2. The meaning route turns the whole question into one vector and compares it.
3. The code note wins on exact words.
4. The burst pipe guide wins on meaning, and it has no code in it.

### How would you choose between them for a bank's policy search?

1. **Collect real questions:** Pull a few hundred real questions from the bank's staff, including ones with fee codes, product names and plain wording.
2. **Build both indexes:** A keyword index on the words, and a vector index on the meaning, both over the same chunks.
3. **Score the top results:** For each question, check whether the right chunk is in the top five, for each route and for the merged list.
4. **Keep what wins, then add the rest:** If codes fail, add keyword search. If synonyms fail, add vectors. Keep the merge only if it wins on your data.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: sparse is one slot per word, dense is a short list of meaning numbers.
- [ ] Where each wins: exact codes for sparse, same idea in new words for dense.
- [ ] Why each fails: keyword search misses synonyms, dense search can lose exact codes.
- [ ] Hybrid search as one documented option, with a merge step such as reciprocal rank fusion (Microsoft Learn).
- [ ] A test on real questions, not a choice made from a blog post.
- [ ] The cost of running two indexes, said honestly.

**Common traps**

- Trap: "Dense embeddings are always better than keyword search." Better: Dense can miss exact codes and names. Test both on real questions, then decide.
- Trap: "Sparse means old, so we shouldn't use it." Better: Classic keyword scoring is sparse, and learned sparse models like SPLADE are sparse too. Say which one you mean.
- Trap: "Hybrid search doubles the work for no gain." Better: It costs more to run, but it covers both kinds of miss. Prove the gain on your questions before you keep it.

## Can you spot the miss?

**Spot the miss:** A staff member ran a dense-only search for claim CL-4471 excess. Which result is the kind of exact match a keyword search is sure to find?

A. Water damage from a burst pipe: the excess applies to the whole claim.
B. Claim CL-4471: excess waived after review, approved on 3 March.
C. Claims desk hours: weekdays 9 am to 5 pm, closed on bank holidays.
D. Excess: the part of a claim the customer pays first.

**Answer:** B. The code CL-4471 is an exact string. A dense search reads it as a loose idea and can drop it, so a word match is the sure way to find this note.

**Quick check:** A customer asks whether the policy covers a dishwasher leak. The wording says appliance water damage, and no codes are in the question. Which single search fits best?

A. Sparse only, because it needs the exact word dishwasher
B. Dense, because it matches the idea of appliance water damage
C. Sparse only, because it counts the word leak
D. A bigger keyword index

**Answer:** B. Dense search matches meaning, so appliance water damage sits close to dishwasher leak. Keyword search needs the same words, and this wording has no dishwasher in it.

## Can you answer these from memory?

**Flash cards**

- **What is a sparse embedding?** A word-slot vector, one slot per word, mostly zeros. Good for exact codes and names.
- **What is a dense embedding?** A short fixed list of numbers, nearly all used. Good for the same idea in new words.
- **Where does keyword search win?** Exact codes, product IDs, dates and rare jargon, where the words must match.
- **Where do vectors win?** Same meaning, different words, such as dishwasher leak and appliance water damage.
- **What is hybrid search?** Keyword and vector search run together, and the two ranked lists are merged.
- **How do you choose?** Measure both on real questions with real codes and wording. Keep what wins.

## Likely follow-up questions

- Q006 What is an embedding? https://designervenkat.online/interview/ai/what-is-an-embedding
- Q116 How do you choose an embedding model? https://designervenkat.online/interview/ai/how-do-you-choose-an-embedding-model
- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
- Q124 What is BM25? https://designervenkat.online/interview/ai/what-is-bm25
- Q126 Rerankers: cross-encoder vs bi-encoder? https://designervenkat.online/interview/ai/cross-encoder-vs-bi-encoder-rerankers
- Q155 Build a minimal RAG pipeline. https://designervenkat.online/interview/ai/build-a-minimal-rag-pipeline

## Learn it in depth

- [Semantic Search](https://designervenkat.online/learn/ai-engineering/semantic-search)
- [Performing Similarity Search](https://designervenkat.online/learn/ai-engineering/performing-similarity-search)
