Sub topic 1
Text Embeddings and Semantic Search
Prerequisites
This chapter assumes basic Python, arrays, vector operations, and a general idea of keyword search. You should know that a dot product combines two vectors into one number.
Why Keyword Search Falls Short
Keyword search finds documents containing the same words as the query. It works well for exact names, codes, and phrases. However, it can miss equivalent wording.
For example, the query “How can I recover my account?” may not match a document titled “Steps to reset your password.” The words differ, although the meaning is related. Keyword search also struggles with synonyms, word order, and paraphrases.
Semantic search compares meaning. It represents text as numbers and finds texts with similar numerical representations.
What an Embedding Is
An embedding is a fixed-length vector that represents text. A vector is an ordered list of numbers. An embedding model places texts with related meanings near one another in a vector space.
The model does not assign one number to “password” and another to “account.” Instead, it produces a full vector for each sentence. The combined pattern captures information about meaning and context.
Measuring Closeness
Common measures give different meanings to “nearby.”
| Measure | What it emphasizes | Common use |
|---|---|---|
| Cosine similarity | Direction, ignoring length | Normalized text embeddings |
| Dot product | Direction and vector length | Retrieval with compatible training |
| Euclidean distance | Straight-line separation | Clustering or geometric comparisons |
Cosine similarity ranges from -1 to 1. A value near 1 means vectors point in nearly the same direction. A dot product is larger when vectors align and have large lengths. Euclidean distance is smaller for closer points.
Normalize vectors when you want cosine similarity through a dot product. Do not compare scores from different models without checking their definitions and scaling.
Where Embeddings Come From
Most modern text embeddings use transformer encoders. A transformer reads tokens while considering their context. For example, it can distinguish different meanings of “bank.”
The encoder produces one vector for each token. Pooling combines those token vectors into one sentence vector. During contrastive training, the model sees related text pairs and unrelated pairs. It learns to move related embeddings closer and unrelated embeddings farther apart.
Exercise
Which measure should you usually start with when comparing unit-normalized sentence embeddings?
Show answer
Cosine similarity, or an equivalent dot product because unit normalization makes the two rankings identical.