Glossary
K-nearest neighbours search
A search that returns the k stored items whose vectors are closest to a query vector under a chosen distance measure, either exactly or approximately.
K-nearest neighbours (kNN) search finds the k items in a collection whose vectors are closest to a query vector. You choose a distance or similarity measure, compare the query with the stored vectors, and return the k best matches in order. It is the operation underneath vector search, semantic search and most retrieval-augmented generation: a question is turned into an embedding, and kNN finds the stored passages, images or records whose embeddings sit nearest to it. Exact kNN compares the query with every vector and always returns the true nearest neighbours; approximate kNN uses an index to skip most comparisons and returns nearly the same results much faster.
How k-nearest neighbours search works
Every item in the collection is represented as a vector, usually an embedding produced by an embedding model. The query is embedded with the same model, so it lands in the same space. Search then has three parts: a way to measure closeness, a way to find the closest candidates, and a value of k that sets how many to return.
The closeness measure depends on how the embeddings were trained. Cosine similarity compares the angle between two vectors and ignores their length, which suits most text embeddings. Dot product similarity also accounts for length, and is identical to cosine when vectors are normalised to unit length, which many models do by default. Euclidean distance measures the straight-line gap between two points and is common in image and classical machine-learning work. Using a different measure from the one the model was trained for is a quiet source of poor results, so it is worth checking the model card before building anything.
The output is a ranked list of k items with their scores. In a retrieval pipeline those items become candidates: they may be passed straight to a language model as context, merged with keyword results, or reordered by a reranker before use. The ranked list is the same thing people mean by top-k retrieval; kNN describes the search, and top-k describes the cut-off applied to its output.
Choosing k
k is a trade-off between missing the answer and drowning it. A small k (three to five) keeps prompts short and precise but risks leaving out the one passage that mattered, particularly when it ranks sixth. A large k (fifty or a hundred) makes it more likely the answer is somewhere in the set, but adds tokens, cost and distraction for the model that reads it. Research on long inputs shows models use information in the middle of a long context less reliably, so more candidates is not automatically better.
A common pattern is to retrieve generously and then narrow. The first kNN pass might fetch 50 to 100 candidates, a cross-encoder reranks them, and only the top five or ten reach the prompt. Another approach is to replace a fixed k with a score threshold, so a question with one clearly relevant passage returns one, and a broad question returns many. Our post on why top-k is the wrong default goes into this in more depth.
Exact kNN: brute force
Exact kNN, sometimes called flat or brute-force search, computes the distance from the query to every stored vector and keeps the k smallest. It is simple, has no parameters to tune, needs no training step, and handles inserts and deletes instantly. Its recall is 100 percent by definition, which makes it the reference against which approximate methods are measured.
Its cost grows linearly with the collection. Each comparison costs one multiply and add per dimension, so a million 1,024-dimensional vectors means roughly a billion operations per query. On modern CPUs and GPUs that is fast enough for many workloads, and libraries such as FAISS make flat search efficient with batched, vectorised arithmetic. For collections of up to a few hundred thousand vectors, or for queries that are already filtered down to a small subset, brute force is often the right answer.
Approximate kNN
Beyond that scale, most systems switch to approximate nearest neighbour (ANN) search. An ANN index organises vectors so that a query only needs to visit a small fraction of them. HNSW builds a layered graph and walks greedily towards the query. An IVF index clusters vectors and searches only the clusters nearest the query. Product quantisation and binary quantisation compress vectors so more of them fit in memory and comparisons are cheaper, at some cost in precision. These structures are covered together under vector index.
The price of approximation is recall. An approximate kNN search might return nine of the true ten nearest neighbours, with the tenth replaced by something slightly further away. This is measured as recall@k against an exact baseline, and most indexes expose a setting (such as efSearch for HNSW or nprobe for IVF) that trades latency for recall. In practice teams aim for 95 to 99 percent recall, because the embedding model’s own errors are usually larger than the index’s.
kNN with filters
Real queries rarely search the whole collection. A user wants results from their own workspace, documents from the last quarter, or only PDFs. Combining metadata filtering with kNN is harder than it sounds, and there are three common approaches.
Post-filtering runs kNN first and then removes results that fail the filter. It is simple, but if the filter is selective it can leave fewer than k results, or none. Pre-filtering applies the filter first and runs kNN over the remaining vectors, which is accurate but can be slow if the subset is large and unindexed. Filtered index traversal checks the filter while walking the index, which most vector databases now support, though very selective filters can still push graph-based indexes into poor regions of the graph. For multi-tenant applications, the cleanest answer is often to give each tenant its own index, so tenant boundaries never depend on a filter being applied correctly.
A worked example
Suppose a small collection holds five passages with two-dimensional embeddings (real embeddings have hundreds of dimensions, but the arithmetic is the same). The query vector is (0.9, 0.2), and we use Euclidean distance with k = 2.
Passage | Vector | Distance to query |
|---|---|---|
A: refund policy for annual plans | (0.8, 0.3) | 0.14 |
B: cancelling a subscription | (0.7, 0.1) | 0.22 |
C: office opening hours | (0.1, 0.9) | 1.06 |
D: invoice formatting | (0.5, 0.5) | 0.50 |
E: annual plan pricing | (0.9, 0.6) | 0.40 |
The two nearest neighbours are A and B, so a kNN search with k = 2 returns those in that order. With k = 3, E joins them. Notice that nothing in this process checks whether A answers the question. kNN returns what is closest in the embedding space, which is usually related and often relevant, but the two are not the same.
kNN search vs kNN classification
The name also refers to a classic machine-learning algorithm. kNN classification labels a new data point by looking at the labels of its k nearest neighbours in a training set and taking a majority vote, and kNN regression averages their values. The search step is identical; what differs is what you do with the neighbours. In retrieval systems the neighbours are the output. In classification they are evidence for a prediction. When people talk about kNN in the context of vector databases and RAG, they almost always mean the search.
Where kNN falls short for retrieval
kNN measures semantic similarity, and similarity is a proxy for relevance rather than relevance itself. A passage about Q3 revenue sits very close to a question about Q3 projections, yet may not contain the projection. This gap is the subject of similarity isn’t relevance, and it is the most common reason RAG systems give confident wrong answers.
Scale makes it worse. In high-dimensional spaces, distances between points tend to bunch together, so the gap between the nearest and the twentieth-nearest result shrinks as the collection grows. This is related to semantic collapse, where many results look equally plausible and ranking becomes unstable; our post on why vector search breaks at scale shows how it plays out. kNN also struggles with exact identifiers such as product codes or names, which embeddings tend to blur. That is why production systems pair kNN with keyword retrieval in hybrid search, add a reranking stage, and evaluate retrieval with precision and recall rather than trusting raw similarity scores.
Where Exabase fits
Exabase handles the kNN layer for you. Content stored as Resources is extracted and indexed when it is written, and Deep Search runs the retrieval, so there is no embedding pipeline, index type or k value to manage. Text queries are hybrid by default, combining semantic search with typo-tolerant keyword matching, which covers the exact identifiers that pure kNN misses. Resource similarity search lets you pass an existing resource as the query and find the stored content nearest to it, and image queries find visually similar images, which is the kNN pattern applied to asset search.
Instead of a fixed k, Deep Search exposes a precision parameter from 0 to 1 (default 0.3): lower values return a wider net, higher values return only the closest matches. Results are passages with page numbers or timestamps rather than whole documents, and filters on kinds, folders, tags and creation dates are applied within the search. Each Base has its own isolated index, so tenant separation does not rely on a filter. The searching resources guide and the search API reference have the details, and RAG accuracy explains how this fits a RAG pipeline. If you are comparing this with running your own index, see best vector databases and Exabase vs Pinecone.
Frequently asked questions
What is k-nearest neighbours search?
K-nearest neighbours search returns the k stored items whose vectors are closest to a query vector. It is the core operation behind vector search, semantic search and retrieval for RAG.
What is the difference between kNN and ANN?
kNN is the task of finding the k closest vectors; exact kNN compares the query with every vector. ANN (approximate nearest neighbour) search uses an index such as HNSW or IVF to find nearly the same neighbours much faster, accepting a small loss in recall.
How do I choose a value for k?
Choose k based on what happens next. If results go straight into a prompt, a small k of three to ten keeps context precise. If a reranker follows, retrieve 50 to 100 candidates and let the reranker choose the final few.
Which distance metric should I use for kNN?
Use the metric your embedding model was trained for, which is usually cosine similarity for text embeddings. If vectors are normalised, cosine similarity and dot product give the same ranking.
Is kNN search accurate?
Exact kNN always returns the true nearest vectors, but nearest is not always relevant. Accuracy for a real task depends on the embedding model, the chunking of the content and whether keyword search and reranking are added.
Why does kNN return results that look right but are wrong?
kNN ranks by similarity in embedding space, and topically similar passages often lack the specific fact asked for. Sub-document retrieval, hybrid search and reranking reduce this.
Do I need to tune kNN parameters in Exabase?
No. Exabase indexes stored content automatically and Deep Search handles retrieval. You set strictness per query with the precision parameter rather than tuning k or index settings.
Related pages: Approximate nearest neighbour, Vector search, Top-k retrieval, Cosine similarity, Euclidean distance, HNSW, FAISS, Recall@k, Semantic collapse, RAG accuracy