Embedding spaces and vector indexes
medium 9 minVector retrieval compares representations under a declared metric.
Video lesson · Chapter 1 of 4
The neighbor the index missed
Theory
Read or listen first. About 4 min.
What it is
Vector retrieval compares representations under a declared metric. The database adds indexing, persistence and metadata management around that calculation. Exact search establishes a reference ranking; approximate indexes trade effort and memory against the chance of recovering those neighbors.
Why it exists
Debug in sequence. Confirm the correct version exists, check the encoder and metric with known vectors, compare approximate results to exact search, then examine the mapping from vector IDs to authorized source text.
An exact neighbor disappears in an approximate index
Inside this chapter
Chapter sources- Semantic Similarity
- Cosine similarity divides the dot product by both vector lengths. It compares direction while discarding magnitude. Two normalized vectors have a cosine equal to their dot product. A near match in this geometry can still contradict the query on a crucial word such as “before” versus “after.”
Cosine similarity asks whether two arrows point the same way, regardless of how long they are. Many text encoders output vectors whose length carries little meaning, so normalising to length one and using the dot product gives the same ranking more cheaply. Remember what similarity cannot do: "refund before 30 days" and "refund after 30 days" point almost the same way because they share nearly all their content.
Example. The vectors (1,0) and (2,0) have cosine 1. Their magnitudes differ; a ranking based on raw dot product can treat them differently.
Cosine ignores length, dot product does not
Pair Dot product Lengths Cosine (1,0) · (2,0) 2 1 and 2 1.0 (1,0) · (1,0) 1 1 and 1 1.0 (1,0) · (0.8,0.6) 0.8 1 and 1 0.8 (1,0) · (0,1) 0 1 and 1 0 With unit-length vectors the two measures agree. - Embedding Models
- Select embedding models using held-out query–passage pairs from the target domain. Check language coverage, appropriate query and document prefixes, vector dimension and inference cost. When replacing a model, build a separate index and compare retrieval results before switching traffic. Existing vectors inhabit the old representation space.
Judge an encoder on your own query and passage pairs, split into slices such as language, short identifiers and long questions. Read the model's retrieval recipe: some expect different prefixes or instructions for queries and documents, and leaving them out quietly lowers quality. When migrating, re-embed everything into a separate index; querying old document vectors with a new query encoder produces nonsense rankings even though nothing errors.
Example. Re-embed the same 100 labeled passages under a candidate encoder. For each query compare whether its answer still appears in the top five.
Another example. A team swaps encoders and sees recall drop. The cause is not the model: the new one expects a
query:prefix on questions and apassage:prefix on documents, and the indexing job left the passage prefix off. Re-embedding with the right recipe recovers the expected result.Choosing and swapping an encoder
Vectors from two encoders live in different spaces, even at the same dimension, so never mix them in one index. - The Math of Embeddings
- An embedding is a point in a learned coordinate space. Dot product, cosine and Euclidean distance can induce different rankings, especially when vector norms vary. Apply the same normalization at indexing and query time and verify the chosen index uses the metric the encoder was trained with.
Each metric is a different question about the same two points. If every vector is normalised to length one, the three rankings coincide and the choice only affects whether bigger or smaller means closer. Trouble starts when indexing normalises but querying does not, or when an index is configured for Euclidean distance while the encoder was trained for cosine. A two-vector test like (1,0) and (0,1) catches these mistakes in seconds.
Example. With unit vectors (1,0) and (0,1), cosine is zero. Test that the configured index reports the documented similarity or distance for this pair.
Three metrics and how they relate
For unit vectors, squared Euclidean distance is 2 minus twice the cosine, so all three give the same ranking. With unequal lengths they can disagree. - Dense vs. Sparse Vectors
- Sparse lexical vectors preserve signals from particular terms, including rare IDs. Dense vectors represent learned semantic proximity. A query for “E17” can be decisive lexically while “card charged twice” benefits from semantic matching. Evaluate both signals and consider fusion for mixed query populations.
A sparse vector has one slot per vocabulary term, mostly zeros, with weights for the terms present (BM25-style scores or learned sparse weights). It is excellent at exact rare strings such as part numbers. A dense vector has a few hundred or thousand learned dimensions, all non-zero, and captures meaning across different wording. Each fails where the other shines, which is why hybrid search is common.
Example. Query “E17” and then “charged twice.” Inspect which lexical and dense candidates are recovered for the identifier and paraphrase.
Two queries, two kinds of signal
Query Sparse lexical top hit Dense top hit Better signal E17 Fault E17: card reader timeout General card reader troubleshooting Sparse charged twice Page containing the word twice Duplicate payment refunds Dense Illustrative. Mixed traffic usually benefits from both. - Dimensionality Reduction
- Dimensionality reduction trades representational capacity for smaller indexes and cheaper distance calculations. Fit any learned transformation on the appropriate data and apply the identical transform to queries. A two-dimensional visualization that forms attractive clusters gives little evidence about nearest-neighbor recall in production.
Reducing dimensions (by PCA, by truncating models trained to allow it, or by quantising each value) shrinks memory and speeds distance computation. The cost is that some distinctions disappear. Fit any learned projection on representative document data and apply the identical transform to queries. Judge it by recall against the full-dimension exact search, never by how tidy a 2D plot looks.
Example. Project (1,0) and (1,9) onto their first coordinate. They collapse to the same point, illustrating why discarded dimensions can change neighbor rankings.
Dropping a coordinate merges neighbours
Vector Full (x, y) Keep x only Distance to query (1,0) Query (1, 0) 1 0 A (1, 0) 1 0 before, 0 after B (1, 9) 1 9 before, 0 after B was far away; after projection it ties with A. - Indexing Algorithms
- Approximate indexes avoid scanning every stored vector. HNSW explores a proximity graph; inverted-file methods search selected partitions. Increasing search effort often improves recall at a latency cost. Compare candidate sets against exact search on a representative sample before choosing defaults.
HNSW builds a layered graph: upper layers are sparse long-range links, the bottom layer links every vector to its nearest few. A search starts at the top, greedily walks towards the query, then drops down and repeats with a wider candidate list (often called ef). IVF instead clusters vectors around centroids, and a query scans only the few clusters (nprobe) nearest to it. Both can miss a true neighbour that sits across a cluster boundary or behind a poor graph link, so measure recall against exact search.
Example. Retrieve five candidates with a flat exact index. Count how many of those five an approximate configuration recovers before measuring latency.
Another example. A product-search index returns the exact top 5 for 4 out of 5 sample queries at the default setting. Doubling the HNSW candidate list recovers the fifth at a modest latency cost, which the team accepts. Illustrative numbers.
HNSW and IVF answer the same query differently
Raising ef or nprobe usually raises recall and latency together. - CRUD in Vector Stores
- Vector-store writes must handle replacement and deletion as well as insertion. Use stable chunk IDs and coordinate source revisions with index updates. When a policy shrinks from five chunks to three, explicitly retire the old trailing chunks or obsolete clauses can still appear in answers.
Inserting is easy; keeping the index in sync with sources is not. Give chunks deterministic IDs derived from document and position, and on a new revision delete every chunk of the old revision that the new one does not overwrite. Some stores mark deletes and clean up later, so check that deleted vectors stop appearing in search results, not just that the delete call returned success.
Example. Replace a five-chunk manual with a three-chunk revision. Search for a sentence unique to chunk five to verify stale content was retired.
Replacing a five-chunk manual with three
Chunk ID Before Upsert only Upsert + retire manual#1 v1 v2 v2 manual#2 v1 v2 v2 manual#3 v1 v2 v2 manual#4 v1 v1 still live deleted manual#5 v1 v1 still live deleted Search for a sentence that only existed in chunk 5 to prove it is gone. - Embedding Models
- Query and document encoders may use different instruction prefixes even when they share weights. Check the model’s documented retrieval recipe. On migration, re-embed a test corpus and compare exact-neighbor and end-to-end performance so index configuration errors are not mistaken for encoder regressions.
Judge an encoder on your own query and passage pairs, split into slices such as language, short identifiers and long questions. Read the model's retrieval recipe: some expect different prefixes or instructions for queries and documents, and leaving them out quietly lowers quality. When migrating, re-embed everything into a separate index; querying old document vectors with a new query encoder produces nonsense rankings even though nothing errors.
Example. Index documents with one encoder and query with another having the same dimension. Compare the results with the correctly paired encoder baseline.
Another example. A team swaps encoders and sees recall drop. The cause is not the model: the new one expects a
query:prefix on questions and apassage:prefix on documents, and the indexing job left the passage prefix off. Re-embedding with the right recipe recovers the expected result.Choosing and swapping an encoder
Vectors from two encoders live in different spaces, even at the same dimension, so never mix them in one index. - ChromaDB Integration
- A Chroma collection holds records with IDs, embeddings and optional metadata and documents. Choose the collection metric and embedding function consistently. Validate add, update, delete and filtered query behavior on a small corpus before deciding how to handle production persistence or tenancy.
A collection bundles IDs, vectors, optional documents and metadata, plus an embedding function and a distance setting. Fix both at creation and keep them consistent with the encoder. Before relying on it, exercise every operation on a toy corpus: add, update an existing ID, delete, and query with a metadata filter, then confirm results match what you expect.
Example. Create two records with the same topic but different tenant metadata. Verify a tenant-filtered query returns only eligible content.
Pythoncol = client.get_or_create_collection( "policies", metadata={"hnsw:space": "cosine"})col.add(ids=["p1", "p2"], documents=["Refunds: 30 days", "Refunds: 14 days"], metadatas=[{"tenant": "a"}, {"tenant": "b"}])col.query(query_texts=["refund window"], n_results=2, where={"tenant": "a"}) # expect only p1A tiny tenant-filter test. Check the metric setting and the query result before scaling up. - FAISS Integration
- FAISS provides indexes for similarity search. Start with a flat exact index to establish correctness, then compare approximate choices when scale requires them. Maintain the mapping from returned vector IDs to source documents outside or alongside the index, including the version and access metadata.
FAISS is a library of index types (flat exact, IVF, HNSW, product-quantised variants) that return integer IDs and distances. It does not store your text or metadata, so you must keep a mapping from those integers to chunk records, versioned together with the index. Start with a flat index to get a correct baseline, then try approximate types and compare their top results with it.
Example. A FAISS search returns integer 17. Resolve it through the same index generation’s ID map instead of looking it up in yesterday’s document order.
Resolving integer 17 to the right text
Store the ID map with the same generation number as the index. - RAG Pipeline Overview
- Follow one known passage end to end: extract it, record its chunk ID, embed it, index it and retrieve it with a paraphrased question. Then check that its ID survives context packing. This isolates a retrieval problem from a later failure to present or use the evidence.
End-to-end tracing is the fastest way to localise a RAG failure. Pick one passage you know answers a question, give it an ID, and confirm its presence at each hand-off. If it is retrieved but not in the prompt, the packer or token budget dropped it; if it is in the prompt but the answer ignores it, the problem is generation, not search.
Example. Track source P7 through extraction, embedding, top-k lookup and context packing. Mark the first boundary at which it disappears.
Follow passage P7 until it disappears - 1Extract P7text and offsets present
- 2Chunk ID recordedpolicy-7#c3
- 3Embedded and indexedvector stored, ID mapped
- 4Paraphrase queryP7 in top k?
- 5Context packingP7 still in prompt?
The first step where P7 is missing is where to debug.
How it works
Step through the idea, or press Play.
Query vector. q = (1, 0)
Understand it
Worked example
An exact neighbor disappears in an approximate index
- 1
q = (1, 0)
Use normalized vectors in the same encoder space. The intended reference passage has vector (0.8, 0.6), cosine 0.8 with this query.
- 2
Exact finds P7 · approximate misses P7
Run both methods over the same authorized corpus. If exact search finds P7, the approximate index’s search effort may be limiting recall.
- 3
Resolve P7 to source v3
Retrieve text through the versioned ID map. Check document freshness separately from nearest-neighbor correctness.
Cosine similarity
Follow the handoffs
Exact versus approximate on the same query
| Rank | Exact flat search | Approximate, low effort | Approximate, higher effort |
|---|---|---|---|
| 1 | P7 · 0.80 | P2 · 0.74 | P7 · 0.80 |
| 2 | P2 · 0.74 | P5 · 0.70 | P2 · 0.74 |
| 3 | P5 · 0.70 | P9 · 0.61 | P5 · 0.70 |
Debug order for a missing neighbour
Summary
The whole topic in one minute.
The candidate is already missing in the exact baseline. Extra approximate search effort cannot improve the underlying representation or restore an absent record.
Debug in sequence. Confirm the correct version exists, check the encoder and metric with known vectors, compare approximate results to exact search, then examine the mapping from vector IDs to authorized source text.