Vector Search
Vector search (semantic search) finds items whose embeddings are closest to a query's embedding. Unlike keyword search, it can match "How do I get my money back?" with a passage about "refunds" even though no word is shared — as long as the embedding model places them close together. It is the retrieval engine behind most RAG systems.
How it works
- Index: embed every chunk with an embedding model → a matrix of vectors (one row per chunk), plus the chunk text and metadata.
- Query: embed the question with the same model.
- Score: compute similarity (usually cosine) between the query vector and every chunk vector.
- Return the top-k chunks.
With an embedding API, step 1 is a call such as embed(["chunk one", "chunk two", …]) that returns one vector per text. Here we use small hand-made vectors so you can see the mechanics; real embeddings have hundreds to thousands of dimensions.
Brute-force search with NumPy
import numpy as np
chunks = ["Refunds are issued within 14 days.", "Our store opens at 9am.",
"You can send items back for a full refund.", "Parking is free for customers.",
"Delivery takes three working days."]
# money time place return shipping
vecs = np.array([
[0.9, 0.3, 0.0, 0.6, 0.0],
[0.0, 0.9, 0.4, 0.0, 0.0],
[0.7, 0.0, 0.0, 0.9, 0.2],
[0.1, 0.0, 0.9, 0.0, 0.1],
[0.0, 0.5, 0.1, 0.1, 0.9],
])
index = vecs / np.linalg.norm(vecs, axis=1, keepdims=True) # normalise once
def search(query_vec, k=2):
q = query_vec / np.linalg.norm(query_vec)
scores = index @ q # cosine = dot product
top = np.argsort(-scores)[:k]
return [(chunks[i], round(float(scores[i]), 3)) for i in top]
# pretend embedding of "How do I get my money back?"
query = np.array([0.8, 0.0, 0.0, 0.8, 0.0])
for text, score in search(query):
print(f"{score:.3f} {text}")0.977 You can send items back for a full refund.
0.945 Refunds are issued within 14 days.
This exact search compares the query with every vector. With NumPy that is fast for tens of thousands of chunks; for millions you need an index.
Approximate nearest neighbours (ANN)
Vector databases use approximate indexes that check only a fraction of the vectors. One classic idea (IVF, "inverted file") clusters the vectors, then searches only the clusters closest to the query:
import numpy as np
rng = np.random.default_rng(0)
centers = rng.normal(size=(8, 16)) * 3
data = np.vstack([c + rng.normal(size=(500, 16)) for c in centers]) # 4,000 vectors
data /= np.linalg.norm(data, axis=1, keepdims=True)
# Build the index: a few rounds of k-means clustering (8 clusters)
centroids = data[rng.choice(len(data), 8, replace=False)]
for _ in range(10):
labels = np.argmax(data @ centroids.T, axis=1) # nearest centroid (cosine)
centroids = np.array([data[labels == c].mean(axis=0) for c in range(8)])
centroids /= np.linalg.norm(centroids, axis=1, keepdims=True)
query = data[1234] + rng.normal(scale=0.05, size=16)
query /= np.linalg.norm(query)
exact = np.argsort(-(data @ query))[:5]
nearest_clusters = np.argsort(-(centroids @ query))[:2] # probe 2 of 8 clusters
candidates = np.where(np.isin(labels, nearest_clusters))[0]
approx = candidates[np.argsort(-(data[candidates] @ query))[:5]]
print("vectors compared, exact: ", len(data))
print("vectors compared, approx:", len(candidates))
print("recall@5:", len(set(exact.tolist()) & set(approx.tolist())) / 5)vectors compared, exact: 4000
vectors compared, approx: 1500
recall@5: 1.0
The approximate search compared 1,500 of the 4,000 vectors and still found the same top 5 (recall 1.0). With more clusters, each probe would touch an even smaller share of the data. Real systems use more refined structures such as HNSW graphs or product quantisation, and you tune them to balance speed against recall.
Metadata filters and hybrid search
Production queries usually combine vector similarity with filters ("only documents this user may see", "only 2025 policies"). And because embeddings can miss exact terms — product codes, names, error numbers — many systems use hybrid search: combine a keyword score (BM25 / TF-IDF) with the vector score.
docs = [
{"text": "Error E42 means the water tank is empty.", "product": "coffee", "vec_score": 0.62, "kw_score": 1.0},
{"text": "Refill the tank when the light blinks.", "product": "coffee", "vec_score": 0.81, "kw_score": 0.0},
{"text": "Error E42 on the kettle: base not connected.", "product": "kettle", "vec_score": 0.60, "kw_score": 1.0},
]
def hybrid(docs, product, alpha=0.5):
allowed = [d for d in docs if d["product"] == product] # metadata filter
for d in allowed:
d["score"] = alpha * d["vec_score"] + (1 - alpha) * d["kw_score"]
return sorted(allowed, key=lambda d: -d["score"])
for d in hybrid(docs, product="coffee"):
print(f"{d['score']:.3f} {d['text']}")0.810 Error E42 means the water tank is empty.
0.405 Refill the tank when the light blinks.
For the query "What does error E42 mean?" on a coffee machine, the keyword component lifts the exact error-code match to the top, and the filter removes the kettle document.
Choosing tools
| Scale | Typical choice |
|---|---|
| Up to ~100k chunks | NumPy / in-memory brute force, or a simple library |
| Larger, single app | a vector extension of your existing database (e.g. PostgreSQL with a vector type) |
| Very large / many tenants | a dedicated vector database with ANN indexes, filters and replication |
Note: Always embed queries and documents with the same embedding model, and re-embed everything if you switch models — vectors from different models are not comparable.
Go further: Dense Retrieval and Semantic Similarity compares BM25 with dense embeddings, adds re-ranking and trains a retriever with in-batch negatives.
Test yourself
Why can vector search match 'money back' with a passage about 'refunds'?
- It uses exact keyword matching
- Their embeddings are close because the meanings are similar
- It translates both to numbers by spelling
- It ignores the query
What do approximate nearest-neighbour indexes trade for speed?
- Nothing
- A small chance of missing some true nearest neighbours (recall)
- The ability to store text
- Cosine similarity
Why combine keyword and vector scores (hybrid search)?
- Embeddings can miss exact terms like codes and names
- Keyword search is always better
- Vector search can't use filters
- It reduces the index size