RAG & retrieval Guide 20 of 25
Embeddings and vector search: a practical guide for engineers
Vector search is two systems: a model that decides what “similar” means, and an index that finds similar items fast. Each fails in its own way, and each needs its own test.
Key takeaways
- The embedding model sets retrieval quality; the index sets speed. Test them separately: the model against labeled queries, the index against exact search.
- Vectors are only comparable within one model and version. Store the model ID with every vector and budget for a full re-embed when you upgrade.
- HNSW is the usual default when vectors fit in memory. IVF and quantization give up some recall to fit far larger collections.
- Shorter vectors and int8 or binary storage, with rescoring, can cut memory four to 32 times while keeping most retrieval quality. Test your own model first.
- Vectors alone miss exact identifiers, and keyword search misses paraphrases. Combine both, then add metadata filters and a reranker.
On this page 8 sections
Semantic search, retrieval-augmented generation (RAG), “more like this” recommendations, and duplicate detection all rest on the same two moves. A model turns each item into a list of numbers, and a search routine finds the stored lists closest to the query’s.
Teams usually start with the second move, by picking a vector database. That is backwards. The embedding model decides what “similar” means and sets most of your retrieval quality, while vector count, dimensions, and precision set most of the bill. The index is a speed-for-accuracy dial between the two.
What is an embedding?
An embedding is a fixed-length list of floating-point numbers that a model produces from an input such as a sentence, an image, or a function of code. The model is trained so that related inputs land close together. Most modern text models learn this contrastively: training pulls matching pairs, such as a query and its answer, together and pushes mismatches apart. Microsoft’s Harrier model card, for example, says its models were trained this way (Microsoft, 2026).
The payoff is matching without shared words. “How do I get back into my account?” and “Resetting a forgotten password” share no keywords, yet a decent model puts them near each other. Individual coordinates rarely mean anything on their own; the information lives in the distances. OpenAI’s text-embedding-3-small returns 1,536 numbers per input, and text-embedding-3-large returns 3,072 (OpenAI).
Closeness is measured with cosine similarity, dot product, or Euclidean distance. Once vectors are normalized to length 1, the choice barely matters: as OpenAI’s guide points out, cosine then reduces to a dot product and ranks exactly as Euclidean distance does (OpenAI). Two practical rules follow:
- Vectors are only comparable within one model. A vector from model A cannot be searched against vectors from model B, or from a new version of A. Switching models means re-embedding everything.
- Queries and documents are often encoded differently. Many recent models expect each query to carry a short task instruction. Harrier’s model card warns that omitting it degrades results (Microsoft).
How do you choose an embedding model?
The usual starting point is MTEB, the Massive Text Embedding Benchmark, which averages scores across many retrieval, clustering, and classification tasks. It is a fair shortlist filter and a poor final judge. Your support tickets or part catalog are not the average of its tasks, and scores from different MTEB versions are not comparable.
As of October 2026, OpenAI’s embeddings guide still lists its two third-generation models, at 62.3% (small) and 64.6% (large) on MTEB (OpenAI). Open-weight models now compete at the top of public leaderboards. Microsoft’s Harrier family, published in March 2026 under the MIT license, spans 270 million to 27 billion parameters. It accepts 32,768-token inputs and claimed state-of-the-art results on multilingual MTEB v2 at release (Microsoft).
What should actually decide the choice:
| Criterion | Why it matters |
|---|---|
| Recall on your own labeled queries | The only quality number that predicts production behavior |
| Languages and domain vocabulary | Averages hide weak languages and jargon |
| Maximum input length | Caps your chunk size; OpenAI’s models accept 8,192 tokens |
| Dimensions | Storage and memory grow in direct proportion |
| Price or hosting cost | Per-token fees for a hosted application programming interface (API), or graphics processing unit (GPU) time for open weights |
| Data residency and latency | Self-hosting keeps text in-house; a 27-billion-parameter model needs serious GPUs |
Embedding itself is usually the cheap part. OpenAI’s published pages-per-dollar figures work out to about $0.02 per million tokens for the small model and $0.13 for the large one (OpenAI). One million 500-token chunks therefore cost roughly $10 or $65 to embed. The expensive mistakes are a model that misreads your domain and the migration needed to replace it.
Why exact search stops scaling
The simplest search is exact, or brute force: compare the query with every stored vector and keep the closest. It always returns the true nearest neighbors, and it is what pgvector, the PostgreSQL extension, does by default (pgvector). Its cost grows linearly with the collection. At 10 million vectors of 1,536 dimensions, every query does about 15 billion multiply-adds across roughly 61 GB of 32-bit floats.
Approximate nearest neighbor (ANN) indexes skip the full scan by examining only promising regions. The authors of Faiss, Meta’s open-source vector search library, treat this as the standard approach above roughly 10,000 vectors, though brute force sometimes remains the right call (Douze et al., 2024). The price is recall. Recall@k, the share of the true top-k neighbors the index actually returns, becomes a tuning knob.
pgvector’s documentation flags a surprise: unlike an ordinary database index, adding an ANN index changes what queries return. That leaves two quality questions needing two tests. Does the model rank the right documents highly under exact search? And how much does the index lose relative to exact search?
import numpy as np
def exact_top_k(q, X, k=10):
# Rows of X and q are unit-normalized, so the
# dot product is cosine similarity.
return set(np.argsort(-(X @ q))[:k])
def index_recall_at_k(queries, X, ann_search, k=10):
"""Average share of the exact top-k that the ANN
index also returns."""
scores = []
for q in queries:
found = set(ann_search(q, k))
scores.append(len(exact_top_k(q, X, k) & found) / k)
return sum(scores) / len(scores)
How do approximate nearest neighbor indexes work?
Two search structures and one compression technique cover most production systems; libraries and databases mostly differ in how they combine them.
Graph indexes: HNSW
Hierarchical Navigable Small World (HNSW) links each vector to a few close neighbors and stacks sparser layers above. A query takes long hops across the sparse top layers, then walks greedily toward its target in the dense bottom layer. More links per node buy recall with memory and build time; a longer candidate list during search (hnsw.ef_search in pgvector) buys recall with latency.
Of pgvector’s two index types, HNSW gives the better balance of speed and recall, and pays for it in memory and build time (pgvector). Deletions are awkward: Faiss’s HNSW cannot remove vectors, and libraries that can, such as hnswlib, rely on graph-repair heuristics the Faiss authors call suboptimal (Douze et al., 2024). Spotify’s Voyager library, open-sourced in October 2023, builds on hnswlib. Spotify reported over 10 times the speed of its older Annoy library at equal recall, with up to four times less memory thanks to 8-bit floats (Spotify).
Inverted file indexes: IVF
An inverted file (IVF) index groups vectors into clusters with k-means, then searches only the clusters nearest the query. The number of clusters probed is the recall dial. Next to HNSW it builds faster and needs less memory, but delivers less speed at the same recall (pgvector). It also needs training on representative data first.
Quantization: compressing the vectors themselves
Product quantization (PQ) splits each vector into short sub-vectors and replaces each with the index number of its nearest entry in a learned codebook. By the code-size formula in the Faiss paper, 64 sub-vectors with 256-entry codebooks turn a 6,144-byte vector into 64 bytes, at the cost of approximate distances (Douze et al., 2024).
Google’s ScaNN (Scalable Nearest Neighbors), announced on 28 July 2020, penalizes compression error parallel to each vector more heavily than error at right angles. Parallel error distorts the high similarity scores that decide rankings. On the glove-100-angular benchmark, it handled roughly twice the queries per second of the next-fastest library at equal accuracy (Google Research, 2020). Rankings shift with the dataset, though: a 2025 revision of the Faiss paper put Faiss ahead of ScaNN in its own test (Douze et al., 2024).
The Faiss paper offers a rule of thumb. Graph indexes fit when memory is plentiful, typically under a million vectors, and past about 10 million their build time becomes the bottleneck. Once vectors must be compressed to fit in memory at all, IVF-based indexes are the only practical choice (Douze et al., 2024).
| Index | How it finds neighbors | Strength | Cost | Reach for it when |
|---|---|---|---|---|
| Flat (exact) | Compares every vector | Perfect recall, nothing to tune | Time grows linearly | Small collections or heavily filtered subsets |
| HNSW | Greedy walk on a layered graph | Strong speed–recall balance | Memory for links, slow builds, awkward deletes | Up to millions of vectors held in memory |
| IVF | Probes the nearest clusters | Fast builds, lower memory | Needs training; lower recall at equal speed | Large collections, often with compression |
| Quantized (PQ, ScaNN) | Approximate distances on compact codes | Huge collections fit in memory | Recall loss; needs reranking | Raw vectors will not fit in memory |
How do you make vectors smaller without losing quality?
Memory is vector count times dimensions times bytes per number, plus index overhead. Hugging Face’s 2024 analysis sized 250 million 1,024-dimension float vectors at 953.67 GB, about $3,623 a month of cloud memory by its estimate (Hugging Face, 2024). Three levers shrink that, and they stack:
- Fewer dimensions. Models trained for truncation let you keep only the leading numbers. OpenAI says its large model, cut to 256 dimensions, still beats its older 1,536-dimension ada-002 model on MTEB (OpenAI). Use the API’s
dimensionsparameter, or renormalize if you truncate by hand. - Lower precision. In the same Hugging Face tests, one strong model stored as 8-bit integers (int8), four times smaller, kept about 97% of its retrieval quality, and about 99% with rescoring. Binary storage, 32 times smaller, kept about 92.5% alone and about 96% with rescoring. A weaker model lost a quarter of its quality in binary, so test yours.
- Rescoring. Fetch extra candidates with the compressed vectors, then rerank them using the full-precision query vector. This cheaply recovers much of the lost quality.
Check your store’s limits too. pgvector indexes standard vectors up to 2,000 dimensions and half-precision vectors up to 4,000 (pgvector). A 3,072-dimension embedding must be stored at half precision, shortened, or binary-quantized before it can be indexed there.
Where does vector search fail?
Exact identifiers. Embeddings blur product codes, error numbers, names, and version strings — exactly what users paste verbatim. Keyword ranking with BM25 (Best Matching 25, the classic term-weighting formula) handles them well, so many production systems run both and merge the results.
Too many combinations. An August 2025 paper from Google DeepMind and Johns Hopkins University shows that embedding dimension caps how many distinct top-k result sets single-vector retrieval can return (Weller et al., 2025). Its LIMIT dataset was built to hit that cap with simple queries. On the 50,000-document version, no single-vector model reached 20% recall@100, while BM25 reached 93.6%.
Keyword search is no cure-all, though: on a small variant where synonyms replaced the shared words, BM25 fell by more than 89% and trailed most neural models. Everyday queries are rarely that adversarial, but the more document combinations your queries must return, the nearer that ceiling gets.
Filters. With ANN indexes, metadata filters often apply only after the index returns its candidates. pgvector’s documentation gives an example: when a filter matches 10% of rows, default HNSW settings return about four results on average. Version 0.8.0 added iterative scans that keep searching until enough rows match (pgvector). The Faiss authors describe the alternative: filter first, then brute-force the subset, which is exact and affordable when the subset is small (Douze et al., 2024).
Change. Documents get edited and deleted, and models get upgraded. Structures fitted to yesterday’s data, such as IVF clusters and PQ codebooks, lose efficiency as the data drifts (Douze et al., 2024). Treat re-indexing and re-embedding as routine maintenance.
Do you need a dedicated vector database?
Often not at first. Three shapes cover most deployments:
- An in-process library such as Faiss or Voyager. Many Spotify systems hold indexes in memory inside stateless services, sparing them a database cluster. As Spotify’s engineers put it, “extreme accuracy can be sacrificed for a significant decrease in cost” (Spotify).
- A database extension such as pgvector. Vectors sit next to the rows they describe, with the transactions, joins, access control, and backups you already run.
- A dedicated vector database. It earns its place with very large collections, heavy filtering, built-in hybrid search, or multi-tenancy at scale.
Our default for a company already on PostgreSQL with up to a few million vectors is pgvector, revisited when measured latency or filter behavior says otherwise.
What this means for your team
- Build the evaluation set first. Collect 100–300 real queries, the range our evals guide suggests for cheap-to-label items, and label the documents each should return. Measure recall@10 under exact search, so model quality is never confused with index loss.
- Shortlist two or three models, including an open-weight one, and compare them on that set alongside cost, latency, languages, and hosting.
- Version every vector. Store the model name, version, dimensions, and query instruction, and budget for a full re-embed at each upgrade.
- Start exact; add an index when latency demands it. Then measure its recall against exact search at realistic filter selectivity, and tune
ef_searchor probes. - Do the memory math early. Shorten and quantize, with rescoring, before buying bigger machines.
- Never rely on vectors alone. Pair them with keyword search, metadata filters, and a reranker.
- Monitor in production. Track short result lists, 95th-percentile latency, and recall on a fixed regression set after every change.
Vector search looks like infrastructure, but its quality is set by an evaluation set many teams never build. When SurgeX Labs builds retrieval systems, that set comes first, so the embedding model and the index can be tested separately.
Sources
-
Vector embeddings (opens in new tab) — OpenAI (OpenAI API docs), 2026 developers.openai.com
-
harrier-oss-v1-27b (model card) (opens in new tab) — Microsoft (Hugging Face), 2026 huggingface.co
-
The Faiss library (opens in new tab) — FAIR at Meta, Zilliz, et al. (arXiv), 2024 arxiv.org
-
Announcing ScaNN: Efficient Vector Similarity Search (opens in new tab) — Google Research, 2020 research.google
-
Introducing Voyager: Spotify’s New Nearest-Neighbor Search Library (opens in new tab) — Spotify Engineering, 2023 engineering.atspotify.com
-
Binary and Scalar Embedding Quantization for Significantly Faster & Cheaper Retrieval (opens in new tab) — Hugging Face, 2024 huggingface.co
-
On the Theoretical Limitations of Embedding-Based Retrieval (opens in new tab) — Google DeepMind and Johns Hopkins University (ICLR 2026, arXiv), 2025 arxiv.org
-
pgvector: Open-source vector similarity search for Postgres (opens in new tab) — pgvector (GitHub), 2026 github.com
Where this shows up in our work
- Solution blueprint Your knowledge, answering with citations — RAG knowledge assistant with citations
- Solution blueprint A catalog that describes itself — LLM catalog enrichment & semantic search