neighbors finds the k most similar other rows for each row of a vector column and returns a column of lists, nearest first.
Signature
The projection is required so a query does not accidentally copy large unused columns.
Example
Return type
AnARRAY<STRUCT> with one struct per neighbor. Each struct contains similarity followed by the projected columns. For the example above:
Behavior
neighborsuses approximate nearest-neighbor search over an HNSW index, the standard approach for fast vector search over large relations. Results can occasionally differ from an exact search.- The HNSW index is cached in memory. Repeated queries over the same in-memory table in one engine reuse it, even with a different
k. See Caching. - The current row is excluded by row identity, not by comparing similarity to
1. - Fewer than
kavailable rows produces a shorter list. - Null or zero-magnitude embeddings produce an empty list.
- Neighbors come from the rows in the query’s input. A
WHEREfilter or aLIMITin a subquery changes which rows are compared. ALIMITin the sameSELECTasneighborsdoesn’t.
Flatten neighbors
Compute neighbors in a CTE, then useunnest to return one row per neighbor. Filter after the CTE so neighbors still come from the whole input:
Related operations
- Use a nearest-neighbor join to find the closest matches between two relations, such as a query set and a corpus.
- Use
simto compare two vectors directly.