Embeddings and vector search
Semantic search is the engine of RAG. In this module you'll build it from scratch and see both its power and its blind spots.
Learning objectives
- Explain embeddings and cosine similarity
- Implement semantic search in Python
- Describe approximate nearest neighbour indexes and vector databases
- Choose an embedding model with appropriate criteria
- Read a similarity table and explain why scores aren't comparable across models
- Judge when an approximate index is needed
2.1 Embeddings recap
An embedding turns a piece of text into a list of numbers — a vector — so that texts with similar meanings get similar vectors. Embedding models are trained specifically for this. Commercial embedding APIs typically return between several hundred and a few thousand numbers per text; open-source models from the sentence-transformers family commonly return 384, 768 or 1,024.
2.2 Measuring similarity
The standard measure is cosine similarity: the cosine of the angle between two vectors. It ranges from −1 to 1; higher means more similar meaning. Many embedding models produce normalised vectors (length 1), in which case cosine similarity is simply the dot product.
Python · cosine similarity from scratchimport numpy as np
def cosine(a, b):
a, b = np.array(a), np.array(b)
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
print(cosine([1, 0], [1, 0])) # 1.0 same direction
print(cosine([1, 0], [0, 1])) # 0.0 unrelated
print(cosine([1, 0], [-1, 0])) # -1.0 opposite
print(round(cosine([3, 1], [6, 2]), 3)) # 1.0: length doesn't matter, only direction
2.3 Semantic search in a few lines
Python · semantic search with an embeddings API (practice mode on this page)from openai import OpenAI
client = OpenAI() # the real SDK reads OPENAI_API_KEY from the environment
EMBED_MODEL = "YOUR-EMBEDDING-MODEL" # copy a current model name from the provider's docs
def embed(texts):
resp = client.embeddings.create(model=EMBED_MODEL, input=list(texts))
return np.array([d.embedding for d in resp.data])
docs = [
"Damaged items can be returned within 30 days for a full refund.",
"Standard UK delivery takes 3 to 5 working days.",
"Our bamboo boards should be hand-washed and oiled monthly.",
"Gift cards are valid for 12 months from purchase.",
]
doc_vecs = embed(docs) # embed the documents once
def search(query, k=2):
q = embed([query])[0]
scores = doc_vecs @ q # cosine, because the vectors are normalised
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 3), docs[i]) for i in top]
print(search("my chopping board arrived cracked, can I get my money back?"))
Notice the query shares almost no words with the refund policy ("cracked" vs "damaged", "money back" vs "refund") — yet semantic search finds it. That's the power of embeddings.
You can also run an embedding model yourself, with no API and no per-request cost. The open-source route looks like this (it downloads a model of about 90 MB, so it is for a notebook, not this page):
Python · the same search with an open-source model (for Colab or your own computer)# !pip install sentence-transformers
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # small, free, runs on CPU
doc_vecs = model.encode(docs, normalize_embeddings=True)
q = model.encode(["my chopping board arrived cracked"], normalize_embeddings=True)[0]
print(docs[int(np.argmax(doc_vecs @ q))])
2.4 Vector databases and indexes
Comparing a query with every vector works for thousands of chunks. For millions, systems use approximate nearest neighbour (ANN) indexes, such as HNSW graphs, that find very close matches much faster by trading a little accuracy for speed.
Options range from libraries (FAISS) to dedicated vector databases and vector features in existing databases (e.g. PostgreSQL with pgvector) and cloud search services (Azure AI Search, Amazon OpenSearch, Google Vertex AI Vector Search). Choose based on scale, filtering needs, security and what your team already runs.
2.5 Choosing an embedding model
- Quality on your data — test a few models on real queries (Module 6). Public leaderboards are a starting point, not an answer.
- Language and domain — multilingual content or specialised jargon needs a model that handles it.
- Size and cost — dimensions affect storage and speed; some models let you shorten vectors.
- Privacy — sending documents to an API vs running a model yourself.
- Consistency — queries and documents must be embedded with the same model. Changing models means re-embedding everything.
2.6 Looking inside
An embedding is easier to trust once you've looked at one. Each text becomes a row of numbers; comparing every row with every other gives a table of similarities.
Python · what the vectors look likeimport pandas as pd
print("Shape:", doc_vecs.shape, "→", doc_vecs.shape[0], "texts,", doc_vecs.shape[1], "numbers each")
print("Length of the first vector:", round(float(np.linalg.norm(doc_vecs[0])), 3), "(normalised)")
labels = ["returns", "delivery", "care", "gift cards"]
print(pd.DataFrame(doc_vecs @ doc_vecs.T, index=labels, columns=labels).round(2))
The diagonal is 1.0: every text is identical to itself. Off the diagonal the numbers are low, because these four documents are about different things. Similarity scores have no fixed meaning across models: 0.5 may be a strong match for one model and a weak one for another. What matters is the ranking, and where you set any cut-off has to be worked out on your own data.
2.7 How far does simple search stretch?
The search above compares the question with every stored vector. It is worth knowing how far that gets you before reaching for a vector database.
Python · timing a search over 100,000 vectorsimport time
rng = np.random.default_rng(0)
many = rng.normal(size=(100_000, 384)).astype("float32")
many /= np.linalg.norm(many, axis=1, keepdims=True) # normalise each row
query = many[0]
start = time.perf_counter()
scores = many @ query
top5 = np.argsort(-scores)[:5]
print(f"Compared with {len(many):,} vectors in {(time.perf_counter() - start) * 1000:.0f} ms")
print("Storage for these vectors:", round(many.nbytes / 1_000_000), "MB")
A hundred thousand chunks is several thousand pages of documents, and searching all of them takes a fraction of a second even in a browser. Many real projects never outgrow this. An approximate index earns its place when you reach millions of chunks, need answers in a few milliseconds, or need filtering and updates handled for you.
The starter code adds a product-code document to the list. Search for "BB-204" and print the results with their scores. Does semantic search rank the right document first? Then try "what is the large bamboo board called?"
Your turnimport numpy as np
from openai import OpenAI
client = OpenAI()
def embed(texts):
resp = client.embeddings.create(model="YOUR-EMBEDDING-MODEL", input=list(texts))
return np.array([d.embedding for d in resp.data])
docs2 = [
"Damaged items can be returned within 30 days for a full refund.",
"Standard UK delivery takes 3 to 5 working days.",
"Our bamboo boards should be hand-washed and oiled monthly.",
"Product code BB-204 is our large bamboo board.",
]
vecs2 = embed(docs2)
def search2(query, k=2):
scores = vecs2 @ embed([query])[0]
return [(round(float(scores[i]), 3), docs2[i]) for i in np.argsort(-scores)[:k]]
# Search for "BB-204", then press RunShow a solution
import numpy as np
from openai import OpenAI
client = OpenAI()
def embed(texts):
resp = client.embeddings.create(model="YOUR-EMBEDDING-MODEL", input=list(texts))
return np.array([d.embedding for d in resp.data])
docs2 = [
"Damaged items can be returned within 30 days for a full refund.",
"Standard UK delivery takes 3 to 5 working days.",
"Our bamboo boards should be hand-washed and oiled monthly.",
"Product code BB-204 is our large bamboo board.",
]
vecs2 = embed(docs2)
def search2(query, k=2):
scores = vecs2 @ embed([query])[0]
return [(round(float(scores[i]), 3), docs2[i]) for i in np.argsort(-scores)[:k]]
print(search2("BB-204"))
print(search2("what is the large bamboo board called?"))
# The code alone scores zero against everything: to an embedding model it is not a word with a meaning.
# The worded question does better. Exact identifiers are the classic weak spot of embeddings,
# and the reason Module 4 adds keyword search alongside.A search always returns something, even for a question the documents can't answer. Write search_or_none(query, minimum=0.3) that returns the best document and its score, or None if the best score is below the minimum. Test it with one question the documents cover and one they don't.
Your turnimport numpy as np
from openai import OpenAI
client = OpenAI()
def embed(texts):
resp = client.embeddings.create(model="YOUR-EMBEDDING-MODEL", input=list(texts))
return np.array([d.embedding for d in resp.data])
docs2 = [
"Damaged items can be returned within 30 days for a full refund.",
"Standard UK delivery takes 3 to 5 working days.",
"Our bamboo boards should be hand-washed and oiled monthly.",
"Gift cards are valid for 12 months from purchase.",
]
vecs2 = embed(docs2)
def search2(query, k=2):
scores = vecs2 @ embed([query])[0]
return [(round(float(scores[i]), 3), docs2[i]) for i in np.argsort(-scores)[:k]]
# Write search_or_none(query, minimum=0.3), then press RunShow a solution
import numpy as np
from openai import OpenAI
client = OpenAI()
def embed(texts):
resp = client.embeddings.create(model="YOUR-EMBEDDING-MODEL", input=list(texts))
return np.array([d.embedding for d in resp.data])
docs2 = [
"Damaged items can be returned within 30 days for a full refund.",
"Standard UK delivery takes 3 to 5 working days.",
"Our bamboo boards should be hand-washed and oiled monthly.",
"Gift cards are valid for 12 months from purchase.",
]
vecs2 = embed(docs2)
def search2(query, k=2):
scores = vecs2 @ embed([query])[0]
return [(round(float(scores[i]), 3), docs2[i]) for i in np.argsort(-scores)[:k]]
def search_or_none(query, minimum=0.3):
score, doc = search2(query, k=1)[0]
return (doc, score) if score >= minimum else None
print(search_or_none("how long does delivery take?"))
print(search_or_none("do you sell electric cars?"))
# Returning nothing is a feature: it lets the system say "I can't find that" instead of answering from an irrelevant passage.
# The right minimum differs for every embedding model; set it using test questions (Module 6).Key takeaways
- Embeddings map meaning to vectors; similar meaning → similar vectors.
- Cosine similarity measures closeness; with normalised vectors it's the dot product.
- Semantic search handles paraphrases but can miss exact identifiers.
- ANN indexes make search fast at scale.
- Use the same embedding model for documents and queries; test candidates on your data.
- Similarity scores only rank; any cut-off must be set on your own data.
- Comparing with every vector is fast up to hundreds of thousands of chunks.