Embeddings and semantic search
9 min read
From words to positions
Keyword search asks whether the same words appear. Semantic search asks whether the same idea appears. To do that, a computer needs a way to measure how close two meanings are, and numbers give it one.
An embedding model reads a text and returns a list of numbers, called a vector. You can think of the list as a position on a map. Texts that mean similar things land near each other, and texts about different things land far apart. A real model's map has hundreds or thousands of dimensions, not two, but the idea is the same.
The model is trained so that this works. It sees many pairs of texts that belong together and learns to place them close. You do not train it for each project. You pick a model, such as one from the Sentence Transformers library or a hosted Vector embeddingsLists of numbers that stand for the meaning of a piece of text. Texts with similar meanings get similar numbers, so a search can find a passage even when the words differ. service, and use it as it is. This is a different job from the token vectors inside a language model, which the Lesson Turning tokens into vectors describes. Those represent single tokens. An embedding model represents a whole passage.
Measuring closeness
The usual measure is Cosine similarityA score for how closely two vectors point in the same direction, from -1 to 1. Search systems use it to compare the vector of a question with the vectors of passages.. It compares the direction of two vectors and ignores their length, and it gives a number from -1 to 1. A score near 1 means the vectors point the same way, and a score near 0 means they are unrelated.
The program below uses four-number vectors written by hand, so you can follow every step. The four numbers stand for "money", "delivery", "bike" and "guarantee". A real model chooses its own dimensions, and nobody can name them like this.
import math
def cosine(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)))
passages = {
"Get your money back within 30 days": (0.9, 0.2, 0.1, 0.0),
"Delivery takes 3 to 5 business days": (0.1, 0.9, 0.1, 0.0),
"The frame is covered for 5 years": (0.1, 0.0, 0.6, 0.8),
}
question = (0.8, 0.1, 0.2, 0.0)
for text, vector in sorted(passages.items(), key=lambda item: -cosine(question, item[1])):
print(f"{cosine(question, vector):.2f} {text}")It prints:
0.99 Get your money back within 30 days
0.25 Delivery takes 3 to 5 business days
0.24 The frame is covered for 5 yearsThe question was "How do I get a refund?", and its vector leans toward "money". It ranks "Get your money back within 30 days" first with a score near 1, though the question and the passage share only the word "get". Keyword search would have ranked it near the bottom.
The two halves of semantic search
- Embed passagesAt index time, run every chunk through the embedding model and store the vector.
- Embed the questionAt query time, run the question through the same model.
- CompareScore the question vector against the stored vectors.
- Return the closestPass the top few passages on to the model.
Two rules follow from this.
- Use the same model on both sides. Vectors from different models are not comparable. If you switch models, you must embed every passage again.
- Embed the chunk, not the whole document. One vector can hold only so much meaning. A vector for a long document blurs all its topics together.
What semantic search is good and bad at
Embeddings find paraphrases, synonyms and questions asked in other words than the document used. They work across languages in some models, so a question in German can find an English passage.
They are weaker at exact detail. A product code, a version number or a person's name has little meaning to compare, and an embedding can rank a passage about a similar product above the exact one. They can also confuse opposites. "You can return sale items" and "You cannot return sale items" are close in meaning space, because both are about returning sale items. A close score means about the same topic. It does not mean the answer.
This is why a close match is evidence, not proof, and why the retrieved passages should still be checked, as the Lessons on measuring retrieval explain.
Choosing an embedding model
- Language. Pick a model that covers the languages of your documents and your users.
- Size. Larger vectors can hold more detail but cost more to store and compare. Common sizes run from a few hundred to a few thousand numbers.
- Input limit. Each model reads only so many tokens at once, so your chunks must fit.
- Your own test. Public leaderboards, such as the MTEB benchmark, help you shortlist. Your documents and questions decide the winner, so test two or three models on questions you wrote yourself.
The idea of embedding whole sentences for search is described in Sentence-BERT, the paper behind the Sentence Transformers library.
What does an embedding model give you?
You pass the text 'Get your money back within 30 days' to it.
Passages and questions are turned into vectors, and nearness stands for similar meaning.
A cosine similarity near 1 means what?
A question and a passage score 0.99.
Cosine similarity compares direction. It does not check whether the passage is true.
When does semantic search beat keyword search?
The user writes 'money back' and the document says 'refund'.
Embeddings capture meaning. Exact names and codes are often better served by keyword search.
Your reading position is saved
0 of 15 complete
Lesson complete
Embeddings and semantic search
Up next