Sub topic 2
The distance operators: `<->`, `<=>`, `<#>`, and `<+>`
This chapter assumes you know basic SQL (CREATE TABLE, INSERT, SELECT, ORDER BY, LIMIT), that you can run CREATE EXTENSION in a PostgreSQL database, and that you understand an embedding as a fixed-length array of numbers.
pgvector adds four binary operators. Each one computes a distance or score between two vectors, using a different metric.
| Operator | Metric | Ordering for nearest first |
|---|---|---|
| `<->` | Euclidean (L2) distance | `ORDER BY ... ASC` |
| `<=>` | Cosine distance | `ORDER BY ... ASC` |
| `<#>` | Negative inner product | `ORDER BY ... ASC` |
| `<+>` | Manhattan (L1) distance | `ORDER BY ... ASC` |
Exact nearest-neighbor queries with ORDER BY and LIMIT
Create a table and load three rows:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3)
);
INSERT INTO items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4,5,6]'),
('c', '[1,1,1]');Sort by a distance operator and limit the output:
SELECT id, content, embedding <-> '[3,1,2]' AS l2_distance
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;Without an index, PostgreSQL computes the distance for every row and sorts them. The result is exact.
Why approximate search exists and what it costs in recall
An exact scan reads every row, so its cost grows with the table size. Approximate indexes, such as HNSW, search a small part of the data and return results much faster.
Recall is the fraction of true nearest neighbors that the approximate search returns. A recall of 0.95 means the index found 95 of the 100 true neighbors. Missing neighbors is the cost of the speed gain.
Creating and querying an HNSW index
An HNSW index uses an operator class that must match the query operator. The class vector_cosine_ops pairs with <=>:
CREATE INDEX items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
SET hnsw.ef_search = 100;
SELECT id, content
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;If you query with <-> instead, the planner cannot use this index. Create vector_l2_ops for <->. Raising hnsw.ef_search widens the search and improves recall at the cost of speed.
Exercise
You created an HNSW index with vector_cosine_ops, but your query uses <->. Will the index be used, and what should you change?
Show answer
No. The operator class must match the operator. Either change the query to <=> or create a new index with vector_l2_ops.