Add hibernate-vector module: pgvector similarity search with Hibernate 7.4.17.Final and Spring Data JPA 4.2.0 (float[] to vector/halfvec, cosine and L2 in HQL and Criteria, SearchResults methods, HNSW plans from auto_explain and five ways a query stops using the index, recall vs hnsw.ef_search, filtered-search row loss, Spring AI PgVectorStore comparison; PostgreSQL 16.15, pgvector 0.8.7)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4XrpfdpsacrvqnrBM
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
# float[] <-> vector(4): the DDL Hibernate generates, the round trip, the failure modes
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
|
||||
== Versions seen at runtime
|
||||
Hibernate ORM (org.hibernate.Version): 7.4.17.Final
|
||||
server: PostgreSQL 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1) on x86_64-pc-linux-gnu
|
||||
|
||||
== Column type Hibernate created for Doc.embedding (pg_attribute)
|
||||
doc.embedding : vector(4)
|
||||
|
||||
== Insert and read back
|
||||
-- insert
|
||||
insert into doc (category,embedding,title) values (?,cast(? as vector),?)
|
||||
read back float[]: [0.7, 0.7, 0.0, 0.0]
|
||||
same values: true
|
||||
how pgvector prints it: [0.7,0.7,0,0]
|
||||
|
||||
== Failure: a three-element array for a vector(4) column
|
||||
DataIntegrityViolationException -> PSQLException: ERROR: expected 4 dimensions, not 3
|
||||
|
||||
== In-place change of the float[] is detected by dirty checking
|
||||
-- update sent at commit
|
||||
update doc set category=?,embedding=cast(? as vector),title=? where id=?
|
||||
|
||||
== Half precision: SqlTypes.VECTOR_FLOAT16 maps the same float[] to halfvec
|
||||
half_doc.embedding : halfvec(4)
|
||||
stored (embedding::text): [0.099975586,0.19995117,0.30004883,0.7001953]
|
||||
read back float[]: [0.099975586, 0.19995117, 0.30004883, 0.7001953]
|
||||
|
||||
== Failure: cosine distance against the zero vector
|
||||
select '[0,0,0,0]'::vector <=> '[1,2,3,4]'::vector -> NaN
|
||||
@@ -0,0 +1,41 @@
|
||||
# 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))<? order by (d1_0.embedding<=>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)
|
||||
@@ -0,0 +1,32 @@
|
||||
# The Criteria API: the same HQL functions through cb.function(...), and the float[] argument that must not be a literal
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
|
||||
== 1. Criteria with cb.parameter(float[].class): category = tech, top 3
|
||||
query vector: [1, 0.5, 0, 0]
|
||||
-- generated SQL
|
||||
select d1_0.title,(d1_0.embedding<=>cast(? as vector)) from doc d1_0 where d1_0.category=? order by 2 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. The HQL version of the same query returns the same rows (the two tied rows may swap places)
|
||||
-- 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
|
||||
same rows: true
|
||||
same nearest row: true
|
||||
|
||||
== 3. Then cb.literal(float[]) in the SAME SessionFactory
|
||||
cb.literal(float[]) -> FunctionArgumentException: Parameter 1 of function 'cosine_distance()' requires a vector type, but argument is of type 'float[]'
|
||||
|
||||
== 3b. And cb.parameter(float[].class) again, which worked in step 1
|
||||
cb.parameter(float[].class) -> FunctionArgumentException: Parameter 1 of function 'cosine_distance()' requires a vector type, but argument is of type 'float[]'
|
||||
(the rejected literal changed the answer for later parameters in this SessionFactory)
|
||||
|
||||
== 4. A fresh SessionFactory where cb.literal(float[]) is the first thing tried (what most people write first)
|
||||
cb.literal(float[]) -> FunctionArgumentException: Parameter 1 of function 'cosine_distance()' requires a vector type, but argument is of type 'float[]'
|
||||
cb.parameter(float[].class) -> FunctionArgumentException: Parameter 1 of function 'cosine_distance()' requires a vector type, but argument is of type 'float[]'
|
||||
|
||||
== 5. The workaround that still works there: SqmCriteriaNodeBuilder.value(value, typeSource)
|
||||
-- generated SQL
|
||||
select (d1_0.embedding<=>cast(? as vector)) from doc d1_0 order by 1 fetch first ? rows only
|
||||
nearest distance: 0.0010
|
||||
@@ -0,0 +1,54 @@
|
||||
# Spring Data JPA: @Query with HQL on a JpaRepository, and the 4.2 SearchResults vector-search methods
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
query vector: Vector.of(1, 0.5, 0, 0)
|
||||
|
||||
== 1. A plain @Query on a JpaRepository (what most projects need)
|
||||
-- generated SQL
|
||||
select d1_0.id,d1_0.category,d1_0.embedding,d1_0.title from doc d1_0 order by (d1_0.embedding<=>cast(? as vector)) fetch first ? rows only
|
||||
Spring Data repositories
|
||||
Hibernate batch inserts, long edition (same direction, 10x the length)
|
||||
|
||||
== 2. searchByEmbeddingNear(Vector, ScoringFunction.cosine()), the form the reference page lists first
|
||||
InvalidDataAccessApiUsageException: Near/Within keywords must be used with a Score or Range<Score> type
|
||||
|
||||
== 2b. The same method with a Score that accepts everything (distance at most 2)
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where (n1_0.embedding<=>cast(? as vector))<=? order by 5
|
||||
score 0.0010314221776160926 (COSINE) Spring Data repositories
|
||||
score 0.03262781810398663 (COSINE) Spring Boot actuator
|
||||
score 0.051316725414124575 (COSINE) Hibernate batch inserts
|
||||
score 0.4645367711975643 (COSINE) Postgres index tuning
|
||||
score 1.0 (COSINE) Sourdough starter basics
|
||||
|
||||
== 3. ... Near(Vector, Score.of(0.05, cosine)): distance at most 0.05
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where (n1_0.embedding<=>cast(? as vector))<=? order by 5
|
||||
score 0.0010314221776160926 (COSINE) Spring Data repositories
|
||||
score 0.03262781810398663 (COSINE) Spring Boot actuator
|
||||
|
||||
== 4. ... Near(Vector, Similarity.of(0.9, cosine)): similarity at least 0.9
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where (n1_0.embedding<=>cast(? as vector))<=? order by 5
|
||||
score 0.9994842889111919 (COSINE) Spring Data repositories
|
||||
score 0.9836860909480067 (COSINE) Spring Boot actuator
|
||||
score 0.9743416372929377 (COSINE) Hibernate batch inserts
|
||||
|
||||
== 4b. searchTop2ByEmbeddingNear(Vector, Score.of(2.0, cosine)): the nearest two, whatever the distance
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where (n1_0.embedding<=>cast(? as vector))<=? order by 5 fetch first ? rows only
|
||||
score 0.0010314221776160926 (COSINE) Spring Data repositories
|
||||
score 0.03262781810398663 (COSINE) Spring Boot actuator
|
||||
|
||||
== 5. searchByCountryAndEmbeddingWithin(country, Vector, Range<Similarity>)
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where n1_0.country=? and (n1_0.embedding<=>cast(? as vector))<=? and (n1_0.embedding<=>cast(? as vector))>=? order by 5
|
||||
score 0.9836860909480067 (COSINE) Spring Boot actuator
|
||||
score 0.7677316144012178 (COSINE) Postgres index tuning
|
||||
score 0.5 (COSINE) Sourdough starter basics
|
||||
|
||||
== 6. An @Query that projects the distance as the second column
|
||||
-- generated SQL
|
||||
select n1_0.id,n1_0.country,n1_0.embedding,n1_0.text,(n1_0.embedding<=>cast(? as vector)) from note n1_0 where n1_0.country=? order by 5
|
||||
score 0.03262781810398663 Spring Boot actuator
|
||||
score 0.4645367711975643 Postgres index tuning
|
||||
score 1.0 Sourdough starter basics
|
||||
@@ -0,0 +1,59 @@
|
||||
# HNSW index on 20,000 x 64-dimension rows: which Hibernate queries use it (auto_explain on the statements Hibernate really sent)
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
rows: 20000, dimensions: 64, clusters: 10
|
||||
|
||||
== 1. No index yet: the nearest-neighbour query reads every row
|
||||
Query Text: select c1_0.id from chunk c1_0 order by (c1_0.embedding<=>cast($1 as vector)) fetch first 10 rows only
|
||||
Limit (cost=1452.19..1452.22 rows=10 width=16) (actual time=5.744..5.747 rows=10 loops=1)
|
||||
-> Sort (cost=1452.19..1502.19 rows=20000 width=16) (actual time=5.742..5.744 rows=10 loops=1)
|
||||
Sort Key: ((embedding <=> '[<query vector>]'::vector))
|
||||
Sort Method: top-N heapsort Memory: 25kB
|
||||
-> Seq Scan on chunk c1_0 (cost=0.00..1020.00 rows=20000 width=16) (actual time=0.006..3.997 rows=20000 loops=1)
|
||||
|
||||
== 2. Create the HNSW index (the schema generator cannot: see T08)
|
||||
sql/hnsw-index.sql: create index chunk_hnsw_cos on chunk using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64)
|
||||
build time (indicative, this machine): 4044 ms
|
||||
table size: 6192 kB, HNSW index size: 11 MB
|
||||
indexdef: CREATE INDEX chunk_hnsw_cos ON public.chunk USING hnsw (embedding vector_cosine_ops) WITH (m='16', ef_construction='64')
|
||||
|
||||
== 3. Same HQL, now with the index: select c.id from Chunk c order by cosine_distance(c.embedding, :q) limit 10
|
||||
Query Text: select c1_0.id from chunk c1_0 order by (c1_0.embedding<=>cast($1 as vector)) fetch first 10 rows only
|
||||
Limit (cost=167.05..171.49 rows=10 width=16) (actual time=1.037..1.052 rows=10 loops=1)
|
||||
-> Index Scan using chunk_hnsw_cos on chunk c1_0 (cost=167.05..9048.00 rows=20000 width=16) (actual time=1.036..1.050 rows=10 loops=1)
|
||||
Order By: (embedding <=> '[<query vector>]'::vector)
|
||||
|
||||
== 4. Trap: L2 distance against a cosine index: select c.id from Chunk c order by euclidean_distance(c.embedding, :q) limit 10
|
||||
Query Text: select c1_0.id from chunk c1_0 order by (c1_0.embedding<->cast($1 as vector)) fetch first 10 rows only
|
||||
Limit (cost=1452.19..1452.22 rows=10 width=16) (actual time=5.240..5.243 rows=10 loops=1)
|
||||
-> Sort (cost=1452.19..1502.19 rows=20000 width=16) (actual time=5.237..5.239 rows=10 loops=1)
|
||||
Sort Key: ((embedding <-> '[<query vector>]'::vector))
|
||||
Sort Method: top-N heapsort Memory: 25kB
|
||||
-> Seq Scan on chunk c1_0 (cost=0.00..1020.00 rows=20000 width=16) (actual time=0.006..3.476 rows=20000 loops=1)
|
||||
|
||||
== 5. Trap: a distance threshold with no ORDER BY ... LIMIT: select c.id from Chunk c where cosine_distance(c.embedding, :q) < 0.3
|
||||
Query Text: select c1_0.id from chunk c1_0 where (c1_0.embedding<=>cast($1 as vector))<0.3
|
||||
Seq Scan on chunk c1_0 (cost=0.00..1070.00 rows=6667 width=8) (actual time=0.282..6.192 rows=7 loops=1)
|
||||
Filter: ((embedding <=> '[<query vector>]'::vector) < '0.3'::double precision)
|
||||
Rows Removed by Filter: 19993
|
||||
|
||||
== 6. Trap: ordering by a similarity expression instead of the distance: select c.id from Chunk c order by 1 - cosine_distance(c.embedding, :q) desc limit 10
|
||||
Query Text: select c1_0.id from chunk c1_0 order by (1-(c1_0.embedding<=>cast($1 as vector))) desc fetch first 10 rows only
|
||||
Limit (cost=1502.19..1502.22 rows=10 width=16) (actual time=7.318..7.322 rows=10 loops=1)
|
||||
-> Sort (cost=1502.19..1552.19 rows=20000 width=16) (actual time=7.315..7.317 rows=10 loops=1)
|
||||
Sort Key: (('1'::double precision - (embedding <=> '[<query vector>]'::vector))) DESC
|
||||
Sort Method: top-N heapsort Memory: 25kB
|
||||
-> Seq Scan on chunk c1_0 (cost=0.00..1070.00 rows=20000 width=16) (actual time=0.012..4.995 rows=20000 loops=1)
|
||||
|
||||
== 7. The Criteria shape from T03 (distance in the select list, so Hibernate renders 'order by 2'): does the index still work?
|
||||
Query Text: select c1_0.id,(c1_0.embedding<=>cast($1 as vector)) from chunk c1_0 order by 2 fetch first $2 rows only
|
||||
Limit (cost=167.05..171.49 rows=10 width=16) (actual time=0.886..0.923 rows=10 loops=1)
|
||||
-> Index Scan using chunk_hnsw_cos on chunk c1_0 (cost=167.05..9048.00 rows=20000 width=16) (actual time=0.884..0.920 rows=10 loops=1)
|
||||
Order By: (embedding <=> '[<query vector>]'::vector)
|
||||
|
||||
== 8. A category filter next to the ORDER BY: select c.id from Chunk c where c.category = 3 order by cosine_distance(c.embedding, :q) limit 10
|
||||
Query Text: select c1_0.id from chunk c1_0 where c1_0.category=3 order by (c1_0.embedding<=>cast($1 as vector)) fetch first 10 rows only
|
||||
Limit (cost=167.05..211.48 rows=10 width=16) (actual time=0.947..0.986 rows=6 loops=1)
|
||||
-> Index Scan using chunk_hnsw_cos on chunk c1_0 (cost=167.05..9053.00 rows=2000 width=16) (actual time=0.946..0.983 rows=6 loops=1)
|
||||
Order By: (embedding <=> '[<query vector>]'::vector)
|
||||
Filter: (category = 3)
|
||||
Rows Removed by Filter: 34
|
||||
@@ -0,0 +1,20 @@
|
||||
# HNSW is approximate: recall against exact search, hnsw.ef_search, LIMIT above ef_search, and filtered queries
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
100 query vectors, top 10 each, cosine distance, index chunk_hnsw_cos (m = 16, ef_construction = 64)
|
||||
|
||||
== 1. Recall@10 and latency by hnsw.ef_search (the default is 40)
|
||||
ef_search recall@10 avg ms per query (indicative)
|
||||
10 0.725 2.97
|
||||
20 0.874 2.01
|
||||
40 0.966 2.80
|
||||
100 0.995 3.38
|
||||
200 0.999 3.04
|
||||
|
||||
== 2. LIMIT 100 with the default ef_search = 40
|
||||
rows requested: 100, rows returned: 40
|
||||
with hnsw.ef_search = 200: rows returned: 100
|
||||
|
||||
== 3. Filter plus nearest neighbour: where c.category = 3 (10% of the rows), LIMIT 10
|
||||
default settings: 4.2 rows returned on average (10 asked for)
|
||||
SET hnsw.iterative_scan = relaxed_order: 10.0 rows returned on average
|
||||
first query vector, default settings: 6 rows
|
||||
@@ -0,0 +1,22 @@
|
||||
# Spring AI 2.1.0 PgVectorStore on the same database (hash-based stand-in embeddings, 32 dimensions)
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
|
||||
== 1. What the store created by itself
|
||||
id uuid
|
||||
content text
|
||||
metadata json
|
||||
embedding vector(32)
|
||||
CREATE INDEX spring_ai_vector_index ON public.vector_store USING hnsw (embedding vector_cosine_ops)
|
||||
CREATE UNIQUE INDEX vector_store_pkey ON public.vector_store USING btree (id)
|
||||
|
||||
== 2. similaritySearch(query = 'vector search with Hibernate and Spring Data', topK = 3)
|
||||
0.5241 IN Spring Data JPA can run vector search methods that return SearchResults
|
||||
0.5051 IN Hibernate maps float arrays to pgvector columns with hibernate-vector
|
||||
0.5040 US Sourdough starter needs flour water and patience
|
||||
|
||||
== 3. The same search with filterExpression("country == 'US'")
|
||||
0.5040 US Sourdough starter needs flour water and patience
|
||||
0.1336 US HNSW indexes in PostgreSQL trade recall for speed
|
||||
|
||||
== 4. The SQL PostgreSQL ran for the filtered search (auto_explain)
|
||||
SELECT *, embedding <=> $1 AS distance FROM public.vector_store WHERE embedding <=> $2 < $3 AND metadata::jsonb @@ '$."country" == "US"'::jsonpath ORDER BY distance LIMIT $4
|
||||
@@ -0,0 +1,11 @@
|
||||
# Two failures: Spring Data's Vector as an entity attribute, and an HNSW index from @Index
|
||||
# Hibernate ORM 7.4.17.Final (on the classpath), PostgreSQL 16.15, pgvector 0.8.7, JDK 25
|
||||
|
||||
== 1. @JdbcTypeCode(SqlTypes.VECTOR) @Array(length = 4) Vector embedding (org.springframework.data.domain.Vector)
|
||||
ClassCastException: class org.hibernate.type.descriptor.java.spi.UnknownBasicJavaType cannot be cast to class org.hibernate.type.descriptor.java.BasicPluralJavaType (org.hibernate.type.descriptor.java.spi.UnknownBasicJavaType and org.hibernate.type.descriptor.java.BasicPluralJavaType are in unnamed module of loader 'app')
|
||||
|
||||
== 2. @Table(indexes = @Index(columnList = "embedding vector_cosine_ops")) with hbm2ddl create
|
||||
SchemaManagementException: Halting on error : Error executing DDL "create index broken_idx on broken_indexed ("embedding vector_cosine_ops")" via JDBC [ERROR: column "embedding vector_cosine_ops" does not exist]
|
||||
caused by CommandAcceptanceException: Error executing DDL "create index broken_idx on broken_indexed ("embedding vector_cosine_ops")" via JDBC [ERROR: column "embedding vector_cosine_ops" does not exist]
|
||||
caused by PSQLException: ERROR: column "embedding vector_cosine_ops" does not exist
|
||||
index created: 0
|
||||
Reference in New Issue
Block a user