pgvector distance operators: L2 vs cosine vs inner product
Verdict: In pgvector, use the inner product operator for length-normalised embeddings such as OpenAI's for best performance. Use cosine distance as the magnitude-insensitive default for text similarity. The Euclidean operator computes L2 distance.
| Criterion | Euclidean (L2) | cosine | inner product |
|---|---|---|---|
| Operator symbol | less-than greater-than | less-than equals greater-than | less-than hash greater-than (negative inner product) |
| Use when | General Euclidean distance | Text embedding similarity; magnitude-insensitive default | Length-normalised embeddings such as OpenAI's; best performance |
Rules
- For length-normalised embeddings cosine and inner product rank equivalently, and inner product avoids extra normalisation, so it is recommended.
- The cosine distance operator ranks recommendation similarity in the documented tutorial's ORDER BY.
- pgvector's core distance operators are L2 (less-than greater-than), cosine (less-than equals greater-than) and negative inner product (less-than hash greater-than).
Traps
- Element-wise operators such as multiplication and subtraction are arithmetic, not distance metrics for similarity search.
- Using the wrong operator silently changes similarity ranking without raising an error.
- Euclidean distance works but is not the operator recommended for length-normalised embeddings.