Sub topic 11
Matching the index operator class to the query operator
This chapter assumes you can create a table with a vector column, run ORDER BY embedding <=> ... LIMIT n queries, and have built an HNSW or IVFFlat index at least once. You should also know that the operators <->, <=>, <#>, and <+> each compute a different distance.
Why an index has to name an operator class
A pgvector index accelerates one specific distance. An HNSW graph built with L2 distance holds links that are only meaningful for L2. If you search it with cosine distance, the graph would navigate by the wrong measure. PostgreSQL prevents this with operator classes. An operator class tells an index access method which operators and support functions it can serve for a column type.
pgvector defines no default operator class for its index types. If you leave it out, PostgreSQL refuses to create the index:
CREATE INDEX ON items USING hnsw (embedding);
-- ERROR: data type vector has no default operator class for access method "hnsw"
-- HINT: You must specify an operator class for the index or define a default operator class for the data type.You must pick the class yourself, and it must match the operator in your queries.
The mapping
| Query operator | Meaning | Operator class | HNSW | IVFFlat |
|---|---|---|---|---|
| `<->` | L2 (Euclidean) distance | `vector_l2_ops` | yes | yes |
| `<=>` | Cosine distance | `vector_cosine_ops` | yes | yes |
| `<#>` | Negative inner product | `vector_ip_ops` | yes | yes |
| `<+>` | L1 (taxicab) distance | `vector_l1_ops` | yes | no |
The same pattern holds for the other types. halfvec uses halfvec_l2_ops, halfvec_cosine_ops, and so on. sparsevec uses sparsevec_l2_ops, and so on. bit uses bit_hamming_ops, plus bit_jaccard_ops for HNSW only. The next-but-one chapters cover those types.
Creating one index per metric
If your application uses cosine distance, build a cosine index. This is the same statement you have seen before, with the operator class stated deliberately:
CREATE INDEX items_embedding_cosine
ON items USING hnsw (embedding vector_cosine_ops);A column can carry several indexes with different operator classes. That is legal and sometimes useful when different features query the same embeddings with different metrics. Each index costs build time, disk, and write overhead, so add one only for a metric you actually query.
CREATE INDEX items_embedding_l2
ON items USING hnsw (embedding vector_l2_ops);
CREATE INDEX items_embedding_ip
ON items USING hnsw (embedding vector_ip_ops);What happens on a mismatch
A mismatch does not raise an error. The planner sees that the index cannot serve the operator in ORDER BY, ignores the index, and scans the whole table. You get correct, exact results, but slowly. This makes the mistake easy to miss on a small test table and costly in production.
Suppose only items_embedding_l2 exists and you run a cosine query. Because tiny tables favor a sequential scan anyway, turn sequential scans off for the session to see whether any index is usable:
DROP INDEX IF EXISTS items_embedding_cosine, items_embedding_ip;
SET enable_seqscan = off;
EXPLAIN
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The plan still shows a Seq Scan followed by a Sort, because no index supports <=>. Now query with the matching operator:
EXPLAIN
SELECT id FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;The plan shows Index Scan using items_embedding_l2 on items. Reset the setting afterwards with RESET enable_seqscan;.
To see which operator class each index was built with, read the index definitions:
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'items';Each indexdef ends with the column and class, such as (embedding vector_l2_ops).
Inner product has a sign trap
<#> returns the negative inner product. The reason is that PostgreSQL index scans return rows in ascending order only, and a larger inner product means a closer match. Negating the value makes the best match sort first.
To rank by inner product and also display the real value, multiply by -1 in the select list but order by the raw operator:
SELECT id, content, (embedding <#> '[3,1,2]') * -1 AS inner_product
FROM items
ORDER BY embedding <#> '[3,1,2]'
LIMIT 5;If you wrote ORDER BY (embedding <#> ...) * -1 DESC, the planner could not use a vector_ip_ops index.
The ORDER BY must keep the bare operator
The index is used only when the ORDER BY clause is the distance operator on the indexed expression, ascending, with a LIMIT. Two common ways to break this follow.
First, ordering by a derived value. This query returns correct results but cannot use the index:
-- Index not used: the sort key is 1 - distance, not the distance.
SELECT id FROM items
ORDER BY 1 - (embedding <=> '[3,1,2]') DESC
LIMIT 5;Order by the bare distance and compute the similarity in the select list, as in the cosine example from earlier chapters.
Second, indexing an expression. If you index a cast, the query must repeat the exact same expression:
CREATE INDEX items_embedding_half
ON items USING hnsw ((embedding::halfvec(3)) halfvec_cosine_ops);
SELECT id FROM items
ORDER BY embedding::halfvec(3) <=> '[3,1,2]'::halfvec(3)
LIMIT 5;A query that orders by plain embedding <=> ... will not match this index.
Choosing the class from your embeddings
Pick the metric first, then the class. The metric should match how the embedding model was trained or how you normalize.
- If the model documentation recommends cosine similarity, use
<=>andvector_cosine_ops. - If the vectors are normalized to length 1, cosine, L2, and inner product all produce the same ranking. In that case
vector_ip_opswith<#>is the cheapest to compute, so it is a reasonable choice. - If vectors are not normalized and magnitude carries meaning,
<#>and<=>rank differently. Choose deliberately instead of defaulting to cosine.
Checklist before shipping a query
- Decide the metric and the operator it uses.
- Create the index with the matching operator class.
- Run
EXPLAINon the real query, with real parameters and anyWHEREfilter, and look for an index scan on your vector index. - Confirm the
ORDER BYuses the bare operator, ascending, withLIMIT.
Exercise
A table has the index CREATE INDEX ON docs USING hnsw (embedding vector_l2_ops);. The application runs SELECT id FROM docs ORDER BY embedding <=> $1 LIMIT 10; and is slow on a table with millions of rows. Why does the query not error, why is it slow, and what is the fix?
Show answer
The <=> operator is cosine distance, but the only index uses vector_l2_ops, so the planner cannot use it. PostgreSQL does not raise an error, because a sequential scan with a sort still returns correct, exact results. The scan reads every row, which is why it is slow. The fix is to create an index with the matching class, CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);, or to change the query to use <-> if L2 is the right metric. Then confirm with EXPLAIN that an index scan appears.
Exercise
You want the five rows with the largest inner product to a query vector, using an index. Which operator class do you build, which operator goes in ORDER BY, and how do you show the true inner product in the results?
Show answer
Build the index with vector_ip_ops. Use ORDER BY embedding <#> query LIMIT 5, ascending, because <#> returns the negative inner product. In the select list, show (embedding <#> query) * -1 to turn it back into the true inner product.