# Distance functions in HQL: cosine vs L2 vs inner product, and what each one becomes in SQL # Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25 query vector: [1, 0.5, 0, 0] axes: [java, databases, cooking, finance] == 1. cosine_distance: the nearest three -- HQL: select new Hit(d.title, cosine_distance(d.embedding, :q)) from Doc d order by cosine_distance(d.embedding, :q) limit :n select d1_0.title,(d1_0.embedding<=>cast(? as vector)) from doc d1_0 order by (d1_0.embedding<=>cast(? as vector)) fetch first ? rows only 0.0010 Spring Data repositories 0.0513 Hibernate batch inserts, long edition (same direction, 10x the length) 0.0513 Hibernate batch inserts == 2. euclidean_distance: the same data, a different ranking -- HQL: euclidean_distance select d1_0.title,(d1_0.embedding<->cast(? as vector)) from doc d1_0 order by (d1_0.embedding<->cast(? as vector)) fetch first ? rows only 0.1414 Spring Data repositories 0.3606 Hibernate batch inserts 1.0112 Postgres index tuning == 3. Where the 10x-long document lands cosine rank of the long edition: 2 euclid. rank of the long edition: 7 == 4. Every distance function Hibernate registers for PostgreSQL, one query -- generated SQL select d1_0.title,(d1_0.embedding<=>cast(? as vector)),(d1_0.embedding<->cast(? as vector)),((d1_0.embedding<->cast(? as vector))^2),l1_distance(d1_0.embedding,cast(? as vector)),((d1_0.embedding<#>cast(? as vector))*-1),(d1_0.embedding<#>cast(? as vector)),vector_dims(d1_0.embedding),vector_norm(d1_0.embedding) from doc d1_0 where d1_0.title like 'Hibernate batch inserts%' escape '' order by d1_0.id doc cosine l2 l2^2 l1 inner neg_in dims norm base 0.0513 0.3606 0.1300 0.5000 1.0500 -1.0500 4 0.9899 10x long 0.0513 8.8459 78.2500 12.5000 10.5000 -10.5000 4 9.8995 == 5. A distance threshold in WHERE (a range query) -- generated SQL select d1_0.title from doc d1_0 where (d1_0.embedding<=>cast(? as vector))cast(? as vector)) Spring Data repositories Hibernate batch inserts, long edition (same direction, 10x the length) Hibernate batch inserts == 6. Filter plus nearest neighbour (a category predicate) -- generated SQL select d1_0.title,(d1_0.embedding<=>cast(? as vector)) from doc d1_0 where d1_0.category=? order by (d1_0.embedding<=>cast(? as vector)) fetch first ? rows only 0.0010 Spring Data repositories 0.0513 Hibernate batch inserts, long edition (same direction, 10x the length)