RAG for Everyone

← Back to all chapters

Chapter 12 of 28Embeddings70 min read

What Embeddings Are

Embeddings turn text into numbers so machines can search by meaning. They are the bridge between human language and retrieval math, but they also have limits that every production RAG builder must understand.

How to read this chapter

Search used to ask: "Do these words match?" Embeddings ask a deeper question: "Do these ideas live near each other?"
Core ideaAn embedding is a vector: a list of numbers that represents text, image, audio, or other data in a space where similar meanings tend to be close together.
Sub-topic 1 of 13

Why Embeddings Exist

At a glance
  • Keyword search misses meaning when words differ.
  • Embeddings help retrieve related text even when vocabulary is different.
  • RAG uses embeddings to find candidate chunks before the model answers.
  • Embeddings are useful but imperfect, so they need metadata, reranking, and evals.

Suppose a user asks, "How do I rotate an API credential?" The document says, "Regenerate the access key and update dependent services." A pure keyword search may struggle because "rotate" and "regenerate" are different words. Embeddings help because they can place related ideas near each other.

Embeddings north starUse vectors to find likely relevant evidence, then use engineering controls to prove it is safe and useful.

Embeddings are excellent candidate finders. They are not a replacement for source governance, metadata, citations, or evaluation.

01
Convert text to vector

Each chunk and question becomes a list of numbers.

02
Compare vectors

Similarity functions rank chunks by closeness to the question.

03
Filter and assemble context

Metadata, reranking, and context budgets decide what reaches the model.

04
Evaluate behavior

Recall, precision, citation support, and failure analysis decide whether the embedding setup works.

Sub-topic 2 of 13

Real-Life Analogy: Google Maps for Meaning

Think of embeddings like a map. Restaurants are near other restaurants. Hospitals are near health services. Airports are near travel locations. If you search for "food near me," the map does not match only the word "food"; it understands related places.

Embeddings create a similar map for meaning. "Password reset," "credential rotation," and "access key regeneration" may live near each other because they are conceptually related.

Mental picture
  • Text becomes a point on a map.
  • Related meanings sit nearby.
  • Search becomes a nearest-neighbor problem.
  • Close does not always mean correct.
Sub-topic 3 of 13

Mental Model

A vector is just a list of numbers. In simple examples, we can imagine two or three dimensions. In real embedding models, vectors often have hundreds or thousands of dimensions.

Tiny example

"reset password"      -> [0.82, 0.10, 0.44]
"change credentials"  -> [0.79, 0.13, 0.41]
"quarterly revenue"   -> [0.05, 0.91, 0.22]

The first two vectors are close because the meanings are related. The revenue vector is far away because it talks about a different topic.

Mentor note: the numbers themselves are not meant for humans to interpret one by one. The useful behavior comes from comparing vectors.
Sub-topic 4 of 13

Technical Explanation

An embedding model reads input and returns a fixed-length numeric vector. Fixed length matters because every chunk and query must live in the same vector space to be compared.

Input

A chunk, query, title, image caption, product description, ticket, policy section, or code snippet.

Embedding model

A model trained to place related items near one another. It can be local, open-source, or API-based.

Output

A vector such as 384, 768, 1024, 1536, or more numbers depending on the model.

Where it fits in RAG
  • Index time: embed chunks and store vectors with text, metadata, ids, and source references.
  • Query time: embed the user's question using the same embedding model family.
  • Retrieval: compare the query vector to stored chunk vectors.
  • Context assembly: send the best chunks, not the vectors, to the language model.
Sub-topic 5 of 13

Similarity

Similarity is how we measure closeness between vectors. Common approaches include cosine similarity, dot product, and Euclidean distance.

Cosine

Angle between vectors

Measures direction more than raw length. Common for text embeddings.

Dot product

Magnitude and direction

Often used by vector databases and embedding systems optimized around it.

Euclidean

Straight-line distance

Measures geometric distance, useful in some settings but not always best for text search.

Ranking

Nearest neighbors

Retrieval ranks chunks by similarity and returns top-k candidates.

Cosine intuition

same direction      -> high similarity
opposite direction  -> low similarity
unrelated direction -> weak similarity
Sub-topic 6 of 13

Dense vs Sparse Intuition

Embeddings are often called dense vectors because most dimensions contain some value. Traditional keyword systems such as TF-IDF or BM25 are sparse because most vocabulary dimensions are zero for a document.

Sparse retrieval

Great for exact terms, product codes, error IDs, names, legal clauses, and rare keywords.

Dense retrieval

Great for paraphrases, semantic matching, concepts, and natural-language questions.

Hybrid retrieval

Combines both. In production, hybrid is often stronger than choosing one camp blindly.

Production example

Error code search

If the user searches for AZ-4032-B, sparse search may outperform dense embeddings because exact tokens matter. If the user asks "Why did my deployment fail after rotating a key?", dense retrieval may help more. A strong RAG system can route or blend both.

Sub-topic 7 of 13

Architecture View

Embedding architecture showing chunks and question converted to vectors, compared by similarity, and returned as context
Embeddings convert chunks and questions into comparable vectors. Retrieval uses vector similarity to find candidate evidence for the prompt.

Embedding retrieval flow

documents
  -> chunks
  -> embedding model
  -> vectors + metadata in vector store

user question
  -> same embedding model
  -> query vector
  -> similarity search
  -> top chunks
  -> grounded answer
Sub-topic 8 of 13

Practical Example

The course project stays dependency-light, so this chapter uses a tiny local vector example to teach similarity. It is not a replacement for a real embedding model, but it makes the mechanics visible.

Mini similarity example

from math import sqrt

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    left = sqrt(sum(x * x for x in a))
    right = sqrt(sum(y * y for y in b))
    return dot / (left * right)

query = [0.80, 0.12, 0.40]
chunk = [0.78, 0.11, 0.42]
print(round(cosine(query, chunk), 3))

In real systems, the embedding model creates the vectors. Your job as an engineer is to choose the model, store vectors correctly, evaluate retrieval, and know when similarity is misleading.

Sub-topic 9 of 13

Production Considerations

Production gear
  • Model consistency: index chunks and embed queries with compatible models. Changing models requires re-indexing.
  • Dimension compatibility: vector stores expect a fixed dimension for a collection.
  • Latency: query embedding adds runtime latency unless cached or optimized.
  • Cost: embedding large corpora and frequent queries can be expensive.
  • Privacy: sending sensitive text to an external embedding API may need legal and security review.
  • Drift: documents, user language, and embedding models change over time.
  • Evaluation: measure whether the right chunks are retrieved, not whether the vectors look impressive.
Sub-topic 10 of 13

Common Mistakes

M01

Treating similarity as correctness

Symptom: close chunks are trusted even when they are stale or incomplete.
Better move: combine similarity with metadata, citations, freshness, and evals.
M02

Changing embedding model without re-indexing

Symptom: query vectors and stored vectors live in incompatible spaces.
Better move: version embedding model and rebuild the index when the model changes.
M03

Ignoring exact identifiers

Symptom: embeddings miss ticket IDs, product codes, error codes, and policy numbers.
Better move: use sparse or hybrid retrieval for exact-match-heavy domains.
M04

Embedding noisy chunks

Symptom: headers, footers, navigation text, or broken tables pollute vectors.
Better move: clean and structure content before embedding.
M05

Embedding whole documents blindly

Symptom: retrieval returns broad documents instead of precise evidence.
Better move: chunk at useful thought units and keep parent context separately.
M06

No embedding version in metadata

Symptom: teams cannot explain retrieval shifts after rebuilds.
Better move: store embedding model, dimension, chunker version, and index version.
M07

Overlooking privacy review

Symptom: sensitive documents are sent to an external model without governance.
Better move: classify data and choose local or approved providers where needed.
M08

Skipping retrieval evals

Symptom: demos look fine, but production users see misses.
Better move: maintain golden queries with expected chunks and measure Recall@k.
Sub-topic 11 of 13

Interview-Level Understanding

A strong answer sounds like this: "Embeddings represent text as vectors so semantically related chunks can be found by similarity. In RAG, we embed chunks at index time and embed the query at runtime. But vector similarity is only a candidate-generation step; we still need metadata filters, reranking, citations, freshness controls, and evals."

Senior signal

What separates beginner and production thinking?

A beginner says, "Embeddings find similar text." A production engineer adds, "Similarity can retrieve stale, unsafe, or incomplete text, so we version models, filter metadata, evaluate Recall@k, and re-index when embedding behavior changes."

Sub-topic 12 of 13

Mini Assignment

Choose five pairs of sentences from your domain. Label each pair as exact match, semantic match, related but unsafe, or unrelated. Then explain whether sparse, dense, or hybrid retrieval should handle each pair and why.

Sub-topic 13 of 13

Points To Remember

  • Embeddings turn text into vectors that can be compared by similarity.
  • RAG uses embeddings to retrieve candidate evidence, not to prove truth.
  • Dense vectors are strong for semantic matching; sparse retrieval is strong for exact terms.
  • Embedding model changes usually require re-indexing.
  • Production embedding systems need metadata, evals, privacy controls, versioning, and failure analysis.

Next, test the mental model in the quiz, then build a tiny similarity searcher in exercises and project.

← Chapter 11 ProjectTake the Quiz →