Search an inverted-file (IVF) vector index
Why it matters FAISS IVF indexes serve billions of vectors for search and RAG.
An IVF index assigns every vector to its nearest coarse centroid, then searches only the few closest lists at query time.
Write ivf_search(db, centroids, q, nprobe, k). Assign each db row to its nearest centroid (squared L2, ties to the smaller index). For the query, pick the nprobe nearest centroids (stable order), gather all db rows in those lists, and return the indices of the k nearest of them by squared L2 (ties by smaller index), as an int array. If fewer than k candidates exist return them all.
def ivf_search(db, centroids, q, nprobe, k)Example
with centroids [[0], [10]], db [[1], [9], [11], [2]], q [8], nprobe 1, k 2 searches list 1 only and returns [1, 2].
Understand the idea
An inverted-file index groups the database around a few coarse centroids, like sorting books onto shelves by topic. At query time you only look at the nprobe shelves whose centroids are closest to the query, which is much faster than checking every book but can miss a near match on another shelf. Worked example: centroids [0] and [10], db [[1], [4], [6], [12]], q [5], k 2. Rows 1 and 4 go to centroid 0; rows 6 and 12 go to centroid 1. The query is 25 away (squared) from both centroids, a tie, so centroid 0 comes first. With nprobe 1 you search rows 0 and 1 (values 1 and 4), distances 16 and 1, so the answer is [1, 0]. With nprobe 2 you search everything; values 4 and 6 both have distance 1, so the answer is [1, 2]. Rule: assign each row to its nearest centroid by squared L2 (ties to the lower index); pick the nprobe nearest centroids with a stable sort; gather their rows; return the k nearest by squared L2 with ties by lower index, or all candidates if fewer than k. Used in: FAISS IVF indexes and vector databases.
Shapes and data flow
db (n, d) vs centroids (C, d) -> assign (n,) q -> nearest nprobe centroids -> candidate ids -> exact top k