Exact and approximate retrieval
Find the nearest vectors
A vector index helps locate stored vectors close to a query according to a chosen metric. Top-k retrieval returns up to k matching records, ordered by proximity. A vector database also manages records, metadata, persistence and query operations; an index alone does not provide those services. Start with exact search: compute a distance for every eligible record and sort. Our five invented vectors share two dimensions and use squared Euclidean distance. Squaring preserves distance order and avoids square roots. The query [0, 0] has squared distances 1, 1, 4, 18 and 4 for a through e. With ascending ID as the tie-breaker, the exact top two are a and b. This is a geometric fixture, not evidence that these vectors represent text well.
def exact_top_k(query, rows, k): # Small integer vectors; squared L2 distance; stable string IDs. if not query or type(k) is not int or k < 1: raise ValueError("nonempty query and positive k required") if any(type(x) is not int for x in query): raise ValueError("integer coordinates required") seen = set() scores = [] for key, vector in rows: if not isinstance(key, str) or not key or key in seen: raise ValueError("unique nonempty IDs required") if len(vector) != len(query) or any(type(x) is not int for x in vector): raise ValueError("incompatible vector") seen.add(key) distance = sum((x-y)**2 for x, y in zip(query, vector)) scores.append((distance, key)) return [key for _, key in sorted(scores)[:k]]
rows = [("a", [1, 0]), ("b", [0, 1]), ("c", [2, 0]), ("d", [3, 3]), ("e", [-2, 0])]print(exact_top_k([0, 0], rows, 2))Why approximate nearest neighbors can help
For N vectors of dimension d, a brute-force scan calculates O(N*d) coordinate differences, then this example sorts all N scores in O(N log N) time. Production exact search can use selection, batching and optimized kernels. Approximate nearest-neighbor (ANN) search instead examines a subset or compressed representation of the data; it may miss a true neighbor. HNSW (hierarchical navigable small world) builds a layered proximity graph, searches coarse layers and refines at lower layers. Search breadth trades work for potential recall; construction also consumes memory and time. IVF (inverted file) groups vectors into lists around coarse centroids, then searches selected lists near the query. More probes usually examine more candidates; centroid training and distribution drift matter. Quantization can reduce storage and change distances. No index guarantees a specific latency or recall on all workloads.
Measure index recall against a fixed exact baseline
Index recall at k is the number of returned IDs also in the exact top-k result divided by the size of that exact result. Use identical corpus snapshot, embedding revision, metric, filters and k. The denominator here is the actual available exact result count, so when fewer than k records are eligible, a complete match still scores 1. An empty exact result is excluded and counted separately. Our invented candidate lists yield 0.5, 1.0, 0.0 and 0.5 respectively. This differs from relevance Recall@k from the previous chapter, which uses human relevance labels instead of the exact nearest neighbors. A tied boundary needs a declared tie convention or a tie-aware evaluation; our IDs supply a fixed convention. Aggregate recall across representative queries, not just one easy example.
def index_recall(exact, returned): # Exact list is the target at a fixed k, not human relevance labels. if not exact or len(set(exact)) != len(exact): raise ValueError("unique nonempty exact result required") if len(returned) > len(exact) or len(set(returned)) != len(returned): raise ValueError("invalid candidate list") return len(set(exact) & set(returned)) / len(exact)
exact = ["a", "b"]# Invented candidate results, NOT measured ANN performance.for found in (["a", "c"], ["a", "b"], [], ["b"]): print(index_recall(exact, found))Choose the storage and index together
FAISS is a similarity-search library: the application must supply record storage, access enforcement and lifecycle coordination. PostgreSQL with pgvector adds vector operations and exact or approximate indexes to a relational database, useful when joins and transactions matter. Qdrant and Milvus provide vector-search services with metadata filtering and configurable indexes. Managed services can reduce operational work but introduce service limits, tenancy design, cost and deployment constraints. Compare exact and approximate configurations on the same permitted workload: report index build time, memory, ingest/update rate, median and p95 query latency, recall, and concurrent load. Warm and cold caches differ. For small datasets an exact baseline may be sufficient. Inspect the query plan and actual index use when integrating pgvector; filtered ANN can produce fewer hits than requested, and iterative scans or another index plan may help depending on version and selectivity. No live benchmarks are provided here.
Practice and common mistakes
Set k to 3, reverse the row order, and predict the result a, b, c. If a candidate list is a, c, e, measure index recall against that top three: 2/3. Do not mix cosine with L2 baselines, count duplicate candidates, silently divide by zero, or claim a synthetic score measures HNSW. Search tuning cannot fix an unsuitable encoder. Keep the exact baseline as an oracle for small fixtures and separately evaluate semantic relevance. Next, restrict the eligible corpus before ranking and recheck permissions before returning any payload.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exact and approximate retrieval quiz
Apply vector retrieval and lifecycle contracts.
What does exact top-k search do in this fixture?
Why can squared L2 replace L2 for ranking?
Which description matches HNSW?
Exact top two are a and b; candidate results are a and c. Index recall?
Which tool is a similarity-search library rather than a complete record database?