Sub topic 11
Matching the Index Operator Class to the Query Operator
This chapter assumes that you know basic PostgreSQL and SQL, including CREATE INDEX, SELECT, ORDER BY, and LIMIT. You should also understand that pgvector indexes perform nearest-neighbor searches using a chosen distance or similarity measure.
An operator class tells PostgreSQL how an index compares values. In pgvector, the operator class must match the distance operator used by the query. If they do not match, PostgreSQL cannot use that vector index for the nearest-neighbor ordering.
Operator and operator class pairs
The main vector operator classes are:
| Query operator | Meaning | Matching operator class |
|---|---|---|
| `<->` | Euclidean, or L2, distance | `vector_l2_ops` |
| `<=>` | Cosine distance | `vector_cosine_ops` |
| `<#>` | Negative inner product | `vector_ip_ops` |
| `<+>` | L1, or taxicab, distance | `vector_l1_ops` |
The query operator appears in the ORDER BY expression. The operator class appears when you create the index.
For example, this HNSW index supports cosine-distance queries:
CREATE INDEX items_embedding_cosine_idx
ON items USING hnsw (embedding vector_cosine_ops);
SELECT id, content
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The index and query both use cosine. PostgreSQL can consider the index because their comparison rules agree.
This index supports L2-distance queries instead:
CREATE INDEX items_embedding_l2_idx
ON items USING hnsw (embedding vector_l2_ops);
SELECT id, content
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;An L2 index does not replace a cosine index. If your application uses both metrics, you may need separate indexes. Each additional index consumes storage and increases the work required for inserts and updates.
Inner product has a negative result
The <#> operator returns the negative inner product. PostgreSQL indexes normally find the smallest values first, so pgvector negates the inner product to make nearest-neighbor ordering possible.
Use the operator directly in ORDER BY:
CREATE INDEX items_embedding_ip_idx
ON items USING hnsw (embedding vector_ip_ops);
SELECT id, content, -(embedding <#> '[3,1,2]') AS inner_product
FROM items
ORDER BY embedding <#> '[3,1,2]'
LIMIT 5;Do not order by the converted positive value when you expect the index to support the ordering. The indexable form is ORDER BY embedding <#> query_vector ASC.
A useful mental model
Use EXPLAIN to check whether PostgreSQL selected the expected index. The plan can still choose a sequential scan for a small table, because scanning the table may be cheaper.
Exercise
You created an HNSW index with vectorl2ops. Which operator should appear in the nearest-neighbor ORDER BY clause?
Show answer
Use the <-> operator, as in ORDER BY embedding <-> '[3,1,2]'.