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: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
LIMITwith noOFFSET. - Keep corpus filters independent of the query row. The correlated expression belongs in the similarity score.
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.
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.
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.
CHOWDER_KNN_JOIN_MODE=exact or CHOWDER_KNN_JOIN_MODE=approx when you need to force one strategy.
Use
neighbors for nearest other rows within one relation. Use a lateral nearest-neighbor join when the query and corpus are different relations.