Skip to main content
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

An ARRAY<STRUCT> with one struct per neighbor. Each struct contains similarity followed by the projected columns. For the example above:

Behavior

  • neighbors uses 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 k available 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 WHERE filter or a LIMIT in a subquery changes which rows are compared. A LIMIT in the same SELECT as neighbors doesn’t.

Flatten neighbors

Compute neighbors in a CTE, then use unnest to return one row per neighbor. Filter after the CTE so neighbors still come from the whole input:
  • Use a nearest-neighbor join to find the closest matches between two relations, such as a query set and a corpus.
  • Use sim to compare two vectors directly.