Level 2 Agentic Coding · Building with AI
Embeddings and Semantic Search
Search by meaning instead of by keyword. An embedding model turns each piece of text into a vector, similar meanings land close together, and the nearest vectors to a query are the best matches. Build a small search engine over your notes, offline first, then with a real embedding model.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 1 hour to read, an afternoon to build
- Builds on
- 7 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 7 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- Using LLM APIs
- Embeddings and Semantic Search
Read them roughly in this order. See it on the concept map →
Why it matters
Type "my automobile won't turn on" into the search box of your notes app, and it finds nothing, even though you wrote "The car would not start this morning; the battery was flat" last week. Classic keyword search matches words, not meanings. It misses synonyms, paraphrases, other languages and questions phrased differently from the answer.
Semantic search fixes this by searching by meaning. It rests on one idea: an embedding model that turns any piece of text into a list of numbers, a vector, such that texts with similar meanings get similar vectors. To search, you embed the query and find the stored texts whose vectors are closest.
This is one of the most useful building blocks in applied AI. It powers retrieval-augmented generation (finding the documents an LLM should read before answering), recommendations (Recommender Systems), duplicate detection, clustering support tickets by topic, and the long-term memory of chatbots and agents (Context Engineering and Memory). Once you have embeddings, all of these are a few lines of code.
The intuition
Imagine a huge map where every sentence ever written has a location, placed so that sentences about similar things sit near each other. Sentences about cars cluster in one region, gardening in another, baking in a third. "The car would not start" and "my automobile won't turn on" share no important words, but they sit almost on top of each other, because they mean the same thing.
An embedding is a sentence's coordinates on that map. The real map has hundreds or thousands of dimensions rather than two, which gives it room to separate many shades of meaning at once, but the picture is the same. Search becomes geography: drop a pin for the query and look at what is nearby.
How do we measure "nearby"? By direction. Each embedding is an arrow from the origin. Arrows pointing the same way mean similar things. The standard measure is the angle between them, through cosine similarity.
Key idea An embedding turns text into a vector whose position encodes meaning. Semantic search embeds the query and returns the stored texts with the most similar vectors, so it finds matches by meaning even when no words are shared.
How it works
What an embedding model is
An embedding model is a neural network, usually a The Transformer encoder much like BERT, that reads a text and outputs one fixed-length vector. OpenAI's text-embedding-3-small, for example, outputs 1,536 numbers for any input up to 8,192 tokens. The popular open model all-MiniLM-L6-v2 outputs 384.
The model is trained on huge numbers of pairs of related texts (a question and its answer, a title and its article, two paraphrases) so that related pairs end up with similar vectors and unrelated texts with dissimilar ones. This is contrastive training, covered in Sentence Embeddings. The individual numbers don't mean anything you can name. There is no "cars" dimension. Only the relative positions carry meaning.
Embeddings are a different service from text generation, and much cheaper. As of late 2026, embedding a million tokens with OpenAI's small model costs about two cents. Anthropic doesn't offer its own embedding model and points developers to partners such as Voyage AI. Open models from the sentence-transformers family run free on a laptop.
Cosine similarity
The dot product of two vectors multiplies them component by component and adds up the results. Divided by both lengths, it gives the cosine of the angle between them:
Here is the query's embedding, a document's embedding, and their -th numbers, and the length of a vector. The result is 1 when the vectors point the same way, 0 when they are at right angles (unrelated), and −1 when they point in opposite directions. In practice, text embeddings mostly score between about 0 and 1.
Worked example. Pretend embeddings had just three dimensions. Let the query "my automobile won't turn on" be , the car note be and a tomato note be .
- and
- , , so
The car note wins clearly.
A common shortcut is normalisation: divide every vector by its length once, when you store it, so all lengths are 1. Then cosine similarity is just the dot product, and scoring a query against a million stored vectors is a single matrix–vector multiplication. Many embedding APIs return vectors that are already normalised.
The search pipeline
- Index (once, or whenever documents change). Split long documents into passages (see Retrieval-Augmented Generation on chunking), embed each one, and store the vectors along with the text and an id.
- Query (every search). Embed the query with the same model, compute its similarity to every stored vector, and return the highest-scoring passages. This is top-k retrieval.
For a few thousand or even a hundred thousand passages, a NumPy matrix in memory is all you need: scoring 100,000 vectors of 1,536 numbers takes a fraction of a second. Beyond that, or when you need filtering and updates, you want a vector database.
Sparse versus dense vectors
Before neural embeddings, search engines also represented text as vectors, of a different kind. TF-IDF (term frequency–inverse document frequency) gives each document one dimension per word in the vocabulary. The value is high when a word is frequent in this document but rare in the collection as a whole, so "battery" counts for a lot and "the" for nothing. These are sparse vectors: tens of thousands of dimensions, almost all zero. Neural embeddings are dense vectors: a few hundred or thousand dimensions, all non-zero.
| Sparse (TF-IDF, BM25) | Dense (neural embeddings) | |
|---|---|---|
| Matches | exact words | meanings |
| Synonyms, paraphrases | missed | found |
| Rare names, codes, part numbers | found reliably | sometimes blurred |
| Needs a model | no | yes |
Neither wins everywhere, which is why production systems often combine them in hybrid search (Advanced RAG). And sparse vectors are perfect for learning: the code below uses TF-IDF from scikit-learn as an offline stand-in, so you can build and test the whole pipeline before swapping in a real embedding model.
Choosing an embedding model
- Quality on your data matters more than leaderboard rank. The MTEB leaderboard is a good place to shortlist models by task and language. Then test two or three on fifty real queries from your own users.
- Dimensions set storage and speed. 384 dimensions take a quarter of the space of 1,536. Some models (including OpenAI's
text-embedding-3family) let you request shorter vectors. - Languages and domains: multilingual models map different languages into the same space, so an English query can find a French document. Code and legal text have specialised models.
- Query and document roles: some models want a hint about which side a text is on, such as a
query:prefix or aninput_type="query"argument, because short questions and long passages are phrased differently. Read the model card.
In code
A semantic search engine over six notes, runnable offline with scikit-learn's TF-IDF as a stand-in for embeddings:
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
notes = [
"Repot the fig tree in spring with fresh compost and a bigger pot.",
"The car would not start this morning; the battery was flat.",
"Booked the dentist for a check-up on Tuesday at 9am.",
"Water tomato plants deeply twice a week during hot weather.",
"Renew the car insurance before the end of the month.",
"Sourdough: feed the starter the night before baking bread.",
]
vectorizer = TfidfVectorizer(stop_words="english") # rows are L2-normalised
doc_matrix = vectorizer.fit_transform(notes).toarray() # shape (6, 36)
def search(query, k=2):
q = vectorizer.transform([query]).toarray()[0]
scores = doc_matrix @ q # cosine similarities
best = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), notes[i][:40]) for i in best]
print(doc_matrix.shape)
print(search("car battery flat"))
print(search("how often to water tomato plants"))
print(search("my automobile won't turn on")) # same meaning, no shared words
# (6, 36)
# [(0.76, 'The car would not start this morning; th'), (0.19, 'Renew the car insurance before the end o')]
# [(0.61, 'Water tomato plants deeply twice a week '), (0.0, 'Repot the fig tree in spring with fresh ')]
# [(0.0, 'Repot the fig tree in spring with fresh '), (0.0, 'The car would not start this morning; th')]
The first two queries work because they share words with the right note. The third fails completely: every score is 0, because "automobile", "turn" and "on" appear in no note. That is exactly the gap neural embeddings close.
To use real embeddings, replace only the two lines that make vectors. With the open-source sentence-transformers library (pip install sentence-transformers, downloads a model of about 90 MB on first use):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # 384 dimensions
doc_matrix = model.encode(notes, normalize_embeddings=True) # shape (6, 384)
def search(query, k=2):
q = model.encode([query], normalize_embeddings=True)[0]
scores = doc_matrix @ q
best = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), notes[i][:40]) for i in best]
Or with OpenAI's embedding API (pip install openai, key in OPENAI_API_KEY):
from openai import OpenAI
client = OpenAI()
def embed(texts):
response = client.embeddings.create(model="text-embedding-3-small", input=texts)
return np.array([item.embedding for item in response.data]) # (len(texts), 1536)
doc_matrix = embed(notes) # already unit length, so dot product = cosine
query_vec = embed(["my automobile won't turn on"])[0]
print(notes[int(np.argmax(doc_matrix @ query_vec))])
With either, the automobile query finds the car note. Embed documents in batches (the API accepts a list) and save the matrix with np.save, so you pay to embed each document only once.
Common pitfalls
- Mixing models. Vectors from different embedding models, or even different versions of one model, live in different spaces and can't be compared. If you change models, re-embed everything.
- Treating scores as absolute. A cosine of 0.8 might be a great match for one model and mediocre for another. Use rankings, or calibrate a threshold on your own labelled examples.
- Embedding whole documents. One vector for a 50-page manual averages away the details. Split documents into passages of a few hundred tokens first (see Retrieval-Augmented Generation).
- Expecting embeddings to match exact identifiers. "Error E-4012" and "Error E-4021" may embed almost identically. For codes, names and numbers, add keyword search (Advanced RAG).
- Not evaluating. "The results look sensible" is not a test. Collect real queries with known right answers and measure how often the right passage appears in the top (Advanced RAG shows how).
Watch out Semantic search always returns something: the nearest vectors, even if nothing is relevant. A question about tax law over a gardening corpus will still return the "closest" gardening notes. Downstream code, and especially an LLM answering from the results, must be prepared for retrieved text that doesn't actually answer the question.
Where it leads
- Vector Databases: searching millions of vectors quickly, with filters and updates.
- Retrieval-Augmented Generation: feeding the retrieved passages to an LLM so it answers from your documents.
- Advanced RAG: hybrid keyword-plus-vector search, reranking and measuring retrieval quality.
- Sentence Embeddings: how embedding models are trained.
- CLIP and Contrastive Learning: embeddings that put images and text in the same space, so you can search photos by description.
- Recommender Systems and k-Nearest Neighbours: the same nearest-neighbour idea applied to users, products and classification.
A bit of history
Representing documents as vectors and comparing them by cosine is old: Gerard Salton's vector space model for information retrieval dates from the 1960s and 1970s, and TF-IDF weighting from the same period. These were sparse, word-based vectors. Latent semantic analysis (1990) compressed them with SVD to capture some synonymy. Word2vec (2013) showed that neural networks could learn dense vectors in which meaning has geometry. Sentence-BERT (2019) made good sentence embeddings cheap to compute, and Dense Passage Retrieval (2020) showed learned embeddings beating keyword search at finding answers to questions. OpenAI, Cohere, Google, Voyage and others then offered embeddings as an API, and in 2023 the rise of RAG made semantic search a standard part of almost every LLM application.
Try it
- Add ten notes of your own to the offline example, and write five queries that use different words from the notes they should find. How many does TF-IDF get right in the top 2?
- If you can install
sentence-transformers, swap it in and run the same five queries. Compare.- Compute the cosine similarity of the worked example's vectors with NumPy, then normalise all three vectors and check that a plain dot product gives the same numbers.
Hint for 1: TF-IDF succeeds when the query and the note share a distinctive word. Try to write queries that don't, and you'll see where meaning-based search earns its keep.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Vector embeddings guide
How to create embeddings with the OpenAI API, the available models and dimensions, and use cases such as search, clustering and recommendations.
Sentence Transformers documentation
The standard Python library for computing, training and fine-tuning sentence embeddings, with many pretrained models and examples.
MTEB Leaderboard
A live ranking of text-embedding models by task and language. The place to shortlist an embedding model, then test it on your own data.
Vector Databases: from Embeddings to Applications
A short course on how vector databases work: embeddings, brute-force and approximate search, HNSW, hybrid search and multilingual search.
Sentence-BERT
Siamese BERT networks that produce useful sentence embeddings.
Dense Passage Retrieval for Open-Domain Question Answering
Showed that learned dense embeddings beat BM25 keyword search for finding passages that answer questions, the foundation of embedding-based retrieval.
MTEB: Massive Text Embedding Benchmark
A benchmark of embedding models across many tasks (retrieval, clustering, classification, similarity) and languages, with a public leaderboard.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/semantic-search.md