mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 08:29:01 +00:00
## Problem The HNSW tuning section said only that a higher `ef_search` gives better accuracy and slower queries. A reader whose query uses a `limit` above `ef_search` gets fewer rows back. The docs didn't explain why, what the range is, or how to change the setting. Related to [FDBKIN-12895](https://linear.app/supabase/issue/FDBKIN-12895/document-performance-trade-offs-of-pgvectors-hnsw-ef-search-parameter) Closes [DOCS-1800](https://linear.app/supabase/issue/DOCS-1800/explain-that-hnswef-search-caps-hnsw-results-and-how-to-set-it) ## Solution The `ef_search` bullet on the "Going to production" guide now names the `hnsw.ef_search` setting, its default, and its valid range. Plain paragraphs after the list explain how it caps the rows an HNSW scan returns and how to set it. They cover a session, one transaction, a transaction-mode pooler, and a database function called through the Data API. They also point to iterative index scans for returning more rows, and don't repeat that explanation. The filtering section of the HNSW indexes page now names `hnsw.ef_search` as the limit, so the two pages agree. ## How to verify 1. Open https://docs-git-tedd-docs-1800-supabase.vercel.app/docs/guides/ai/going-to-prod#hnsw-understanding-efconstruction--efsearch--and-m and https://docs-git-tedd-docs-1800-supabase.vercel.app/docs/guides/ai/vector-indexes/hnsw-indexes#filtering-with-hnsw-indexes. 2. The `ef_search` bullet states the `hnsw.ef_search` default (40) and range (1 to 1,000), and stays one paragraph like the `m` and `ef_construction` bullets. 3. A paragraph after the list says that without iterative index scans, an HNSW index scan returns at most `ef_search` rows, even when the query's `limit` is larger. 4. A SQL block shows a `set` statement and a `set local` statement inside `begin` / `commit`. A second SQL block shows a database function with a `set hnsw.ef_search = 100` clause. 5. The paragraph about setting the value links to "Transaction mode limitations" and to "Querying a vector / embedding", and both links land on those sections. 6. A paragraph links to "Filtering with HNSW indexes", and the link lands on that section. 7. In "Filtering with HNSW indexes", the sentence about selective filters names `hnsw.ef_search` as the limit on rows a scan returns, and its link lands on the going-to-prod HNSW section. ## Checks Ran `pnpm turbo run typecheck`, `pnpm turbo run lint`, and `pnpm exec oxfmt --check` on the changed docs. Ran both SQL blocks in page order on Postgres 18 with pgvector 0.8.1, against 20k random vectors with an HNSW `vector_l2_ops` index and `vector` installed in the `extensions` schema. At the default, `limit 100` returned 40 rows. With `set` or `set local hnsw.ef_search = 100`, it returned 100 rows. The `set local` value reset after `commit`, and `1001` was rejected as outside 1..1000. The function with `set hnsw.ef_search = 100` returned 100 rows for `limit 200`, and the session value stayed at 40. At `ef_search = 1000`, `limit 1500` returned 1000 rows, and 1500 after `set hnsw.iterative_scan = relaxed_order`. Docs tests skipped: they need Docker. ## Checklist - [x] I have read the [Contributing Guidelines](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] I have checked that the change works in the preview deployment ## Feedback for Tedd To ask Tedd for a change to this PR, reply in Tedd's session on [DOCS-1800](https://linear.app/supabase/issue/DOCS-1800/explain-that-hnswef-search-caps-hnsw-results-and-how-to-set-it). Tedd doesn't read comments on this PR. --------- Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
128 lines
7.8 KiB
Plaintext
128 lines
7.8 KiB
Plaintext
---
|
|
id: 'ai-hnsw-indexes'
|
|
title: 'HNSW indexes'
|
|
description: 'Understanding HNSW indexes in pgvector'
|
|
sidebar_label: 'HNSW indexes'
|
|
---
|
|
|
|
HNSW is an algorithm for approximate nearest neighbor search. It is a frequently used index type that can improve performance when querying highly-dimensional vectors, like those representing embeddings.
|
|
|
|
## Usage
|
|
|
|
The way you create an HNSW index depends on the distance operator you are using. `pgvector` includes 3 distance operators:
|
|
|
|
| Operator | Description | [**Operator class**](https://www.postgresql.org/docs/current/sql-createopclass.html) |
|
|
| -------- | ---------------------- | ------------------------------------------------------------------------------------ |
|
|
| `<->` | Euclidean distance | `vector_l2_ops` |
|
|
| `<#>` | negative inner product | `vector_ip_ops` |
|
|
| `<=>` | cosine distance | `vector_cosine_ops` |
|
|
|
|
Use the following SQL commands to create an HNSW index for the operator(s) used in your queries.
|
|
|
|
### Euclidean L2 distance (`vector_l2_ops`)
|
|
|
|
```sql
|
|
create index on items using hnsw (column_name vector_l2_ops);
|
|
```
|
|
|
|
### Inner product (`vector_ip_ops`)
|
|
|
|
```sql
|
|
create index on items using hnsw (column_name vector_ip_ops);
|
|
```
|
|
|
|
### Cosine distance (`vector_cosine_ops`)
|
|
|
|
```sql
|
|
create index on items using hnsw (column_name vector_cosine_ops);
|
|
```
|
|
|
|
For the maximum dimensions you can index and how to check your pgvector version, see [Vector index limits](/docs/guides/ai/vector-indexes#limits).
|
|
|
|
## Example with high-dimensional vectors
|
|
|
|
For vectors with more than 2,000 dimensions, you can use the `halfvec` type to create indexes. Here's an example with 3,072 dimensions:
|
|
|
|
```sql
|
|
CREATE TABLE documents (
|
|
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
content text,
|
|
embedding vector(3072)
|
|
);
|
|
|
|
CREATE INDEX ON documents
|
|
USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);
|
|
```
|
|
|
|
## How does HNSW work?
|
|
|
|
HNSW uses proximity graphs (graphs connecting nodes based on distance between them) to approximate nearest-neighbor search. To understand HNSW, we can break it down into 2 parts:
|
|
|
|
- **Hierarchical (H):** The algorithm operates over multiple layers
|
|
- **Navigable Small World (NSW):** Each vector is a node within a graph and is connected to several other nodes
|
|
|
|
### Hierarchical
|
|
|
|
The hierarchical aspect of HNSW builds off of the idea of skip lists.
|
|
|
|
Skip lists are multi-layer linked lists. The bottom layer is a regular linked list connecting an ordered sequence of elements. Each new layer above removes some elements from the underlying layer (based on a fixed probability), producing a sparser subsequence that “skips” over elements.
|
|
|
|
The diagram below shows a multi-layer skip list. The bottom layer links every ordered element, and each layer above keeps a sparser subset that skips over elements.
|
|
|
|
<Image
|
|
alt="Diagram of a multi-layer skip list: the bottom layer is a linked list of all ordered elements, and each higher layer keeps a sparser subset that skips over elements."
|
|
src={{
|
|
light: '/docs/img/ai/vector-indexes/hnsw-indexes/skip-list--light.png',
|
|
dark: '/docs/img/ai/vector-indexes/hnsw-indexes/skip-list--dark.png',
|
|
}}
|
|
width={1400}
|
|
height={700}
|
|
/>
|
|
|
|
When searching for an element, the algorithm begins at the top layer and traverses its linked list horizontally. If the target element is found, the algorithm stops and returns it. Otherwise if the next element in the list is greater than the target (or `NULL`), the algorithm drops down to the next layer below. Since each layer below is less sparse than the layer above (with the bottom layer connecting all elements), the target will eventually be found. Skip lists offer O(log n) average complexity for both search and insertion/deletion.
|
|
|
|
### Navigable Small World
|
|
|
|
A navigable small world (NSW) is a special type of proximity graph that also includes long-range connections between nodes. These long-range connections support the “small world” property of the graph, meaning almost every node can be reached from any other node within a few hops. Without these additional long-range connections, many hops would be required to reach a far-away node.
|
|
|
|
The diagram below shows a navigable small world graph. Each node connects to nearby neighbors plus a few long-range links, so almost any node can reach any other in a few hops.
|
|
|
|
<Image
|
|
alt="Diagram of a navigable small world graph, where each node connects to nearby neighbors plus a few long-range links that let almost any node reach any other within a few hops."
|
|
src="/docs/img/ai/vector-indexes/hnsw-indexes/nsw.png"
|
|
className="max-h-[600px] mx-auto"
|
|
width={1016}
|
|
height={759}
|
|
/>
|
|
|
|
The “navigable” part of NSW specifically refers to the ability to logarithmically scale the greedy search algorithm on the graph, an algorithm that attempts to make only the locally optimal choice at each hop. Without this property, the graph may still be considered a small world with short paths between far-away nodes, but the greedy algorithm tends to miss them. Greedy search is ideal for NSW because it is quick to navigate and has low computational costs.
|
|
|
|
### **Hierarchical +** Navigable Small World
|
|
|
|
HNSW combines these two concepts. From the hierarchical perspective, the bottom layer consists of a NSW made up of short links between nodes. Each layer above “skips” elements and creates longer links between nodes further away from each other.
|
|
|
|
Like skip lists, search starts at the top layer and works its way down until it finds the target element. However, instead of comparing a scalar value at each layer to determine whether or not to descend to the layer below, a multi-dimensional distance measure (such as Euclidean distance) is used.
|
|
|
|
## When should you create HNSW indexes?
|
|
|
|
HNSW should be your default choice when creating a vector index. Add the index when you don't need 100% accuracy and are willing to trade a small amount of accuracy for a lot of throughput.
|
|
|
|
HNSW indexes are based on graphs, so they aren't affected by the same limitations as IVFFlat. For when you can build each index type, see [When to use each index type](/docs/guides/ai/vector-indexes#when-to-use-each-index-type).
|
|
|
|
## Filtering with HNSW indexes
|
|
|
|
Adding a `where` clause to a vector query does not bypass the HNSW index. The Postgres planner picks between using the index and a sequential scan based on the selectivity of the filter and the size of the table. When the index is used, the filter is applied as the index returns candidates.
|
|
|
|
The trade-off shows up when the filter is selective. An HNSW scan returns at most the nearest [`hnsw.ef_search`](/docs/guides/ai/going-to-prod#hnsw-understanding-efconstruction--efsearch--and-m) rows (40 by default). If the filter removes most of them, you get fewer rows than your `LIMIT`. From `pgvector` 0.8.0, the planner supports **iterative index scans** that automatically scan more of the index until enough results are found, controlled by the `hnsw.iterative_scan` GUC. The default is `off`. The two enabled modes are:
|
|
|
|
- `strict_order` preserves exact distance ordering across iterations.
|
|
- `relaxed_order` allows slight reordering across iterations for better recall.
|
|
|
|
`hnsw.max_scan_tuples` (default 20,000) and `hnsw.scan_mem_multiplier` (default 1) bound how far the iterative scan goes. See the [pgvector iterative scans documentation](https://github.com/pgvector/pgvector#iterative-index-scans) for the full reference.
|
|
|
|
For an end-to-end JavaScript example of filtering a vector search by another column, see [Filtering vector search by metadata](/docs/guides/ai/semantic-search#filtering-vector-search-by-metadata).
|
|
|
|
## Resources
|
|
|
|
Read more about indexing on `pgvector`'s [GitHub page](https://github.com/pgvector/pgvector#indexing).
|