> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chowder.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Nearest-neighbor joins

> Find related modern movies for each favorite using an optimized nearest-neighbor join operator.

A nearest-neighbor join finds the closest corpus rows for every row in a query relation. You express it with a correlated lateral subquery ordered by `sim`. Chowder’s query planner recognizes this lateral SQL pattern and executes an optimized nearest-neighbor join operator.

## Match older favorites to modern movies

Use the saved movie-summary embeddings on both sides. The query side contains Toy Story and The Matrix; the corpus side contains movies released from 2000 onward:

```chowder-sql theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
WITH movies AS (
    SELECT
        movie_id,
        title,
        release_year,
        summary_embedding
    FROM read_parquet('hf://buckets/chowderai/chowder-demo/parquet/data/cmu-movie-summaries-embeddings/*.parquet')
)
SELECT
    q.title AS favorite,
    nn.title AS related_movie,
    nn.similarity
FROM (
    SELECT *
    FROM movies
    WHERE movie_id IN (53085, 30007) -- Toy Story and The Matrix
) AS q, LATERAL ( -- Find related movies separately for each favorite
    SELECT
        d.title,
        sim(q.summary_embedding.output, d.summary_embedding.output) AS similarity -- Compare saved plot embeddings
    FROM movies AS d
    WHERE d.release_year >= 2000 -- Only compare with movies released from 2000 onward
    ORDER BY similarity DESC
    LIMIT 2 -- Two matches per favorite
) AS nn;
```

Recorded matches include Toy Story → Toy Story 3 and Buzz Lightyear of Star Command: The Adventure Begins, and The Matrix → The Matrix Reloaded and The Matrix Revolutions. The join compares plot-summary embeddings; titles are carried labels rather than matching keys. The release-year restriction makes the query and corpus populations distinct and prevents either original from matching itself.

Each query row yields up to two corpus matches. Approximate execution can return a different ranking, so treat displayed results as examples rather than exact assertions.

## Keep the supported shape

The correlated subquery must:

* Project `sim(query_vector, corpus_vector)` as its final selected value.
* Sort that similarity in descending order.
* Use a constant `LIMIT` with no `OFFSET`.
* Keep corpus filters independent of the query row. The correlated expression belongs in the similarity score.

Use `LEFT JOIN LATERAL (...) AS nn ON true` when unmatched query rows must remain in the output. Use vectors from the same embedding space and dimension on both sides.

For new data, first create each relation with `embed(...).output`, then use those vector columns in the same join shape. See [Create embeddings](https://docs.chowder.ai/guides/embeddings.md).

## How the planner optimizes the join

For the supported query shape above, Chowder plans an optimized nearest-neighbor join instead of leaving the work as a generic correlated subquery.

* **Prepare the corpus once.** Indexed execution builds a cosine-similarity HNSW index over the corpus and probes it for the query rows.
* **Avoid carrying unused values.** When the output projection makes it safe, the planner removes unneeded carried columns, including vector embeddings, while retaining values required by the join predicate.
* **Reuse eligible indexes within an engine.** Repeated queries over eligible, unchanged in-memory embedding columns can reuse a cached index. Do not assume this reuse across file scans or different engines.

Assign the complete query above to `SQL`, then inspect `chowder.sql(SQL).explain()` to confirm that a supported query uses `KnnJoinExec`. The plan shows the execution mode; auto mode makes its final choice at execution time.

## Execution mode

The join runs in one of three modes:

* **Exact** compares every query vector with every corpus vector.
* **Approximate** builds and probes a usearch HNSW index. It can trade recall for search speed and may return different neighbors from exact comparison.
* **Auto** chooses between them at execution time from the query and corpus row counts and the requested neighbor count. It's the default.

Use exact mode when you need exhaustive comparison. Set `CHOWDER_KNN_JOIN_MODE=exact` or `CHOWDER_KNN_JOIN_MODE=approx` when you need to force one strategy.

> [!NOTE]
>
> Use [`neighbors`](https://docs.chowder.ai/reference/column-functions/neighbors) for nearest other rows within one relation. Use a lateral nearest-neighbor join when the query and corpus are different relations.

See [Caching](https://docs.chowder.ai/concepts/caching.md) for result reuse, cache validity, and cache controls.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.