Learn
RAG & vector databases

How Embeddings and Vector Databases Work

The short answer

An embedding turns text into a point in a high-dimensional space where distance means similarity, and a vector database finds the nearest points fast without scanning everything. This explains the geometry, how the models are trained, how HNSW and IVF-PQ trade recall for speed, the memory arithmetic, and where production systems break.

On this page

What an embedding actually is

An embedding model maps text to a fixed-length list of floats — 768, 1,024 or 1,536 dimensions are common — learned so that texts with similar meaning land near each other. That is the whole trick. Everything else in a vector database is engineering on top of it: a data structure for finding near neighbours fast in a space with hundreds of dimensions and millions of points.

The geometry explains the failure modes. Directions correspond to concepts, and the model compresses a whole passage into one point, so it must discard most of the detail. A 600-token chunk about refund eligibility for enterprise plans becomes one vector blending refund, eligibility, enterprise and duration; a query about duration alone meets a blurred summary of four topics. That is why chunking and embedding are inseparable, and why vector search returns results that are topically right and specifically wrong.

Embeddings are also not interpretable dimension by dimension. Dimension 412 does not mean formality. The representation is distributed, and the only meaningful operations are distance, clustering and linear combination. Attempts to read semantics off individual axes produce stories, not measurements.

Similarity is a choice, and cosine is not magic

Three metrics dominate: dot product, cosine and Euclidean distance. For unit-length vectors all three rank results identically — cosine equals the dot product, and squared Euclidean distance is a monotone function of it. Most modern models ship normalised outputs, precisely so the cheap dot product works. Skip normalisation and longer vectors score higher, and since length correlates with text length, you rank by verbosity.

Cosine is the safe default when you are unsure, because it ignores magnitude and compares only direction. Euclidean distance is the right choice when the model was trained with it, which is true for some older and some image models. The practical rule: use whatever the model card specifies, and if it says cosine, normalise once at write time and use dot product at query time for speed.

A subtlety that bites: similarity scores are not comparable across queries. A top score of 0.82 means nothing in absolute terms — the distribution depends on the query's specificity and the corpus. Never threshold on raw similarity to decide whether an answer exists unless you have calibrated that threshold per embedding model on your own data. Use a reranker or an explicit relevance classifier instead.

How the models learn what similar means

Most text embedding models are trained with a contrastive objective. Each training item is an anchor (a query), a positive (a passage that answers it) and a set of negatives (passages that do not). The loss pulls the anchor towards the positive and pushes it away from the negatives. What counts as similar is therefore defined entirely by the training data, not by an abstract notion of meaning. A model trained mostly on web question-answer pairs will treat FAQ-style paraphrases as similar and may treat two passages that share a legal conclusion but differ in jurisdiction as dissimilar.

Negatives are where quality comes from. Easy negatives — random passages — are trivially separable and stop teaching after one epoch. Hard negatives, passages a retriever ranked highly but that are wrong, force fine distinctions. Mining them needs a first-stage retriever, which is why good models are trained in rounds: train, mine with the current model, retrain.

Symmetric versus asymmetric training matters for RAG. If the model only ever saw question-question pairs, embedding a question and a 500-token passage puts them in different regions and retrieval degrades. Models intended for retrieval are trained on query-passage pairs, often with an instruction prefix on the query side — the e5 family's query: and passage: prefixes are the familiar example. Mismatching the prefix convention at inference is a common and silent quality loss.

Dimensions, truncation and Matryoshka

Higher dimension is not automatically better. A 3,072-dimension model can encode finer distinctions but costs four times the storage of a 768-dimension one and slows every distance computation. For many domain corpora, a well-trained 768-dimension model matches a general 3,072-dimension model, and the smaller one is four times cheaper to serve.

Matryoshka representation learning trains a model so that the first 256, 512 or 1,024 dimensions are themselves usable embeddings, nested like dolls. You can store the full vector and truncate at query time, or store a short version for a first pass and rescore with the full vector. Truncating from 1,536 to 256 typically costs a few points of recall on general benchmarks and cuts memory by six times, which is often the best available trade at scale.

Quantisation is the other lever. Float32 to float16 halves storage with almost no quality loss. Int8 scalar quantisation quarters it, with a small recall drop usually recovered by rescoring the top candidates with the original vectors. Binary quantisation goes to one bit per dimension — 96 bytes for a 768-dimension vector, a 32-fold reduction — and works surprisingly well for high-dimension models when you over-fetch and rescore, but it is a recall decision you must measure, not assume.

The memory arithmetic you should do before choosing anything

Storage is dimensions times bytes per dimension times count. A million chunks at 768 dimensions in float32 is 768 million floats, about 3.1 GB; at 1,024 dimensions 4.1 GB; at 1,536, 6.1 GB. Those are raw vector bytes. Add chunk text — roughly 1.6 GB for 400-token chunks at four characters per token — plus metadata and keys, and the real footprint is two to three times the vector size in a row store.

Index structures add their own overhead. HNSW keeps a proximity graph: with M equals 16, each node holds up to 32 links at the base layer, so a million vectors adds about 128 MB of links plus per-node bookkeeping. That is modest, but the graph must live in RAM for fast search, which is why HNSW deployments are memory-bound rather than disk-bound. Product quantisation is the escape hatch: splitting a 768-dimension vector into 96 subvectors of 8 dimensions, each encoded as one of 256 centroids, gives 96 bytes per vector — 96 MB per million — at the cost of approximate distances that you correct by rescoring a shortlist.

Do this arithmetic early, because it determines the architecture. Ten million chunks at 1,536 dimensions in float32 is 61 GB of vectors before text and index — a machine, not a container. At int8 with a 256-dimension truncation it is 2.5 GB, which fits anywhere. The choice between those two designs is made by a multiplication, not by a benchmark.

ANN indexes: what the families actually trade

Exact search compares the query against every vector. At a million vectors of 768 dimensions that is 768 million multiply-adds per query, roughly a few tens of milliseconds on a modern CPU with SIMD and multiple cores — tolerable at small scale and hopeless at a hundred million vectors with concurrency. Approximate nearest neighbour indexes give up the guarantee of exactness for orders of magnitude in speed, and every one of them exposes knobs that trade recall against latency.

IVF clusters vectors with k-means and searches only the nearest few lists at query time. With a million vectors, 1,000 lists is a reasonable start and probing 10 to 50 gives tunable recall. It is simple and memory-efficient, but assumes balanced clusters and handles filtering poorly, since a filter can empty the probed lists.

HNSW builds a multi-layer proximity graph and descends greedily from a sparse top layer to a dense bottom one. It delivers the best recall-per-millisecond of the mainstream indexes at moderate scale, and it is what most managed vector databases use by default. Its costs are memory, since the graph lives in RAM, slow inserts as the graph is repaired, and a deletion story that usually amounts to tombstones plus periodic rebuilds. The three parameters that matter are M (links per node, 16 to 64), efConstruction (build effort, 100 to 400) and efSearch (query effort, 64 to 256), and only efSearch can be tuned at query time.

PQ and its variants compress vectors into codebooks; IVF-PQ combines coarse clustering with compression and is the standard choice when the corpus does not fit in RAM. DiskANN keeps the graph on SSD with a compressed in-memory representation, which is how billion-scale indexes run on a single machine. The pattern across all of them: memory buys latency, compression buys capacity, and you pay in recall.

Recall is the only benchmark that matters

Vendors quote queries per second at some recall level, and the recall level is usually the interesting part. Measure it yourself: take a few hundred queries, compute exact top-10 by brute force on a sample, and compare the index's top-10 against it. That gives recall@10 for your data and your parameters. Anything below about 0.9 will be visible in answer quality; 0.95 to 0.98 is the usual operating range for RAG, where a reranker cleans up the ordering anyway.

Measure latency as a distribution, not a mean. p50 of 8 milliseconds with a p99 of 300 is a different product from a flat 25, and tail latency usually comes from segment merges, garbage collection or a filter that made a graph search explore too much. Load-test with realistic concurrency and realistic filter selectivity, because a filtered query over a narrow tenant slice behaves nothing like an unfiltered benchmark.

Then measure the thing that actually matters: end-to-end answer quality as you vary efSearch or nprobe. Retrieval recall improvements saturate — going from 0.95 to 0.98 often changes no answers because the reranker already had the right passage in its shortlist. Spend the latency budget where it changes outputs.

Filtering is where vector stores earn their keep

Real queries are almost always filtered: tenant id, document type, date range, permission group, language. The naive implementation searches the index and then discards non-matching results, which fails badly when the filter is selective — ask for one tenant's documents out of ten thousand and the top 100 neighbours may contain none of them, so you return nothing while claiming there are no results.

Pre-filtering solves correctness but breaks graph indexes, because HNSW traversal needs connectivity and a filtered subgraph may be disconnected or tiny. The good implementations handle this with filter-aware traversal, by partitioning the index per tenant, or by maintaining separate indexes for high-cardinality filter dimensions. Ask any candidate store how it handles a filter that matches 0.1 percent of the corpus; the answer distinguishes a real vector database from a library with a SQL wrapper.

Also settle where permissions live. If authorisation is enforced by the application after retrieval, a prompt injection or a logging bug can expose text the user was never entitled to see. Push the permission predicate into the query and make the index the enforcement point.

Choosing a store

  • Already running Postgres and under a few million chunks: pgvector with HNSW. One system to operate, transactional consistency with your metadata, and good enough recall.
  • Need rich filtering, multi-tenancy and a dedicated service: Qdrant or Weaviate. Both treat payload filtering as a first-class concern rather than an afterthought.
  • Hundreds of millions to billions of vectors, or GPU-accelerated build: Milvus. More moving parts, and it assumes you have someone who enjoys operating distributed systems.
  • Embedded, single-file, versioned with your repo: LanceDB or sqlite-vec. Excellent for local development, evaluation harnesses and small on-prem deployments.
  • Research, batch experiments, no server: FAISS. Still the reference implementation and the fastest way to measure what an index can do before committing to a vendor.
  • You already run Elasticsearch or OpenSearch and want hybrid search in one query: their kNN fields plus BM25. Convenient, though dense performance trails dedicated engines at large scale.

Operations that bite

Deletion is not free. HNSW does not remove a node cleanly without breaking the graph, so implementations mark it deleted and filter at query time, which means the index slowly fills with dead weight and needs compaction. If your product has a hard delete requirement, know the compaction story and the window during which deleted vectors still exist on disk.

Changing the embedding model is a migration, not a config change. Vectors from two models are not comparable, so you either rebuild the whole index or run both side by side and dual-write during a cutover, with a query router that knows which collections are on which model. Version the collection name with the model and dimension — chunks_v2_bge_m3_1024 — and the migration becomes obvious instead of hazardous.

Back up the vectors and the metadata together, and verify restore by running your retrieval evaluation against the restored copy. A snapshot that restores vectors but loses the mapping to chunk text is not a backup; it is a pile of numbers. Test the restore before you need it.

Evaluating an embedding model for your corpus

Public leaderboards rank models on general retrieval benchmarks, and general is the operative word. A model that tops MTEB can lose to a smaller domain-specific one on patents, clinical notes or code. The only evaluation that decides is one built from your own queries and your own passages: 200 queries, gold passage ids, recall@10 and nDCG@10 across three or four candidate models.

Check the asymmetry explicitly. Embed your queries and your passages with the prefixes and instruction format the model card specifies, then measure. Also test chunk lengths similar to what you will deploy — a model trained on 128-token passages may degrade when you feed it 800-token chunks, and truncation at the model's maximum length silently discards the tail of every long chunk.

Test multilingual behaviour if you have it. Many models claim multilingual support and perform acceptably on high-resource languages while collapsing on the long tail. If your corpus mixes languages, evaluate per language rather than in aggregate, because the average hides the failure.

Common mistakes

  • Skipping normalisation while using dot product, which ranks by vector magnitude and therefore often by text length.
  • Thresholding on raw cosine similarity as if it were a probability, without calibrating against the corpus.
  • Choosing a 3,072-dimension model for a corpus that a 768-dimension model handles equally well, then paying four times the memory.
  • Post-filtering after ANN search on a selective filter, which returns nothing and reports it as no results.
  • Benchmarking queries per second without measuring recall against exact search, so the reported speed is for an index that returns the wrong neighbours.
  • Treating an embedding-model upgrade as a config change instead of a full reindex.
  • Assuming MTEB rank predicts performance on your domain instead of running a 200-query evaluation on your own data.
Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.