Embeddings
What embeddings are, how cosine similarity compares them, how they are used for search, and the mistakes that make similarity search return wrong results.
On this page
An embedding is a list of numbers, called a vector, that represents a piece of content such as a word, a sentence, an image or a product. A model produces it so that pieces of content with similar meaning get similar vectors. Embeddings are used for search by meaning, recommendations, duplicate detection and retrieval for language models, because they turn the question "is this similar to that?" into arithmetic on numbers.
Without embeddings, a search for "warm jacket" is a keyword match. A shop's "insulated winter coat" shares no words with the query and is missed, while an unrelated "jacket potato" recipe card matches on the word "jacket". An embedding search compares meaning instead of spelling, so the coat ranks first.
What an embedding represents
You can think of each embedding as a point in space. Items with similar meaning are close together, and items with unrelated meaning are far apart. The figure shows this in two dimensions, with the query "warm jacket" landing among the coats.
Real embeddings have hundreds or thousands of numbers, so the space cannot be drawn, but the arithmetic is the same as in two or three dimensions. The individual numbers have no names you can read off. Position 17 does not mean "warmth"; only the distances between whole vectors carry meaning.
How a model produces embeddings
An embedding comes from a neural network that was trained on a task which forces similar content to look similar inside the network. There are two common training tasks. In the first, the model predicts a word from the words around it, so words that appear in similar contexts, such as "coat" and "jacket", end up with similar internal values. In the second, the model is shown pairs that belong together, such as a question and the passage that answers it, and it is trained to give matching pairs close vectors and random pairs distant ones.
After training, you feed any text into the model and read the numbers from one of its layers. You do not train anything yourself in normal use. You call an embedding model and store the vectors it returns.
Cosine similarity
The standard way to compare two embeddings is cosine similarity. It measures the angle between the two vectors and ignores their lengths. A score of 1 means the vectors point the same way, 0 means they are at right angles and unrelated, and -1 means they point in opposite directions.
The calculation needs two pieces. The dot product multiplies the numbers at matching positions and adds the results, so for [4, 1, 1] and [5, 2, 2] it is 4×5 + 1×2 + 1×2 = 24. The length of a vector is the square root of the sum of its squared entries, so for [4, 1, 1] it is √(16 + 1 + 1) ≈ 4.24. Cosine similarity is the dot product divided by the product of the two lengths.
cosine(a, b) = dot(a, b) / (length(a) × length(b))
Dividing by the lengths means that only direction counts, so a long document and a short one about the same topic still score as similar.
Ranking products by cosine similarity
To see the whole search, give each product a hand-made embedding with three numbers that stand for warmth, dressiness and waterproofing. The query "warm jacket" becomes [4, 1, 1]. Real embeddings do not have dimensions this tidy, but the ranking works the same way.
qlen = length(query)for each item: score = dot(query, item) / (qlen * length(item))sort items by score, highest first- item0coat1overcoat2shell3shirtvector05,2,214,4,021,1,530,3,0cosine0123
- query
- [4, 1, 1]
- qlen
- 4.24
1The query is
[4, 1, 1]. Its length, √18 ≈ 4.24, is computed once and reused. - item0coati1overcoat2shell3shirtvector05,2,214,4,021,1,530,3,0cosine00.98123
- qlen
- 4.24
- dot
- 24
- length
- 5.74
2Coat
[5, 2, 2]: dot = 20 + 2 + 2 = 24. Length √33 ≈ 5.74. Cosine = 24 / (4.24 × 5.74) ≈ 0.98. - item0coat1overcoati2shell3shirtvector05,2,214,4,021,1,530,3,0cosine00.9810.8323
- qlen
- 4.24
- dot
- 20
- length
- 5.66
3Overcoat
[4, 4, 0]: dot = 16 + 4 + 0 = 20. Length √32 ≈ 5.66. Cosine ≈ 0.83. It is warm but dressier than the query. - item0coat1overcoat2shelli3shirtvector05,2,214,4,021,1,530,3,0cosine00.9810.8320.453
- qlen
- 4.24
- dot
- 10
- length
- 5.2
4Rain shell
[1, 1, 5]: dot = 4 + 1 + 5 = 10. Length √27 ≈ 5.20. Cosine ≈ 0.45. It points mostly toward the "waterproof" dimension. - item0coat1overcoat2shell3shirtivector05,2,214,4,021,1,530,3,0cosine00.9810.8320.4530.24
- qlen
- 4.24
- dot
- 3
- length
- 3
5Linen shirt
[0, 3, 0]: dot = 0 + 3 + 0 = 3. Length 3. Cosine = 3 / (4.24 × 3) ≈ 0.24. It is barely related to the query. - item0coat1overcoat2shell3shirtvector05,2,214,4,021,1,530,3,0cosine00.9810.8320.4530.24
- best match
- coat
- comparisons
- 4
6Sorted by score, the order is coat, overcoat, shell, shirt. The winter coat ranks first even though it shares no words with "warm jacket".
function dot(a, b) {
let total = 0;
for (let i = 0; i < a.length; i++) total += a[i] * b[i];
return total;
}
// Cosine similarity: 1 means same direction, 0 means unrelated.
function cosine(a, b) {
return dot(a, b) / (Math.sqrt(dot(a, a)) * Math.sqrt(dot(b, b)));
}
// Item names with their scores, most similar first.
function search(query, items) {
return Object.entries(items)
.map(([name, vec]) => [name, cosine(query, vec)])
.sort((x, y) => y[1] - x[1]);
}
search([4, 1, 1], {
"insulated winter coat": [5, 2, 2],
"wool overcoat": [4, 4, 0],
"rain shell": [1, 1, 5],
"linen shirt": [0, 3, 0],
}); // coat 0.985, overcoat 0.833, shell 0.454, shirt 0.236import math
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cosine(a, b):
"""Cosine similarity: 1 means same direction, 0 means unrelated."""
return dot(a, b) / (math.sqrt(dot(a, a)) * math.sqrt(dot(b, b)))
def search(query, items):
"""Item names with their scores, most similar first."""
scored = [(name, cosine(query, vec)) for name, vec in items.items()]
return sorted(scored, key=lambda pair: pair[1], reverse=True)
search([4, 1, 1], {
"insulated winter coat": [5, 2, 2],
"wool overcoat": [4, 4, 0],
"rain shell": [1, 1, 5],
"linen shirt": [0, 3, 0],
}) # coat 0.985, overcoat 0.833, shell 0.454, shirt 0.236Variants and design choices
Cosine similarity or dot product
The raw dot product grows with vector length, so a long or repetitive item can outscore a better match. Cosine similarity removes that effect. Many embedding models return vectors that are already scaled to length 1, and for those the dot product and the cosine are the same number, so the cheaper dot product is safe. If you are not sure the vectors are scaled, use cosine, or scale every vector to length 1 once when you store it. Which measure to use is a property of the model, so check its documentation, and use the same measure for every comparison. Euclidean distance, the straight-line distance between two points, is a third option. For vectors scaled to length 1 it gives the same ranking as cosine similarity, so the choice rarely changes results in that case.
Searching many vectors: exact and approximate
The simplest search compares the query with every stored vector, which takes time proportional to the number of items times the number of dimensions. That is fast enough for thousands of items and often for hundreds of thousands. Beyond that, a vector index is used. An approximate nearest-neighbour index groups vectors ahead of time so that a query only examines the promising groups. It is much faster, but it can miss the true best match, and its settings trade speed against how often that happens. Start with the exact comparison and move to an index only when the exact search is measurably too slow. Storage grows too: every stored vector takes one number per dimension, so a model with more dimensions costs more memory and makes every comparison slower.
What to embed: whole documents or chunks
A single vector for a long document averages everything in it, so a specific question about one paragraph matches it weakly. For search over long text, split each document into chunks of a few paragraphs, embed each chunk, and return the best chunks. Chunks that are too small lose the context needed to understand them, and chunks that are too large blur several topics together. The right size depends on your content, so try a few sizes and look at what comes back for real queries. Retrieval systems for language models depend heavily on this choice; RAG Basics covers it in context.
Other uses beyond search
The same comparison supports recommendations, where you show the items nearest to one the user liked, and duplicate detection, where near-identical tickets or listings score close to 1. Language models also turn every token into an embedding as their first step, which is the link between this lesson and What Is an LLM.
Pitfalls
What this changes in practice
Use embedding search when users describe what they want in their own words and the documents use other words. Keep keyword search when users type exact names or codes, and use both when you need both. Store the name of the embedding model next to the vectors so that you know when a re-embed is needed. Embed once when content is added, not on every query, since only the query needs to be embedded at search time. Always read a sample of the top results for real queries before trusting the system, because a high score only says the text is related.
A query is [1, 2], document A is [2, 4] and document B is [3, 1]. Compute the dot product and the cosine similarity of the query with each document. Which is the better match, and why do the two measures differ in how they describe it?
Show a sample answer
- A: the dot product is 1×2 + 2×4 = 10. The lengths are √5 and √20, so the cosine is 10 / √100 = 10 / 10 = 1.0.
- B: the dot product is 1×3 + 2×1 = 5. The lengths are √5 and √10, so the cosine is 5 / √50 ≈ 0.71.
Document A points in exactly the same direction as the query and is twice as long, so its cosine is a perfect 1.0. The dot product also ranks A first, but its values of 10 and 5 depend on vector length, so they do not tell you that A is a perfect directional match. The cosine always lies between -1 and 1, whatever the lengths are.
Check yourself
Two vectors point in exactly the same direction, but one is three times longer. What is their cosine similarity?
You switch to a new embedding model for queries but keep the old document embeddings. What happens?
A search for "can I cancel my order" returns a passage saying "orders cannot be cancelled once shipped" as the top match. What does that tell you?
What to practise next
To write cosine similarity yourself, try Bookshop Blurb Match. To see how embeddings are used to give a model relevant text, continue with RAG Basics.