Skip to content

Vector Search Finds Neighbors, Not Truth

By Maksym Kuzmitskyi
6 min read
Vector Search Finds Neighbors, Not Truth

Vector Search Finds Neighbors, Not Truth

The closest policy is the retired one. It discusses exactly the right system, uses exactly the right vocabulary and differs from the current policy in the one sentence that matters.

The search can be mathematically correct and operationally wrong.

I find that distinction more useful than asking whether vector search works. It works at finding nearby representations under a chosen metric. Our application still has to decide which candidates are eligible and whether the eventual answer follows from them.

A neighbor is a ranking relationship

A vector is an ordered list of numbers. A distance function compares two such lists. Nearest-neighbor search finds stored vectors with the smallest distance from a query vector under that function.

Top-k means returning a chosen number of the best-ranked candidates. It doesn't mean the system found k relevant or correct documents. If every available document is irrelevant, a nearest-neighbor query can still return a first place.

The embedding model, preprocessing and distance metric together define the comparison. Query and document representations must be compatible. Equal-length arrays from unrelated models are not automatically coordinates in the same useful space.

For a tiny corpus, we can inspect exact search directly: calculate distance to every eligible row, sort and take the requested count. Production systems use established numerical libraries or database operators rather than a tutorial loop over millions of records.

Keep eligibility outside the score

Our fictional assistant should normally search current policies, not archived ones. Current is a metadata condition: a property supplied by the source lifecycle, not something to infer from vector proximity.

Here is a deliberately small exact search over invented numeric vectors. It uses Euclidean, or L2, distance: the straight-line distance between coordinates. Unlike cosine, L2 can compare a zero vector, which we use only to simplify the fixture.

type VectorRow = { id: string; values: readonly number[]; current: boolean }; function nearest( rows: readonly VectorRow[], query: readonly number[], count: number, eligible: (row: VectorRow) => boolean, ) { if (!Number.isSafeInteger(count) || count < 0) throw new Error('Invalid result count'); if (query.length === 0 || !query.every(Number.isFinite)) throw new Error('Invalid query vector'); const candidates = rows.filter(eligible); if (new Set(candidates.map((row) => row.id)).size !== candidates.length) throw new Error('Duplicate row'); const scored = candidates.map((row) => { if (row.values.length !== query.length || !row.values.every(Number.isFinite)) { throw new Error('Invalid stored vector'); } const distance = Math.hypot(...row.values.map((value, index) => value - query[index])); if (!Number.isFinite(distance)) throw new Error('Invalid distance'); return { id: row.id, distance }; }); return scored.sort((left, right) => left.distance - right.distance || left.id.localeCompare(right.id)).slice(0, count); }

The eligibility callback is trusted application logic. It is not a model-generated permission predicate, and this array example is not a database security design.

Ties have a deterministic identifier order so a small test doesn't change merely because rows arrived in a different order. Deterministic tie handling is not the same as a universally reproducible AI system; it is one property of this function.

Let the wrong document win once

The coordinates below are chosen by hand, not produced by an embedding model:

const rows: VectorRow[] = [ { id: 'policy-v1', values: [0, 0.01], current: false }, { id: 'policy-v3', values: [0, 0.1], current: true }, { id: 'other-topic', values: [2, 2], current: true }, ]; const unrestricted = nearest(rows, [0, 0], 1, () => true); const currentOnly = nearest(rows, [0, 0], 1, (row) => row.current);

The unrestricted result is policy-v1. The current-only result is policy-v3. We didn't improve the distance calculation. We changed which documents were allowed to compete.

Neither result proves that its policy answers the question. The fixture establishes selection behavior and illustrates a failure mode. Actual embeddings may arrange these texts differently, and that needs a real retrieval evaluation with the chosen model.

A small distance isn't confidence

The distance 0.01 means that two fixture coordinates are close under L2. It doesn't mean 99 percent confidence. A cosine score, a database distance and a model-generated certainty field are also different quantities.

A threshold can be useful if calibrated against representative labelled questions and documents. I would not copy one threshold across models, corpora or preprocessing changes and assume it retains the same meaning.

Even a calibrated retrieval threshold concerns candidate quality, not the truth of every sentence in a generated answer. The source can be wrong, stale or incomplete. The model can also misinterpret a good source.

If there are no eligible rows, this function returns an empty list. The assistant should preserve that condition as missing evidence, not widen its search to unauthorized or retired material simply to avoid an empty response.

Exact relative to what?

Exact search means the nearest results under the chosen metric among the eligible stored vectors. It does not mean semantically exact answers.

The pgvector 0.8.7 documentation makes a useful implementation distinction: default nearest-neighbor search is exact, while optional approximate indexes trade some recall for speed. Recall here concerns finding members of a reference result set, not proving their factual correctness.

That distinction will matter when the corpus grows. Before optimizing, I want a baseline whose behavior I can inspect. A list of expected source IDs for a few awkward questions is more useful than a screenshot of plausible results.

I would include old/current pairs, near-duplicate exceptions, exact identifiers and questions with no answer. Then record separately whether retrieval found the needed evidence and whether generation used it correctly.

The requested result count deserves testing too. Returning one passage can make the answer cheap while omitting its exception. Returning every passage can restore the exception while overwhelming the context budget. There is no result count that resolves that trade-off for every question. I would compare a few bounded choices against the actual evidence needed.

Candidate identity matters during that comparison. If a single source is split into several near-duplicate passages, the first five results may all describe the same paragraph. Counting five returned rows as five independent pieces of supporting evidence overstates what the system found. Preserve source and section identifiers so the evaluation can notice repeated coverage.

I would also record the corpus revision with the result. A test failure after a document update may reflect a changed searchable collection rather than an arithmetic defect in distance calculation. Without that identity, a supposedly stable baseline can quietly compare different questions against different worlds.

The next step is storing vectors beside the document metadata in an ordinary relational database. PostgreSQL can do that without making the vector index the owner of every other application responsibility.

Which document would your search rank highly but your product should refuse to treat as current? That example belongs in the retrieval test set.

A note from the author

I’m Maksym Kuzmitskyi, a senior software developer working mainly with React and TypeScript. I build frontend applications and design workflows for working with AI in software delivery. If this article connects with something you’re working on, I’d love to hear from you.

Telegram

More than a blog post

I share frontend news and the reasoning behind it throughout the day. Pick the language that feels natural to you.

Need to discuss your project? Get in touch.