Slides · Embeddings and vector search

Embeddings and similarity search

Embeddings and similarity search

How a model turns a chunk or a query into one vector, how we measure “close”, and where that ranking breaks.

By the end you can explain embedding geometry, compare cosine, dot product and Euclidean distance, and diagnose the common ways embedding search goes wrong.

Concept

One search works, one fails

  • “My parcel arrived smashed” finds the “damaged items” article, with no shared words.
  • The exact ticket “ST-48213” returns a hundred look-alike tickets, and not the one asked for.
  • Same system, opposite results. The geometry explains both.
  • Teams that sell this as “fuzzy keyword search” are surprised by the second case.

Concept

Mental model: a map of meaning

  • Every piece of content gets coordinates, like a pin on a map.
  • A real map has two axes. An embedding has hundreds or thousands.
  • “Dog” and “puppy” land close. “Dog” and “spreadsheet” land far apart, whatever letters they share.
  • Search means: drop a pin at the query, list the nearest pins.

Diagram

From text to ranked neighbours

Diagram: Chunks and the query are each turned into one vector by the same embedding model.

Chunk text

Embedding model

Chunk vector

Query text

Same embedding model

Query vector

Compare

Ranked nearest chunks

Diagram summary: Chunks and the query are each turned into one vector by the same embedding model. A similarity score compares the query vector with every chunk vector, and the highest scores become the ranked results.

Compare

Two different “embeddings”

AspectToken embedding table (inside an LLM)Dedicated embedding model (this lesson)
InputOne token IDA whole chunk, document or query
OutputOne vector per tokenOne vector for the whole input
Used forFeeding the transformerSearch, clustering, deduplication, RAG retrieval
  • The vector’s job is to represent the whole text, so whole texts can be compared, ranked and stored.
  • Sentence-BERT was designed so sentence embeddings can be compared with cosine similarity. Over 10,000 sentences, finding the most similar pair dropped from about 65 hours (running BERT on every pair) to about 5 seconds, according to its abstract.

Source1 Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks

Diagram

How the model learns “close”

Diagram: Training repeats one loop.

Matching pair: question and its answer passage

Pull the two vectors closer

Mismatched pair: question and unrelated passage

Push the two vectors apart

Update the model

Next batch of pairs

Diagram summary: Training repeats one loop. Matching pairs are pulled together, mismatched pairs are pushed apart, and the model is updated before the next batch. What counts as “similar” is whatever the training pairs taught it.
  • Contrastive pre-training on unsupervised data at scale gives high-quality embeddings (Neelakantan et al.). The diagram shows a generic labelled-pair example; pairs can also come from unlabelled text.
  • Consequence: “meaning” is whatever the pairs made similar. That is why a general model can misjudge a specialised domain.

Source2 Text and Code Embeddings by Contrastive Pre-Training

Worked example

Dimensions cost storage

More dimensions can hold more nuance, but every vector costs memory and compute.

StepCalculation
Bytes per 1,536-dim float32 vector1,536×4=6,1441{,}536 \times 4 = 6{,}144 bytes
1 million vectors1,000,000×6,144=6.1441{,}000{,}000 \times 6{,}144 = 6.144 GB
Same count at 3,072 dims1,000,000×3,072×4=12.2881{,}000{,}000 \times 3{,}072 \times 4 = 12.288 GB
  • This is raw vector storage, before any index overhead.
  • OpenAI’s guide lists 1,536 default dimensions for text-embedding-3-small and 3,072 for text-embedding-3-large, and a dimensions parameter to shorten them. Model names and sizes change; check the model you use.

Source3 Vector embeddings

Compare

Three ways to measure “close”

MetricMeasuresBigger score meansSensitive to length?
Cosine similarityAngle between vectorsMore similarNo
Dot productAngle and length togetherMore similarYes, longer scores higher
Euclidean (L2) distanceStraight-line gap between pointsLess similar (smaller is closer)Yes
  • Cosine is the usual default for text.
  • For many text models the length carries little meaning; check yours.

Math

Cosine similarity

cos⁡(a,b)=a⋅b∥a∥ ∥b∥a⋅b=a1b1+a2b2+⋯+anbn∥a∥=a12+a22+⋯+an2\begin{aligned} \cos(a, b) &= \frac{a \cdot b}{\lVert a \rVert \, \lVert b \rVert} \\ a \cdot b &= a_1 b_1 + a_2 b_2 + \dots + a_n b_n \\ \lVert a \rVert &= \sqrt{a_1^2 + a_2^2 + \dots + a_n^2} \end{aligned}
SymbolMeaning
a,ba, bThe two vectors being compared
a⋅ba \cdot bDot product: multiply matching entries and add them up
∥a∥\lVert a \rVertLength (norm) of aa
cos⁡(a,b)\cos(a, b)Score from −1-1 to 11

Dot product divided by the two lengths removes length from the score. Only the angle is left.

Concept

Reading the number as an angle

CosineAngleIn plain words
10 degreesPoint the same way: very similar
0.7about 45 degreesClearly related
090 degreesUnrelated direction
-1180 degreesOpposite, rare for text embeddings in practice
  • A score has no universal meaning. “0.8” from one model is not “0.8” from another.
  • Choose thresholds by labelling real pairs, never by guessing.

Worked example

Same data, three rankings

Query q=(3,4)q = (3, 4), length 5. Four documents, in 2 dimensions for hand calculation.

DocVectorDot with qCosineEuclidean distance
x(6,8)(6, 8), length 10501.0005.000
y(4,3)(4, 3), length 5240.9601.414
z(1,0.5)(1, 0.5)50.8944.031
w(0,5)(0, 5), length 5200.8003.162

Arithmetic for y: dot =3×4+4×3=24= 3 \times 4 + 4 \times 3 = 24; cosine =24/(5×5)=0.96= 24 / (5 \times 5) = 0.96; distance =1+1=1.414= \sqrt{1 + 1} = 1.414.

MetricBest to worst
Cosinex, y, z, w
Dot productx, y, w, z
Euclidean distancey, w, z, x

Document x points exactly where the query points but is long, so cosine ranks it first and Euclidean distance ranks it last.

Diagram

Try it: move the query

Measuring "close" in an embedding space

Text summary

This plot has seven made-up items as points in 2 dimensions, such as “Ending your plan” at (2, 1), and one query point you can move. A real embedding model has hundreds or thousands of dimensions, so this is a drawing of the idea, not a real model.

For each item, a table gives cosine similarity, dot product and Euclidean distance to the query, and the rank each metric gives it. With the query at (2, 2), where it starts, cosine similarity ranks “Cancel a subscription” first, because it points almost the same way as the query. Euclidean distance ranks “Ending your plan” first, because it is the nearest point.

The dot product ranks “Quarterly report (a long vector)” first, because that vector is long and the dot product grows with length. The metrics disagree here because the item vectors have different lengths. If every item vector had length 1, all three would give the same order.

The interactive version needs JavaScript. The text summary above says what it shows.

Move the query point and watch the three metrics re-rank the same items. When item vectors have different lengths, the metrics disagree. If every item vector had length 1, all three would give the same order.

Math

Why unit length makes cosine cheap

If ∥a∥=1\lVert a \rVert = 1 and ∥b∥=1\lVert b \rVert = 1:

cos⁡(a,b)=a⋅b∥a−b∥2=2−2 (a⋅b)\begin{aligned} \cos(a, b) &= a \cdot b \\ \lVert a - b \rVert^2 &= 2 - 2\,(a \cdot b) \end{aligned}
ResultConsequence
Cosine equals the dot productA plain dot product is fast on hardware
Distance squared falls as the dot product risesEuclidean distance gives the same order as cosine
  • OpenAI’s guide says its embeddings are normalized to length 1, so cosine and Euclidean distance give identical rankings and a dot product is slightly faster.
  • Other models may not normalize. Check the model card, and configure the vector index with the metric the model expects.

Source3 Vector embeddings

Worked example

Checking the identity by hand

Take two unit vectors: a=(1,0)a = (1, 0) and b=(0.6,0.8)b = (0.6, 0.8).

QuantityCalculationResult
Length of bb0.36+0.64\sqrt{0.36 + 0.64}1
Dot product1×0.6+0×0.81 \times 0.6 + 0 \times 0.80.6
Cosine0.6/(1×1)0.6 / (1 \times 1)0.6
Squared distance(0.4)2+(0.8)2=0.16+0.64(0.4)^2 + (0.8)^2 = 0.16 + 0.640.8
2−2(a⋅b)2 - 2(a \cdot b)2−1.22 - 1.20.8

Both formulas agree, so the two metrics order any set of unit vectors the same way.

Code

Cosine in code

Python

import numpy as np

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

q = np.array([3.0, 4.0])
y = np.array([4.0, 3.0])
print(cosine_similarity(q, y))   # 0.96
print(np.linalg.norm(y))         # 5.0, so y is not unit length
  • np.dot is the top of the formula. np.linalg.norm gives each length.
  • For vectors that are already unit length, the division is by 1, so plain np.dot is enough.
  • Printing the norm of your own model’s vectors tells you whether that shortcut is safe.

Concept

Where embedding search fails

  • Exact identifiers and numbers.
  • Rare terms and new vocabulary.
  • Domain shift: a general model blurs a specialised field.
  • Related, but not useful: right topic, not the answer.
  • Mixed models: documents and queries embedded differently.

Embedding search is semantic, not lexical. That is why it wins on paraphrases and loses on exact strings.

Concept

Exact IDs and rare terms

  • A product code such as KB-87-TKL carries little learned meaning. Nearby vectors are other products with similar-looking codes, not the exact one.
  • Product names, internal jargon and new acronyms may be missing from the training data, so they land in arbitrary places.
  • Fix: hybrid search. Run keyword search (BM25) next to vector search, then merge the lists.
  • Vector databases such as Weaviate describe search that uses both semantic similarity and keywords.
  • A model trained on your own domain also helps with rare vocabulary. Measure before you fine-tune.

Source4 Weaviate Database | Weaviate Documentation

Concept

Related, but not useful

  • Embeddings find text on the same topic. That is different from text that answers the question.
  • Fix: retrieve more candidates, then rerank with a model that reads the query and each candidate together.

Concept

Domain shift

  • “Meaning” is whatever the training pairs made similar, so a general model may treat all legal clauses, or all medical notes, as roughly alike.
  • Symptom: everything in a specialised collection scores about the same, so the ranking looks arbitrary.
  • Fix: measure on your own queries first, then try another model, and consider fine-tuning only after measuring.
  • Hybrid search and reranking do not repair a space that cannot tell your documents apart.

Concept

Mixed models give meaningless scores

  • Each embedding model builds its own space. Two models can both output 1,536 numbers and still not be comparable.
  • Failure is silent: the index accepts the vectors and returns scores.
  • Typical cause: upgrading the model but re-embedding only new documents.
  • Fix: store the model name and version with the index, and re-embed everything when it changes.

Diagram

Triage a bad result

Diagram: Work down the questions in order.

yes

no

yes

no

yes

no

yes

no

Wrong results

Exact ID, code or number?

Hybrid search

Rare terms or jargon?

Hybrid / domain model

Right topic, no answer?

Rerank

Mixed embedding models?

Re-embed

Measure, try another model

Diagram summary: Work down the questions in order. Exact identifiers point to hybrid search, rare vocabulary to hybrid or a domain model, right-topic-wrong-answer to reranking, and mixed models to re-embedding. If none fits (domain shift is one such case), measure on your own queries before changing anything.

Check yourself

Check: which one is closer?

Query q=(1,0)q = (1, 0). Document d1=(2,0)d_1 = (2, 0) and document d2=(0.8,0.6)d_2 = (0.8, 0.6). Which document does cosine similarity prefer, and which does Euclidean distance prefer?

Answer

Cosine: d1d_1 scores 1.0 and d2d_2 scores 0.8, so cosine prefers d1d_1. Euclidean distance: d1d_1 is 1.0 away and d2d_2 is 0.04+0.36=0.632\sqrt{0.04 + 0.36} = 0.632 away, so Euclidean prefers d2d_2. d1d_1 points exactly the same way as qq but is twice as long, which only distance notices. If both were scaled to length 1, the two metrics would agree.

Check yourself

Check: the legal archive

A team embeds 20,000 contract clauses with a general-purpose model. Searches for “limitation of liability” return clauses on indemnity, termination and warranties with almost the same scores as the right ones. What failure is this, and what do you do first?

Answer

This is domain shift: a general model treats most contract clauses as roughly similar. First build a small set of real queries with known right clauses and measure. Then try another embedding model, and consider fine-tuning only if measurement shows a gap. Switching the metric will not separate clauses the model cannot tell apart.

Check yourself

Check: sizing a corpus

You will store 5 million chunks, each embedded as 768 float32 values. How much raw vector storage is that, and what does halving the dimensions do?

Answer

768×4=3,072768 \times 4 = 3{,}072 bytes per vector, and 5,000,000×3,072=15.365{,}000{,}000 \times 3{,}072 = 15.36 GB. Halving to 384 dimensions gives 7.68 GB, because storage scales with dimension count. That excludes index overhead, and shorter vectors may lose some quality, so measure retrieval on your own queries before choosing.

Summary

Recap

  • A dedicated embedding model maps a whole chunk or query to one vector; contrastive training makes matching pairs close.
  • Dimensions and vector count set storage: count x dimensions x bytes.
  • Cosine ignores length, dot product and Euclidean distance do not; on unit-length vectors all three agree.
  • Embedding search is semantic, not lexical: use hybrid search for exact IDs and rare terms, reranking for related-but-unhelpful, and one embedding model for both index and queries.
  • Use the metric the model expects and configure the index to match.

References

References & Sources

  1. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (opens in a new tab)

    Nils Reimers, Iryna Gurevych2019EMNLP 2019Paper

    Used for Sentence-BERT was built to produce sentence embeddings that can be compared with cosine similarity, and cut similar-pair search over 10,000 sentences from about 65 hours to about 5 seconds.

  2. Text and Code Embeddings by Contrastive Pre-Training (opens in a new tab)

    Arvind Neelakantan, Tao Xu, Raul Puri, Alec Radford, et al.2022Preprint

    Used for Contrastive pre-training on unsupervised data at scale gives high-quality text and code vector representations.

  3. Vector embeddings (opens in a new tab)

    OpenAI2026Documentation

    Used for OpenAI's guide lists 1536 default dimensions for text-embedding-3-small and 3072 for text-embedding-3-large, a dimensions parameter, and says its embeddings are normalized to length 1, so cosine and Euclidean give identical rankings.

  4. Weaviate Database | Weaviate Documentation (opens in a new tab)

    Weaviate2026Documentation

    Used for Weaviate describes search that uses both semantic similarity and keywords (hybrid search).