pgvector HNSW index-supported queries
You need to use the distance operator (<=>, <->, or <#>) matching the ops class you used during index creation in your ORDER BY clause. A canonical query would be:
Pgvector provides a clustering-based indexing algorithm. The blog post describes how it works in detail. It provides the fastest index-build speed but the slowest query speeds of any indexing algorithm.
To create an index named document_embedding_idx on table document_embedding having a vector column named embedding, run:
This command creates an index for cosine-distance queries because of vector_cosine_ops. There are also "ops" classes for Euclidean distance and negative inner product:
| Distance type | Query operator | Index ops class |
|---|---|---|
| Cosine / Angular | <=> | vector_cosine_ops |
| Euclidean / L2 | <-> | vector_ip_ops |
| Negative inner product | <#> | vector_l2_ops |
Note: ivfflat should never be created on empty tables because it needs to cluster data, and that only happens when an index is first created, not when new rows are inserted or modified. Also, if your table undergoes a lot of modifications, you need to rebuild this index occasionally to maintain good accuracy. See the blog post for details.
Pgvector ivfflat has a lists index parameter that should be set. See the next section.