diff --git a/README.md b/README.md index 096dfaa..526e244 100755 --- a/README.md +++ b/README.md @@ -356,3 +356,4 @@ Modules with their own `pom.xml` that run plain Hibernate without the Spring Boo | [`enums`](enums/) | Enum mapping in Hibernate 7: `ORDINAL` vs `STRING` vs PostgreSQL native enum vs `AttributeConverter` vs JPA 3.2 `@EnumeratedValue`, the DDL each creates, what release 2 reads and writes after a constant is inserted, appended or renamed, `hbm2ddl=update` limits and the migration each change needs; plain Hibernate on H2 and PostgreSQL 18 (Hibernate `7.4.17.Final`) | | [`formula-filter`](formula-filter/) | `@Formula`, `@Filter` and `@SQLRestriction` in Hibernate 7: the SQL each one adds, `@Formula` staleness and the unqualified-column trap, where filters skip find-by-id, collections and loaded collections, `applyToLoadByKey`, `autoEnabled` tenant filters, and the removed `@Where`; plain Hibernate on H2 (Hibernate `7.4.17.Final`) | | [`embeddables`](embeddables/) | Records and value objects in Hibernate 7: `@Embeddable` records, null handling (all-null columns, partial nulls, compact constructors), collections of embeddables and the SQL for add/remove, record equality vs database equality, `@EmbeddedId` records, a DDD `Email` value object, and the failure modes; plain Hibernate on H2 (Hibernate `7.4.17.Final`) | +| [`hibernate-vector`](hibernate-vector/) | pgvector similarity search with Hibernate 7 and Spring Data JPA 4.2: `float[]` to `vector`/`halfvec`, cosine and L2 in HQL and Criteria, `SearchResults` repository methods, HNSW index plans from `auto_explain` (five ways a query stops using the index), recall vs `hnsw.ef_search`, filtered-search row loss, and Spring AI `PgVectorStore` for comparison; PostgreSQL 16 + pgvector 0.8.7 (Hibernate `7.4.17.Final`, Spring Boot `4.2.0`) | diff --git a/hibernate-vector/README.md b/hibernate-vector/README.md new file mode 100644 index 0000000..81afe4b --- /dev/null +++ b/hibernate-vector/README.md @@ -0,0 +1,48 @@ +# hibernate-vector + +Companion module for the ankurm.com article **Hibernate Vector Module: pgvector Similarity Search in HQL and Spring Data JPA**. +Every SQL line, plan and number in the article comes from a test here; each test writes what it observed to `output/` and asserts the same facts. + +## Versions + +| Component | Version | Notes | +|---|---|---| +| Hibernate ORM + `hibernate-vector` | `7.4.17.Final` | newest 7.x GA in `maven-metadata.xml` on 2026-11-26; Spring Boot 4.2.0 manages `7.4.15.Final`, so the POM overrides it | +| Spring Boot / Spring Data JPA | `4.2.0` / `4.2.0` | Spring Data JPA 4.2 adds the `SearchResults` vector-search methods | +| Spring AI (`spring-ai-pgvector-store`, test scope) | `2.1.0` | only for the comparison in `T07` | +| PostgreSQL / pgvector | `16.15` / `0.8.7` | pgvector built from the `v0.8.7` tag (released 2026-10-01) | +| JDBC driver | `42.7.14` | | +| Java | `25` (Temurin 25.0.5+2) | | + +## Run + +No Docker was available where this was written, so `scripts/start-postgres.sh` installs PostgreSQL 16 from apt, builds pgvector 0.8.7 and starts it on port 55433. +`T05` and `T07` read the server log for `auto_explain` plans, so the server must be local. + +```bash +./scripts/start-postgres.sh && ./scripts/run-all.sh # or: mvn clean test +``` + +## What is where + +| File | Role | +|---|---| +| `Doc`, `Chunk`, `HalfDoc` | Entities with `float[]` embeddings (`vector(4)`, `vector(64)`, `halfvec(4)`) | +| `Note`, `NoteRepository` | Spring Data JPA 4.2 vector-search methods returning `SearchResults` | +| `DocRepository` | `@Query` HQL nearest-neighbour methods | +| `sql/hnsw-index.sql` | The HNSW index statement the schema generator cannot produce | +| `src/test/.../com/ankurm/broken` | Deliberately broken entities, bootstrapped only by `T08` | + +| Test | Output | Question it answers | +|---|---|---| +| `T01_MappingTest` | `output/01-mapping.txt` | What DDL does `float[]` become, and what fails? | +| `T02_HqlTest` | `output/02-hql-distance.txt` | Which HQL functions exist, what SQL they become, cosine vs L2 | +| `T03_CriteriaTest` | `output/03-criteria.txt` | Does Criteria work, and what does it reject? | +| `T04_SpringDataTest` | `output/04-spring-data.txt` | `@Query` and the `SearchResults` methods | +| `T05_HnswIndexTest` | `output/05-hnsw-explain.txt` | Which Hibernate queries use the HNSW index (`auto_explain` on the real statements) | +| `T06_RecallTest` | `output/06-recall-ef-search.txt` | Recall, `hnsw.ef_search`, `LIMIT` above it, filters | +| `T07_SpringAiTest` | `output/07-spring-ai.txt` | What Spring AI's `PgVectorStore` creates and runs | +| `T08_SchemaGenerationFailureTest` | `output/08-failures.txt` | `Vector` as an attribute type, `@Index` for HNSW | + +The embeddings in `T01` to `T04` are four hand-picked axes so the numbers can be checked by eye; `T05` and `T06` use seeded synthetic clusters; `T07` uses a word-hashing stand-in model. No real embedding model was run. +Timings are indicative of one machine. diff --git a/hibernate-vector/output/01-mapping.txt b/hibernate-vector/output/01-mapping.txt new file mode 100644 index 0000000..9acabc6 --- /dev/null +++ b/hibernate-vector/output/01-mapping.txt @@ -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 diff --git a/hibernate-vector/output/02-hql-distance.txt b/hibernate-vector/output/02-hql-distance.txt new file mode 100644 index 0000000..72b1a78 --- /dev/null +++ b/hibernate-vector/output/02-hql-distance.txt @@ -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))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) diff --git a/hibernate-vector/output/03-criteria.txt b/hibernate-vector/output/03-criteria.txt new file mode 100644 index 0000000..b4fcfc9 --- /dev/null +++ b/hibernate-vector/output/03-criteria.txt @@ -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 diff --git a/hibernate-vector/output/04-spring-data.txt b/hibernate-vector/output/04-spring-data.txt new file mode 100644 index 0000000..c298125 --- /dev/null +++ b/hibernate-vector/output/04-spring-data.txt @@ -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 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) +-- 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 diff --git a/hibernate-vector/output/05-hnsw-explain.txt b/hibernate-vector/output/05-hnsw-explain.txt new file mode 100644 index 0000000..fcfbfff --- /dev/null +++ b/hibernate-vector/output/05-hnsw-explain.txt @@ -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 <=> '[]'::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 <=> '[]'::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 <-> '[]'::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 <=> '[]'::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 <=> '[]'::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 <=> '[]'::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 <=> '[]'::vector) + Filter: (category = 3) + Rows Removed by Filter: 34 diff --git a/hibernate-vector/output/06-recall-ef-search.txt b/hibernate-vector/output/06-recall-ef-search.txt new file mode 100644 index 0000000..faba66d --- /dev/null +++ b/hibernate-vector/output/06-recall-ef-search.txt @@ -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 diff --git a/hibernate-vector/output/07-spring-ai.txt b/hibernate-vector/output/07-spring-ai.txt new file mode 100644 index 0000000..2da288d --- /dev/null +++ b/hibernate-vector/output/07-spring-ai.txt @@ -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 diff --git a/hibernate-vector/output/08-failures.txt b/hibernate-vector/output/08-failures.txt new file mode 100644 index 0000000..d2fec11 --- /dev/null +++ b/hibernate-vector/output/08-failures.txt @@ -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 diff --git a/hibernate-vector/pom.xml b/hibernate-vector/pom.xml new file mode 100644 index 0000000..09ab109 --- /dev/null +++ b/hibernate-vector/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + hibernate-vector + 1.0.0 + hibernate-vector + pgvector similarity search with Hibernate 7 (hibernate-vector), HQL, Criteria, Spring Data JPA vector search, HNSW indexes, and Spring AI PgVectorStore for comparison + + + 25 + + 7.4.17.Final + 2.1.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hibernate.orm + hibernate-vector + + + org.postgresql + postgresql + runtime + + + org.springframework.ai + spring-ai-pgvector-store + ${spring-ai.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Xmx768m + + ${hibernate.version} + + + + + + diff --git a/hibernate-vector/scripts/run-all.sh b/hibernate-vector/scripts/run-all.sh new file mode 100755 index 0000000..8b69989 --- /dev/null +++ b/hibernate-vector/scripts/run-all.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. Needs JDK 25, Maven 3.9, network access to Maven Central, and a PostgreSQL with +# pgvector on 127.0.0.1:55433 (user postgres, trust auth, database vec; scripts/start-postgres.sh starts one without Docker). +# T05 and T07 read the server log (/tmp/hibvec-pg/pg.log, override with -Dpg.log=...) for auto_explain output, so the +# server has to be local and its log readable by the user running the tests. +# ./scripts/start-postgres.sh && ./scripts/run-all.sh +set -euo pipefail +cd "$(dirname "$0")/.." +mvn -B clean test +ls -1 output diff --git a/hibernate-vector/scripts/start-postgres.sh b/hibernate-vector/scripts/start-postgres.sh new file mode 100755 index 0000000..206546a --- /dev/null +++ b/hibernate-vector/scripts/start-postgres.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Starts a throwaway PostgreSQL 16 with pgvector 0.8.7 on 127.0.0.1:55433, without Docker. Idempotent. Run as root in a disposable sandbox. +# PostgreSQL : Ubuntu 24.04 packages postgresql-16 and postgresql-server-dev-16 (apt) +# pgvector : built from the v0.8.7 tag of https://github.com/pgvector/pgvector (the Ubuntu package is 0.6.0) +# PostgreSQL refuses to run as root, so this creates a throwaway OS user (pgj). +set -euo pipefail +B="${BASE:-/tmp/hibvec-pg}" +PGPORT="${PGPORT:-55433}" +PGBIN=/usr/lib/postgresql/16/bin +if [ ! -f /usr/share/postgresql/16/extension/vector.control ] || ! grep -q "0.8.7" /usr/share/postgresql/16/extension/vector.control; then + apt-get install -y postgresql-16 postgresql-server-dev-16 build-essential git >/dev/null + rm -rf /tmp/pgvector-src + git clone -q --depth 1 --branch v0.8.7 https://github.com/pgvector/pgvector.git /tmp/pgvector-src + make -C /tmp/pgvector-src -s && make -C /tmp/pgvector-src -s install +fi +id pgj >/dev/null 2>&1 || useradd -m pgj +mkdir -p "$B"; chown pgj "$B" +if [ ! -f "$B/data/PG_VERSION" ]; then + su pgj -c "cd /tmp && $PGBIN/initdb -D $B/data -U postgres -A trust -E UTF8 >/dev/null" +fi +su pgj -c "$PGBIN/pg_ctl -D $B/data -o '-p $PGPORT -k /tmp' -l $B/pg.log -w start" || true +psql -h 127.0.0.1 -p "$PGPORT" -U postgres -Atc "select 1 from pg_database where datname='vec'" | grep -q 1 \ + || psql -h 127.0.0.1 -p "$PGPORT" -U postgres -Atc "create database vec" +psql -h 127.0.0.1 -p "$PGPORT" -U postgres -d vec -Atc "select version()" diff --git a/hibernate-vector/sql/hnsw-index.sql b/hibernate-vector/sql/hnsw-index.sql new file mode 100644 index 0000000..d850390 --- /dev/null +++ b/hibernate-vector/sql/hnsw-index.sql @@ -0,0 +1,4 @@ +-- The HNSW index the tests build on the chunk table (20,000 rows, 64 dimensions). +-- Hibernate's schema generator cannot create it (see output/08-failures.txt), so it lives in a migration like this one. +-- vector_cosine_ops must match the operator the queries use: cosine_distance(..) in HQL is "<=>" in SQL. +create index chunk_hnsw_cos on chunk using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64); diff --git a/hibernate-vector/src/main/java/com/ankurm/halfvec/HalfDoc.java b/hibernate-vector/src/main/java/com/ankurm/halfvec/HalfDoc.java new file mode 100644 index 0000000..d17450f --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/halfvec/HalfDoc.java @@ -0,0 +1,31 @@ +package com.ankurm.halfvec; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** Half-precision storage (in its own package, outside the application's entity scan, on purpose: see T03): {@code SqlTypes.VECTOR_FLOAT16} maps the same {@code float[]} to pgvector's {@code halfvec}. */ +@Entity +@Table(name = "half_doc") +public class HalfDoc { + + @Id + private Long id; + + @JdbcTypeCode(SqlTypes.VECTOR_FLOAT16) + @Array(length = 4) + private float[] embedding; + + protected HalfDoc() { + } + + public HalfDoc(Long id, float[] embedding) { + this.id = id; + this.embedding = embedding; + } + + public float[] getEmbedding() { return embedding; } +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/Chunk.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/Chunk.java new file mode 100644 index 0000000..9cf5014 --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/Chunk.java @@ -0,0 +1,43 @@ +package com.ankurm.hibvector; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** + * The bigger table for the index experiments: 64 dimensions, 20,000 rows, ten categories. + * The HNSW index is NOT declared here; see {@code HnswIndexTest} and the article for why. + */ +@Entity +@Table(name = "chunk") +public class Chunk { + + public static final int DIMS = 64; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private int category; + + @JdbcTypeCode(SqlTypes.VECTOR) + @Array(length = DIMS) + private float[] embedding; + + protected Chunk() { + } + + public Chunk(int category, float[] embedding) { + this.category = category; + this.embedding = embedding; + } + + public Long getId() { return id; } + public int getCategory() { return category; } + public float[] getEmbedding() { return embedding; } +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/Doc.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/Doc.java new file mode 100644 index 0000000..9f43bec --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/Doc.java @@ -0,0 +1,48 @@ +package com.ankurm.hibvector; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** + * The smallest useful vector entity: a four-dimension embedding mapped to a PostgreSQL {@code vector(4)}. + * The four dimensions are hand-picked axes (java, databases, cooking, finance) so that the distances in the + * transcripts can be checked by eye. A real embedding model produces 384 to 3072 dimensions. + */ +@Entity +@Table(name = "doc") +public class Doc { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String title; + + private String category; + + /** {@code @JdbcTypeCode(SqlTypes.VECTOR)} + {@code @Array(length)} is the whole mapping. */ + @JdbcTypeCode(SqlTypes.VECTOR) + @Array(length = 4) + private float[] embedding; + + protected Doc() { + } + + public Doc(String title, String category, float... embedding) { + this.title = title; + this.category = category; + this.embedding = embedding; + } + + public Long getId() { return id; } + public String getTitle() { return title; } + public String getCategory() { return category; } + public float[] getEmbedding() { return embedding; } + public void setEmbedding(float[] embedding) { this.embedding = embedding; } +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/DocRepository.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/DocRepository.java new file mode 100644 index 0000000..ab9a4a7 --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/DocRepository.java @@ -0,0 +1,26 @@ +package com.ankurm.hibvector; + +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface DocRepository extends JpaRepository { + + /** The nearest neighbours by cosine distance; {@code <=>} in SQL. Needs ORDER BY + LIMIT to be able to use an HNSW index. */ + @Query("select d from Doc d order by cosine_distance(d.embedding, :q) limit :n") + List nearestByCosine(@Param("q") float[] q, @Param("n") int n); + + @Query("select new com.ankurm.hibvector.Hit(d.title, cosine_distance(d.embedding, :q)) from Doc d " + + "order by cosine_distance(d.embedding, :q) limit :n") + List hitsByCosine(@Param("q") float[] q, @Param("n") int n); + + @Query("select new com.ankurm.hibvector.Hit(d.title, euclidean_distance(d.embedding, :q)) from Doc d " + + "order by euclidean_distance(d.embedding, :q) limit :n") + List hitsByEuclidean(@Param("q") float[] q, @Param("n") int n); + + /** A category filter combined with the nearest-neighbour order. */ + @Query("select new com.ankurm.hibvector.Hit(d.title, cosine_distance(d.embedding, :q)) from Doc d " + + "where d.category = :category order by cosine_distance(d.embedding, :q) limit :n") + List hitsInCategory(@Param("q") float[] q, @Param("category") String category, @Param("n") int n); +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/Hit.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/Hit.java new file mode 100644 index 0000000..473545c --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/Hit.java @@ -0,0 +1,5 @@ +package com.ankurm.hibvector; + +/** A title with its distance, built by an HQL constructor expression. */ +public record Hit(String title, Double distance) { +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/Note.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/Note.java new file mode 100644 index 0000000..fc1a9e6 --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/Note.java @@ -0,0 +1,44 @@ +package com.ankurm.hibvector; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** + * Same idea as {@link Doc}, for the Spring Data JPA vector-search repository. The attribute stays a {@code float[]}: + * the Spring Data reference shows a {@code Vector} attribute, but Hibernate 7.4.17 cannot bootstrap that + * (see {@code T08_VectorAttributeFailureTest} and {@code com.ankurm.broken.BrokenNote}). + */ +@Entity +@Table(name = "note") +public class Note { + + @Id + private Long id; + + private String country; + + private String text; + + @JdbcTypeCode(SqlTypes.VECTOR) + @Array(length = 4) + private float[] embedding; + + protected Note() { + } + + public Note(Long id, String country, String text, float[] embedding) { + this.id = id; + this.country = country; + this.text = text; + this.embedding = embedding; + } + + public Long getId() { return id; } + public String getCountry() { return country; } + public String getText() { return text; } + public float[] getEmbedding() { return embedding; } +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/NoteRepository.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/NoteRepository.java new file mode 100644 index 0000000..3260a14 --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/NoteRepository.java @@ -0,0 +1,33 @@ +package com.ankurm.hibvector; + +import org.springframework.data.domain.Range; +import org.springframework.data.domain.Score; +import org.springframework.data.domain.ScoringFunction; +import org.springframework.data.domain.SearchResults; +import org.springframework.data.domain.Similarity; +import org.springframework.data.domain.Vector; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; + +/** Spring Data JPA vector search: methods that return {@link SearchResults}. No SQL, no HQL for the derived ones. */ +public interface NoteRepository extends Repository { + + Note save(Note note); + + SearchResults searchByEmbeddingNear(Vector vector, ScoringFunction function); + + SearchResults searchByEmbeddingNear(Vector vector, Score score); + + SearchResults searchByEmbeddingNear(Vector vector, Similarity similarity); + + /** Top-K: the Top keyword adds the LIMIT that the plain Near methods lack. */ + SearchResults searchTop2ByEmbeddingNear(Vector vector, Score score); + + SearchResults searchByCountryAndEmbeddingWithin(String country, Vector vector, Range range); + + @Query(""" + select n, cosine_distance(n.embedding, :embedding) as distance from Note n + where n.country = :country + order by distance asc""") + SearchResults searchAnnotatedByCountry(String country, Vector embedding); +} diff --git a/hibernate-vector/src/main/java/com/ankurm/hibvector/VectorDemoApplication.java b/hibernate-vector/src/main/java/com/ankurm/hibvector/VectorDemoApplication.java new file mode 100644 index 0000000..fd98fbe --- /dev/null +++ b/hibernate-vector/src/main/java/com/ankurm/hibvector/VectorDemoApplication.java @@ -0,0 +1,7 @@ +package com.ankurm.hibvector; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class VectorDemoApplication { +} diff --git a/hibernate-vector/src/main/resources/application.properties b/hibernate-vector/src/main/resources/application.properties new file mode 100644 index 0000000..eef3e13 --- /dev/null +++ b/hibernate-vector/src/main/resources/application.properties @@ -0,0 +1,10 @@ +# PostgreSQL with pgvector, started by scripts/start-postgres.sh (no Docker in the sandbox this was written in). +spring.datasource.url=${PG_URL:jdbc:postgresql://127.0.0.1:55433/vec} +spring.datasource.username=${PG_USER:postgres} +spring.datasource.password=${PG_PASSWORD:} +# The extension must exist before Hibernate creates a vector column, so schema.sql runs first. +spring.sql.init.mode=always +spring.jpa.hibernate.ddl-auto=create +spring.jpa.open-in-view=false +spring.jpa.properties.hibernate.jdbc.batch_size=200 +spring.jpa.properties.hibernate.order_inserts=true diff --git a/hibernate-vector/src/main/resources/schema.sql b/hibernate-vector/src/main/resources/schema.sql new file mode 100644 index 0000000..0aa0fc2 --- /dev/null +++ b/hibernate-vector/src/main/resources/schema.sql @@ -0,0 +1 @@ +CREATE EXTENSION IF NOT EXISTS vector; diff --git a/hibernate-vector/src/test/java/com/ankurm/broken/BrokenIndexed.java b/hibernate-vector/src/test/java/com/ankurm/broken/BrokenIndexed.java new file mode 100644 index 0000000..29240b8 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/broken/BrokenIndexed.java @@ -0,0 +1,22 @@ +package com.ankurm.broken; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Table; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +/** Deliberately broken: asks the schema generator for an operator-class index. JPA's @Index has no "using hnsw". */ +@Entity +@Table(name = "broken_indexed", indexes = @Index(name = "broken_idx", columnList = "embedding vector_cosine_ops")) +public class BrokenIndexed { + + @Id + Long id; + + @JdbcTypeCode(SqlTypes.VECTOR) + @Array(length = 4) + float[] embedding; +} diff --git a/hibernate-vector/src/test/java/com/ankurm/broken/BrokenNote.java b/hibernate-vector/src/test/java/com/ankurm/broken/BrokenNote.java new file mode 100644 index 0000000..33fd2c1 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/broken/BrokenNote.java @@ -0,0 +1,20 @@ +package com.ankurm.broken; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import org.hibernate.annotations.Array; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; +import org.springframework.data.domain.Vector; + +/** Deliberately broken: the attribute type is Spring Data's Vector, as in the Spring Data JPA reference's Comment example. Lives outside the scanned package. */ +@Entity +public class BrokenNote { + + @Id + Long id; + + @JdbcTypeCode(SqlTypes.VECTOR) + @Array(length = 4) + Vector embedding; +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/ChunkData.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/ChunkData.java new file mode 100644 index 0000000..45c8111 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/ChunkData.java @@ -0,0 +1,80 @@ +package com.ankurm.hibvector; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Random; +import org.springframework.jdbc.core.JdbcTemplate; + +/** Deterministic synthetic embeddings: ten clusters in 64 dimensions, so recall can be measured against exact search. */ +final class ChunkData { + + static final int ROWS = 20_000; + static final int CLUSTERS = 10; + + private static final float[][] CENTERS = centers(); + + private static float[][] centers() { + Random r = new Random(42); + float[][] c = new float[CLUSTERS][Chunk.DIMS]; + for (float[] v : c) { + for (int i = 0; i < v.length; i++) { + v[i] = (float) r.nextGaussian(); + } + } + return c; + } + + static float[] point(Random r, int cluster) { + float[] v = new float[Chunk.DIMS]; + for (int i = 0; i < v.length; i++) { + v[i] = CENTERS[cluster][i] + (float) (0.8 * r.nextGaussian()); + } + return v; + } + + static List queries(int n) { + Random r = new Random(99); + List q = new ArrayList<>(); + for (int i = 0; i < n; i++) { + q.add(point(r, r.nextInt(CLUSTERS))); + } + return q; + } + + static String literal(float[] v) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < v.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(String.format(Locale.ROOT, "%.4f", v[i])); + } + return sb.append(']').toString(); + } + + /** Runs sql/hnsw-index.sql, the one statement the schema generator cannot produce. */ + static void createIndex(JdbcTemplate jdbc) { + try { + jdbc.execute(java.nio.file.Files.readString(java.nio.file.Path.of("sql", "hnsw-index.sql"))); + } + catch (java.io.IOException e) { + throw new IllegalStateException(e); + } + jdbc.execute("analyze chunk"); + } + + /** Bulk load with plain JDBC batching: IDENTITY ids switch Hibernate's own insert batching off. */ + static void load(JdbcTemplate jdbc) { + jdbc.execute("drop index if exists chunk_hnsw_cos"); + jdbc.execute("truncate chunk restart identity"); + Random r = new Random(7); + List batch = new ArrayList<>(); + for (int i = 0; i < ROWS; i++) { + int cat = i % CLUSTERS; // independent of the cluster the vector comes from, like a tenant or a language column + batch.add(new Object[] {cat, literal(point(r, r.nextInt(CLUSTERS)))}); + } + jdbc.batchUpdate("insert into chunk (category, embedding) values (?, ?::vector)", batch); + jdbc.execute("analyze chunk"); + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/HashingEmbeddingModel.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/HashingEmbeddingModel.java new file mode 100644 index 0000000..6a8073f --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/HashingEmbeddingModel.java @@ -0,0 +1,58 @@ +package com.ankurm.hibvector; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.ai.document.Document; +import org.springframework.ai.embedding.Embedding; +import org.springframework.ai.embedding.EmbeddingModel; +import org.springframework.ai.embedding.EmbeddingRequest; +import org.springframework.ai.embedding.EmbeddingResponse; + +/** + * A stand-in for a real embedding model so the Spring AI part runs offline: it hashes each lower-cased word into one + * of 32 buckets and L2-normalises the counts. Texts that share words get similar vectors. It captures word overlap and + * nothing else; it is a plumbing test, not a semantic one. + */ +class HashingEmbeddingModel implements EmbeddingModel { + + static final int DIMS = 32; + + @Override + public EmbeddingResponse call(EmbeddingRequest request) { + List out = new ArrayList<>(); + int i = 0; + for (String text : request.getInstructions()) { + out.add(new Embedding(embed(text), i++)); + } + return new EmbeddingResponse(out); + } + + @Override + public float[] embed(Document document) { + return embed(document.getText()); + } + + @Override + public float[] embed(String text) { + float[] v = new float[DIMS]; + for (String w : text.toLowerCase().split("\\W+")) { + if (!w.isEmpty()) { + v[Math.floorMod(w.hashCode(), DIMS)] += 1f; + } + } + double norm = 0; + for (float x : v) { + norm += x * x; + } + norm = Math.sqrt(norm); + for (int i = 0; i < v.length; i++) { + v[i] /= (float) norm; + } + return v; + } + + @Override + public int dimensions() { + return DIMS; + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/SqlCapture.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/SqlCapture.java new file mode 100644 index 0000000..f582a3b --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/SqlCapture.java @@ -0,0 +1,37 @@ +package com.ankurm.hibvector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.hibernate.resource.jdbc.spi.StatementInspector; + +/** Records every SQL string Hibernate prepares, so the transcripts can show what HQL and Criteria became. */ +public class SqlCapture implements StatementInspector { + + private static final List SQL = new CopyOnWriteArrayList<>(); + + @Override + public String inspect(String sql) { + SQL.add(sql); + return sql; + } + + public static void clear() { + SQL.clear(); + } + + public static List snapshot() { + return new ArrayList<>(SQL); + } + + /** The last statement that mentions a given fragment. */ + public static String last(String fragment) { + List copy = snapshot(); + for (int i = copy.size() - 1; i >= 0; i--) { + if (copy.get(i).contains(fragment)) { + return copy.get(i); + } + } + return "(none)"; + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T01_MappingTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T01_MappingTest.java new file mode 100644 index 0000000..9e7fcd0 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T01_MappingTest.java @@ -0,0 +1,102 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import jakarta.persistence.EntityManager; +import java.util.Arrays; +import com.ankurm.halfvec.HalfDoc; +import org.hibernate.Version; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.support.TransactionTemplate; + +class T01_MappingTest extends VectorTestBase { + + @Autowired + EntityManager em; + + @Autowired + TransactionTemplate tx; + + @Test + void mappingRoundTrip() { + Transcript t = new Transcript("01-mapping", "float[] <-> vector(4): the DDL Hibernate generates, the round trip, the failure modes", serverInfo()); + docs.deleteAll(); + + t.heading("Versions seen at runtime"); + t.line("Hibernate ORM (org.hibernate.Version): " + Version.getVersionString()); + t.line("server: " + jdbc.queryForObject("select version()", String.class).split(",")[0]); + + t.heading("Column type Hibernate created for Doc.embedding (pg_attribute)"); + String type = jdbc.queryForObject( + "select format_type(atttypid, atttypmod) from pg_attribute where attrelid = 'doc'::regclass and attname = 'embedding'", String.class); + t.line("doc.embedding : " + type); + assertThat(type).isEqualTo("vector(4)"); + + t.heading("Insert and read back"); + SqlCapture.clear(); + Doc saved = docs.saveAndFlush(new Doc("Hibernate batch inserts", "tech", 0.7f, 0.7f, 0f, 0f)); + t.sql("insert", SqlCapture.last("insert into doc")); + em.clear(); + Doc loaded = docs.findById(saved.getId()).orElseThrow(); + t.line("read back float[]: " + Arrays.toString(loaded.getEmbedding())); + t.line("same values: " + Arrays.equals(loaded.getEmbedding(), new float[] {0.7f, 0.7f, 0f, 0f})); + t.line("how pgvector prints it: " + jdbc.queryForObject("select embedding::text from doc", String.class)); + assertThat(loaded.getEmbedding()).containsExactly(0.7f, 0.7f, 0f, 0f); + + t.heading("Failure: a three-element array for a vector(4) column"); + String msg = failureMessage(() -> docs.saveAndFlush(new Doc("too short", "tech", 1f, 2f, 3f))); + t.line(msg); + assertThat(msg).containsIgnoringCase("expected 4 dimensions, not 3"); + + t.heading("In-place change of the float[] is detected by dirty checking"); + SqlCapture.clear(); + tx.executeWithoutResult(s -> { + Doc d = docs.findById(saved.getId()).orElseThrow(); + d.getEmbedding()[0] = 0.5f; + }); + String update = SqlCapture.last("update doc"); + t.sql("update sent at commit", update); + assertThat(update).startsWith("update doc"); + + t.heading("Half precision: SqlTypes.VECTOR_FLOAT16 maps the same float[] to halfvec"); + jdbc.execute("drop table if exists half_doc"); + var registry = new org.hibernate.boot.registry.StandardServiceRegistryBuilder().applySettings(java.util.Map.of( + "jakarta.persistence.jdbc.url", T08_SchemaGenerationFailureTest.URL, + "jakarta.persistence.jdbc.user", "postgres", + "jakarta.persistence.jdbc.password", "", + "hibernate.hbm2ddl.auto", "create")).build(); + try (var sf = new org.hibernate.boot.MetadataSources(registry).addAnnotatedClass(HalfDoc.class).buildMetadata().buildSessionFactory()) { + sf.inTransaction(s -> s.persist(new HalfDoc(1L, new float[] {0.1f, 0.2f, 0.3f, 0.7f}))); + String halfType = jdbc.queryForObject( + "select format_type(atttypid, atttypmod) from pg_attribute where attrelid = 'half_doc'::regclass and attname = 'embedding'", String.class); + t.line("half_doc.embedding : " + halfType); + t.line("stored (embedding::text): " + jdbc.queryForObject("select embedding::text from half_doc", String.class)); + float[] back = sf.fromTransaction(s -> s.find(HalfDoc.class, 1L).getEmbedding()); + t.line("read back float[]: " + Arrays.toString(back)); + assertThat(halfType).isEqualTo("halfvec(4)"); + } + jdbc.execute("drop table if exists half_doc"); + + t.heading("Failure: cosine distance against the zero vector"); + Object nan = jdbc.queryForObject("select '[0,0,0,0]'::vector <=> '[1,2,3,4]'::vector", Object.class); + t.line("select '[0,0,0,0]'::vector <=> '[1,2,3,4]'::vector -> " + nan); + assertThat(String.valueOf(nan)).isEqualTo("NaN"); + t.write(); + } + + private static String failureMessage(Runnable r) { + try { + r.run(); + return "(no exception)"; + } + catch (RuntimeException e) { + Throwable root = e; + while (root.getCause() != null) { + root = root.getCause(); + } + return e.getClass().getSimpleName() + " -> " + root.getClass().getSimpleName() + ": " + root.getMessage().split("\n")[0]; + } + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T02_HqlTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T02_HqlTest.java new file mode 100644 index 0000000..9311ea9 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T02_HqlTest.java @@ -0,0 +1,100 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.persistence.EntityManager; +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +class T02_HqlTest extends VectorTestBase { + + @Autowired + EntityManager em; + + static final float[] QUERY = {1f, 0.5f, 0f, 0f}; // "java persistence" + + @Test + void distanceFunctionsInHql() { + seedDocs(); + Transcript t = new Transcript("02-hql-distance", "Distance functions in HQL: cosine vs L2 vs inner product, and what each one becomes in SQL", serverInfo()); + t.line("query vector: [1, 0.5, 0, 0] axes: [java, databases, cooking, finance]"); + + t.heading("1. cosine_distance: the nearest three"); + SqlCapture.clear(); + List cos = docs.hitsByCosine(QUERY, 3); + t.sql("HQL: select new Hit(d.title, cosine_distance(d.embedding, :q)) from Doc d order by cosine_distance(d.embedding, :q) limit :n", SqlCapture.last("from doc")); + cos.forEach(h -> t.line(row(h))); + assertThat(SqlCapture.last("from doc")).contains("<=>"); + + t.heading("2. euclidean_distance: the same data, a different ranking"); + SqlCapture.clear(); + List l2 = docs.hitsByEuclidean(QUERY, 3); + t.sql("HQL: euclidean_distance", SqlCapture.last("from doc")); + l2.forEach(h -> t.line(row(h))); + assertThat(SqlCapture.last("from doc")).contains("<->"); + + t.heading("3. Where the 10x-long document lands"); + t.line("cosine rank of the long edition: " + rank(docs.hitsByCosine(QUERY, 10), "long edition")); + t.line("euclid. rank of the long edition: " + rank(docs.hitsByEuclidean(QUERY, 10), "long edition")); + assertThat(rank(docs.hitsByCosine(QUERY, 10), "long edition")).isLessThanOrEqualTo(2); + assertThat(rank(docs.hitsByEuclidean(QUERY, 10), "long edition")).isEqualTo(7); + + t.heading("4. Every distance function Hibernate registers for PostgreSQL, one query"); + @SuppressWarnings("unchecked") + List rows = em.createQuery(""" + select d.title, + cosine_distance(d.embedding, :q), + euclidean_distance(d.embedding, :q), + euclidean_squared_distance(d.embedding, :q), + l1_distance(d.embedding, :q), + inner_product(d.embedding, :q), + negative_inner_product(d.embedding, :q), + vector_dims(d.embedding), + vector_norm(d.embedding) + from Doc d where d.title like 'Hibernate batch inserts%' order by d.id + """).setParameter("q", QUERY).getResultList(); + t.sql("generated SQL", SqlCapture.last("vector_dims")); + t.line(String.format("%-14s %8s %8s %8s %8s %8s %8s %5s %7s", "doc", "cosine", "l2", "l2^2", "l1", "inner", "neg_in", "dims", "norm")); + for (Object[] r : rows) { + String name = r[0].toString().contains("long edition") ? "10x long" : "base"; + t.line(String.format(Locale.ROOT, "%-14s %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %5s %7.4f", name, + (Double) r[1], (Double) r[2], (Double) r[3], (Double) r[4], (Double) r[5], (Double) r[6], r[7], (Double) r[8])); + } + assertThat((Double) rows.get(0)[1]).isEqualTo((Double) rows.get(1)[1], org.assertj.core.data.Offset.offset(1e-6)); + + t.heading("5. A distance threshold in WHERE (a range query)"); + SqlCapture.clear(); + @SuppressWarnings("unchecked") + List within = em.createQuery(""" + select d.title from Doc d + where cosine_distance(d.embedding, :q) < :max + order by cosine_distance(d.embedding, :q) + """).setParameter("q", QUERY).setParameter("max", 0.1).getResultList(); + t.sql("generated SQL", SqlCapture.last("from doc")); + within.forEach(s -> t.line(" " + s)); + assertThat(within).isNotEmpty().doesNotContain("Cast iron pan care"); + + t.heading("6. Filter plus nearest neighbour (a category predicate)"); + List tech = docs.hitsInCategory(QUERY, "tech", 2); + SqlCapture.clear(); + docs.hitsInCategory(QUERY, "tech", 2); + t.sql("generated SQL", SqlCapture.last("from doc")); + tech.forEach(h -> t.line(row(h))); + t.write(); + } + + static String row(Hit h) { + return String.format(Locale.ROOT, " %.4f %s", h.distance(), h.title()); + } + + static int rank(List hits, String fragment) { + for (int i = 0; i < hits.size(); i++) { + if (hits.get(i).title().contains(fragment)) { + return i + 1; + } + } + return -1; + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T03_CriteriaTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T03_CriteriaTest.java new file mode 100644 index 0000000..954ff38 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T03_CriteriaTest.java @@ -0,0 +1,119 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import jakarta.persistence.criteria.ParameterExpression; +import jakarta.persistence.criteria.Root; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import org.hibernate.query.sqm.internal.SqmCriteriaNodeBuilder; +import org.hibernate.query.sqm.tree.expression.SqmExpression; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * Every Criteria experiment runs in its own application context, so its own SessionFactory: what Hibernate decides + * about a float[] argument turned out to depend on what was tried first in the same SessionFactory (see section 4). + */ +class T03_CriteriaTest extends VectorTestBase { + + static ConfigurableApplicationContext freshApplication() { + return new SpringApplicationBuilder(VectorDemoApplication.class) + .web(WebApplicationType.NONE) + .run("--spring.jpa.hibernate.ddl-auto=none", "--spring.main.banner-mode=off", // arguments beat application.properties' create + "--spring.jpa.properties.hibernate.session_factory.statement_inspector=com.ankurm.hibvector.SqlCapture"); + } + + @Test + void criteriaCallsTheSameFunctions() { + seedDocs(); + Transcript t = new Transcript("03-criteria", "The Criteria API: the same HQL functions through cb.function(...), and the float[] argument that must not be a literal", serverInfo()); + + try (ConfigurableApplicationContext ctx = freshApplication()) { + EntityManager em = ctx.getBean(EntityManager.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + + t.heading("1. Criteria with cb.parameter(float[].class): category = tech, top 3"); + CriteriaQuery cq = cb.createQuery(Hit.class); + Root d = cq.from(Doc.class); + ParameterExpression q = cb.parameter(float[].class, "q"); + Expression distance = cb.function("cosine_distance", Double.class, d.get("embedding"), q); + cq.select(cb.construct(Hit.class, d.get("title"), distance)) + .where(cb.equal(d.get("category"), "tech")) + .orderBy(cb.asc(distance)); + SqlCapture.clear(); + List hits = em.createQuery(cq).setParameter("q", T02_HqlTest.QUERY).setMaxResults(3).getResultList(); + t.line("query vector: [1, 0.5, 0, 0]"); + t.sql("generated SQL", SqlCapture.last("from doc")); + hits.forEach(h -> t.line(T02_HqlTest.row(h))); + + t.heading("2. The HQL version of the same query returns the same rows (the two tied rows may swap places)"); + SqlCapture.clear(); + List viaHql = docs.hitsInCategory(T02_HqlTest.QUERY, "tech", 3); + t.sql("generated SQL", SqlCapture.last("from doc")); + // Two rows tie exactly (same direction, different length), and ORDER BY says nothing about ties, so the order of + // those two may differ between statements. Compare the sets and the first row. + t.line("same rows: " + new HashSet<>(titles(hits)).equals(new HashSet<>(titles(viaHql)))); + t.line("same nearest row: " + titles(hits).get(0).equals(titles(viaHql).get(0))); + assertThat(titles(hits)).containsExactlyInAnyOrderElementsOf(titles(viaHql)); + assertThat(titles(hits).get(0)).isEqualTo(titles(viaHql).get(0)); + + t.heading("3. Then cb.literal(float[]) in the SAME SessionFactory"); + String literal = attempt(cb, "cb.literal(float[])", () -> cb.literal(T02_HqlTest.QUERY), t); + assertThat(literal).contains("requires a vector type"); + t.heading("3b. And cb.parameter(float[].class) again, which worked in step 1"); + String again = attempt(cb, "cb.parameter(float[].class)", () -> cb.parameter(float[].class), t); + t.line("(the rejected literal changed the answer for later parameters in this SessionFactory)"); + assertThat(again).contains("requires a vector type"); + } + + try (ConfigurableApplicationContext ctx = freshApplication()) { + EntityManager em = ctx.getBean(EntityManager.class); + CriteriaBuilder cb = em.getCriteriaBuilder(); + t.heading("4. A fresh SessionFactory where cb.literal(float[]) is the first thing tried (what most people write first)"); + assertThat(attempt(cb, "cb.literal(float[])", () -> cb.literal(T02_HqlTest.QUERY), t)).contains("requires a vector type"); + assertThat(attempt(cb, "cb.parameter(float[].class)", () -> cb.parameter(float[].class), t)).contains("requires a vector type"); + + t.heading("5. The workaround that still works there: SqmCriteriaNodeBuilder.value(value, typeSource)"); + SqmCriteriaNodeBuilder nb = (SqmCriteriaNodeBuilder) cb; + CriteriaQuery c1 = cb.createQuery(Double.class); + Root d1 = c1.from(Doc.class); + Expression typed = nb.value(T02_HqlTest.QUERY, (SqmExpression) d1.get("embedding")); + Expression dist1 = cb.function("cosine_distance", Double.class, d1.get("embedding"), typed); + c1.select(dist1).orderBy(cb.asc(dist1)); + SqlCapture.clear(); + Double nearest = em.createQuery(c1).setMaxResults(1).getSingleResult(); + t.sql("generated SQL", SqlCapture.last("from doc")); + t.line(String.format(Locale.ROOT, "nearest distance: %.4f", nearest)); + assertThat(nearest).isLessThan(0.01); + } + t.write(); + } + + /** Builds cosine_distance(d.embedding, ) and reports whether Hibernate accepted it. */ + private static String attempt(CriteriaBuilder cb, String label, java.util.function.Supplier> argument, Transcript t) { + Root d = cb.createQuery(Double.class).from(Doc.class); + String r; + try { + cb.function("cosine_distance", Double.class, d.get("embedding"), argument.get()); + r = "accepted"; + } + catch (RuntimeException ex) { + r = ex.getClass().getSimpleName() + ": " + ex.getMessage(); + } + t.line(String.format("%-30s -> %s", label, r)); + return r; + } + + private static List titles(List hits) { + return hits.stream().map(Hit::title).toList(); + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T04_SpringDataTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T04_SpringDataTest.java new file mode 100644 index 0000000..38bf740 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T04_SpringDataTest.java @@ -0,0 +1,113 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Range; +import org.springframework.data.domain.Score; +import org.springframework.data.domain.ScoringFunction; +import org.springframework.data.domain.SearchResult; +import org.springframework.data.domain.SearchResults; +import org.springframework.data.domain.Similarity; +import org.springframework.data.domain.Vector; + +class T04_SpringDataTest extends VectorTestBase { + + @Autowired + NoteRepository notes; + + static final Vector Q = Vector.of(1f, 0.5f, 0f, 0f); + + @BeforeEach + void seed() { + jdbc.update("delete from note"); + notes.save(new Note(1L, "IN", "Hibernate batch inserts", new float[] {0.7f, 0.7f, 0f, 0f})); + notes.save(new Note(2L, "IN", "Spring Data repositories", new float[] {0.9f, 0.4f, 0f, 0f})); + notes.save(new Note(3L, "US", "Postgres index tuning", new float[] {0.1f, 0.95f, 0f, 0.1f})); + notes.save(new Note(4L, "US", "Sourdough starter basics", new float[] {0f, 0f, 1f, 0f})); + notes.save(new Note(5L, "US", "Spring Boot actuator", new float[] {0.95f, 0.2f, 0f, 0f})); + SqlCapture.clear(); + } + + @Test + void vectorSearchMethods() { + seedDocs(); + Transcript t = new Transcript("04-spring-data", "Spring Data JPA: @Query with HQL on a JpaRepository, and the 4.2 SearchResults vector-search methods", serverInfo()); + t.line("query vector: Vector.of(1, 0.5, 0, 0)"); + + t.heading("1. A plain @Query on a JpaRepository (what most projects need)"); + List top = docs.nearestByCosine(T02_HqlTest.QUERY, 2); + SqlCapture.clear(); + docs.nearestByCosine(T02_HqlTest.QUERY, 2); + t.sql("generated SQL", SqlCapture.last("from doc")); + top.forEach(x -> t.line(" " + x.getTitle())); + assertThat(top).hasSize(2); + + t.heading("2. searchByEmbeddingNear(Vector, ScoringFunction.cosine()), the form the reference page lists first"); + String failure; + try { + notes.searchByEmbeddingNear(Q, ScoringFunction.cosine()); + failure = "(no exception)"; + } + catch (RuntimeException e) { + failure = e.getClass().getSimpleName() + ": " + e.getMessage(); + } + t.line(failure); + assertThat(failure).contains("Near/Within keywords must be used with a Score"); + + t.heading("2b. The same method with a Score that accepts everything (distance at most 2)"); + SqlCapture.clear(); + SearchResults all = notes.searchByEmbeddingNear(Q, Score.of(2.0, ScoringFunction.cosine())); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, all); + assertThat(all.getContent()).hasSize(5); + assertThat(all.getContent().get(0).getContent().getText()).isEqualTo("Spring Data repositories"); + + t.heading("3. ... Near(Vector, Score.of(0.05, cosine)): distance at most 0.05"); + SqlCapture.clear(); + SearchResults near = notes.searchByEmbeddingNear(Q, Score.of(0.05, ScoringFunction.cosine())); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, near); + + t.heading("4. ... Near(Vector, Similarity.of(0.9, cosine)): similarity at least 0.9"); + SqlCapture.clear(); + SearchResults sim = notes.searchByEmbeddingNear(Q, Similarity.of(0.9, ScoringFunction.cosine())); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, sim); + + t.heading("4b. searchTop2ByEmbeddingNear(Vector, Score.of(2.0, cosine)): the nearest two, whatever the distance"); + SqlCapture.clear(); + SearchResults top2 = notes.searchTop2ByEmbeddingNear(Q, Score.of(2.0, ScoringFunction.cosine())); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, top2); + assertThat(top2.getContent()).hasSize(2); + + t.heading("5. searchByCountryAndEmbeddingWithin(country, Vector, Range)"); + SqlCapture.clear(); + SearchResults inCountry = notes.searchByCountryAndEmbeddingWithin("US", Q, + Range.closed(Similarity.of(0.5, ScoringFunction.cosine()), Similarity.of(1.0, ScoringFunction.cosine()))); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, inCountry); + + t.heading("6. An @Query that projects the distance as the second column"); + SqlCapture.clear(); + SearchResults annotated = notes.searchAnnotatedByCountry("US", Q); + t.sql("generated SQL", SqlCapture.last("from note")); + print(t, annotated); + assertThat(annotated.getContent().get(0).getContent().getText()).isEqualTo("Spring Boot actuator"); + t.write(); + } + + private static void print(Transcript t, SearchResults results) { + for (SearchResult r : results) { + t.line(String.format(Locale.ROOT, " score %-28s %s", r.getScore(), r.getContent().getText())); + } + if (!results.iterator().hasNext()) { + t.line(" (no rows)"); + } + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T05_HnswIndexTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T05_HnswIndexTest.java new file mode 100644 index 0000000..35eaac6 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T05_HnswIndexTest.java @@ -0,0 +1,185 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.persistence.EntityManager; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; +import org.hibernate.Session; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.support.TransactionTemplate; + +class T05_HnswIndexTest extends VectorTestBase { + + @Autowired + EntityManager em; + + @Autowired + TransactionTemplate tx; + + static final Path PG_LOG = Path.of(System.getProperty("pg.log", "/tmp/hibvec-pg/pg.log")); + static final float[] Q = ChunkData.queries(1).get(0); + + static final String COSINE_HQL = "select c.id from Chunk c order by cosine_distance(c.embedding, :q) limit 10"; + static final String L2_HQL = "select c.id from Chunk c order by euclidean_distance(c.embedding, :q) limit 10"; + static final String THRESHOLD_HQL = "select c.id from Chunk c where cosine_distance(c.embedding, :q) < 0.3"; + static final String SIMILARITY_HQL = "select c.id from Chunk c order by 1 - cosine_distance(c.embedding, :q) desc limit 10"; + + @Test + void hnswIndexAndPlans() throws Exception { + Transcript t = new Transcript("05-hnsw-explain", "HNSW index on 20,000 x 64-dimension rows: which Hibernate queries use it (auto_explain on the statements Hibernate really sent)", serverInfo()); + ChunkData.load(jdbc); + t.line("rows: " + jdbc.queryForObject("select count(*) from chunk", Integer.class) + ", dimensions: " + Chunk.DIMS + ", clusters: " + ChunkData.CLUSTERS); + + t.heading("1. No index yet: the nearest-neighbour query reads every row"); + String before = plan(() -> em.createQuery(COSINE_HQL, Long.class).setParameter("q", Q).getResultList()); + t.line(before); + assertThat(before).contains("Seq Scan on chunk").doesNotContain("Index Scan"); + + t.heading("2. Create the HNSW index (the schema generator cannot: see T08)"); + long start = System.nanoTime(); + ChunkData.createIndex(jdbc); + long ms = (System.nanoTime() - start) / 1_000_000; + t.line("sql/hnsw-index.sql: create index chunk_hnsw_cos on chunk using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64)"); + t.line("build time (indicative, this machine): " + ms + " ms"); + t.line("table size: " + jdbc.queryForObject("select pg_size_pretty(pg_table_size('chunk'))", String.class) + + ", HNSW index size: " + jdbc.queryForObject("select pg_size_pretty(pg_relation_size('chunk_hnsw_cos'))", String.class)); + t.line("indexdef: " + jdbc.queryForObject("select indexdef from pg_indexes where indexname = 'chunk_hnsw_cos'", String.class)); + + t.heading("3. Same HQL, now with the index: " + COSINE_HQL); + String cosine = plan(() -> em.createQuery(COSINE_HQL, Long.class).setParameter("q", Q).getResultList()); + t.line(cosine); + assertThat(cosine).contains("Index Scan using chunk_hnsw_cos on chunk"); + + t.heading("4. Trap: L2 distance against a cosine index: " + L2_HQL); + String l2 = plan(() -> em.createQuery(L2_HQL, Long.class).setParameter("q", Q).getResultList()); + t.line(l2); + assertThat(l2).contains("Seq Scan on chunk").doesNotContain("chunk_hnsw_cos"); + + t.heading("5. Trap: a distance threshold with no ORDER BY ... LIMIT: " + THRESHOLD_HQL); + String threshold = plan(() -> em.createQuery(THRESHOLD_HQL, Long.class).setParameter("q", Q).getResultList()); + t.line(threshold); + assertThat(threshold).contains("Seq Scan on chunk"); + + t.heading("6. Trap: ordering by a similarity expression instead of the distance: " + SIMILARITY_HQL); + String similarity = plan(() -> em.createQuery(SIMILARITY_HQL, Long.class).setParameter("q", Q).getResultList()); + t.line(similarity); + assertThat(similarity).contains("Seq Scan on chunk"); + + t.heading("7. The Criteria shape from T03 (distance in the select list, so Hibernate renders 'order by 2'): does the index still work?"); + String criteria = plan(() -> criteriaTop10()); + t.line(criteria); + assertThat(criteria).contains("chunk_hnsw_cos"); + + t.heading("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"); + String filtered = plan(() -> em.createQuery(T06_RecallTest.FILTERED, Long.class).setParameter("q", Q).getResultList()); + t.line(filtered); + assertThat(filtered).contains("chunk_hnsw_cos").contains("Filter: (category = 3)"); + + t.write(); + } + + @SuppressWarnings("unchecked") + private Object criteriaTop10() { + var cb = em.getCriteriaBuilder(); + var cq = cb.createQuery(Object[].class); + var c = cq.from(Chunk.class); + var nb = (org.hibernate.query.sqm.internal.SqmCriteriaNodeBuilder) cb; + jakarta.persistence.criteria.Expression q = nb.value(Q, (org.hibernate.query.sqm.tree.expression.SqmExpression) c.get("embedding")); + var distance = cb.function("cosine_distance", Double.class, c.get("embedding"), q); + cq.multiselect(c.get("id"), distance).orderBy(cb.asc(distance)); + return em.createQuery(cq).setMaxResults(10).getResultList(); + } + + /** + * Runs the query inside one transaction with auto_explain switched on for that connection, then returns the plan + * PostgreSQL logged for the statement Hibernate actually sent. Reads the server log; the server must be local. + */ + String plan(Supplier query) { + long offset = logLength(); + tx.executeWithoutResult(s -> { + em.unwrap(Session.class).doWork(conn -> { + try (var st = conn.createStatement()) { + st.execute("load 'auto_explain'"); + st.execute("set auto_explain.log_min_duration = 0"); + st.execute("set auto_explain.log_analyze = on"); + } + }); + query.get(); + }); + sleep(); + return extractPlan(readFrom(offset)); + } + + static long logLength() { + try { + return Files.size(PG_LOG); + } + catch (IOException e) { + throw new IllegalStateException("cannot read " + PG_LOG + " (set -Dpg.log=...)", e); + } + } + + static String readFrom(long offset) { + try (RandomAccessFile f = new RandomAccessFile(PG_LOG.toFile(), "r")) { + f.seek(offset); + byte[] b = new byte[(int) (f.length() - offset)]; + f.readFully(b); + return new String(b, StandardCharsets.UTF_8); + } + catch (IOException e) { + throw new IllegalStateException(e); + } + } + + static void sleep() { + try { + Thread.sleep(300); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** The plan block of the last "duration: ... plan:" entry that is a select on chunk, without the log prefix and the Query Text. */ + static String extractPlan(String log) { + List out = new ArrayList<>(); + boolean inPlan = false; + boolean isChunk = false; + List current = new ArrayList<>(); + List last = new ArrayList<>(); + for (String line : log.split("\n")) { + if (line.matches("^\\d{4}-\\d{2}-\\d{2} .*")) { + if (inPlan && isChunk) { + last = current; + } + inPlan = line.contains("plan:"); + isChunk = false; + current = new ArrayList<>(); + continue; + } + if (inPlan) { + if (line.contains("Query Text:")) { + isChunk = line.contains("from chunk"); + current.add("Query Text: " + line.substring(line.indexOf("Query Text:") + 11).strip()); + continue; + } + current.add(line.stripTrailing()); + } + } + if (inPlan && isChunk) { + last = current; + } + out.addAll(last); + // The 64-float query vector would fill the page: elide it, and drop the Query Parameters line. + return String.join("\n", out).strip().replaceAll("(?m)^\\tQuery Parameters:.*\\n", "") + .replaceAll("'\\[[-0-9.,eE]+\\]'::vector", "'[]'::vector").replaceAll("(?m)^\\t", ""); + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T06_RecallTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T06_RecallTest.java new file mode 100644 index 0000000..bd85ada --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T06_RecallTest.java @@ -0,0 +1,99 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.persistence.EntityManager; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.support.TransactionTemplate; + +/** Needs the chunk table and HNSW index that T05 builds, so it rebuilds them itself if they are missing. */ +class T06_RecallTest extends VectorTestBase { + + @Autowired + EntityManager em; + + @Autowired + TransactionTemplate tx; + + static final String TOP10 = "select c.id from Chunk c order by cosine_distance(c.embedding, :q) limit 10"; + static final String TOP100 = "select c.id from Chunk c order by cosine_distance(c.embedding, :q) limit 100"; + static final String FILTERED = "select c.id from Chunk c where c.category = 3 order by cosine_distance(c.embedding, :q) limit 10"; + + @Test + void recallAndEfSearch() { + ensureIndex(); + Transcript t = new Transcript("06-recall-ef-search", "HNSW is approximate: recall against exact search, hnsw.ef_search, LIMIT above ef_search, and filtered queries", serverInfo()); + List queries = ChunkData.queries(100); + t.line("100 query vectors, top 10 each, cosine distance, index chunk_hnsw_cos (m = 16, ef_construction = 64)"); + + t.heading("1. Recall@10 and latency by hnsw.ef_search (the default is 40)"); + List> exact = queries.stream().>map(q -> new HashSet<>(run(TOP10, q, "enable_indexscan", "off"))).toList(); + t.line(String.format(Locale.ROOT, "%-10s %-10s %-22s", "ef_search", "recall@10", "avg ms per query (indicative)")); + double recallAt10 = 0; + double recallAt200 = 0; + for (int ef : new int[] {10, 20, 40, 100, 200}) { + double recall = 0; + long start = System.nanoTime(); + for (int i = 0; i < queries.size(); i++) { + Set got = new HashSet<>(run(TOP10, queries.get(i), "hnsw.ef_search", String.valueOf(ef))); + got.retainAll(exact.get(i)); + recall += got.size() / 10.0; + } + double ms = (System.nanoTime() - start) / 1e6 / queries.size(); + recall /= queries.size(); + t.line(String.format(Locale.ROOT, "%-10d %-10.3f %-22.2f", ef, recall, ms)); + if (ef == 10) recallAt10 = recall; + if (ef == 200) recallAt200 = recall; + } + assertThat(recallAt200).isGreaterThanOrEqualTo(recallAt10); + + t.heading("2. LIMIT 100 with the default ef_search = 40"); + List hundred = run(TOP100, queries.get(0), "hnsw.ef_search", "40"); + t.line("rows requested: 100, rows returned: " + hundred.size()); + assertThat(hundred).hasSize(40); + List hundredWide = run(TOP100, queries.get(0), "hnsw.ef_search", "200"); + t.line("with hnsw.ef_search = 200: rows returned: " + hundredWide.size()); + assertThat(hundredWide).hasSize(100); + + t.heading("3. Filter plus nearest neighbour: where c.category = 3 (10% of the rows), LIMIT 10"); + int[] withoutIterative = new int[1]; + int[] withIterative = new int[1]; + double meanPlain = 0; + double meanIterative = 0; + for (float[] q : queries) { + meanPlain += run(FILTERED, q, "hnsw.ef_search", "40").size(); + meanIterative += run(FILTERED, q, "hnsw.iterative_scan", "relaxed_order").size(); + } + meanPlain /= queries.size(); + meanIterative /= queries.size(); + t.line(String.format(Locale.ROOT, "default settings: %.1f rows returned on average (10 asked for)", meanPlain)); + t.line(String.format(Locale.ROOT, "SET hnsw.iterative_scan = relaxed_order: %.1f rows returned on average", meanIterative)); + t.line("first query vector, default settings: " + run(FILTERED, queries.get(0), "hnsw.ef_search", "40").size() + " rows"); + assertThat(meanPlain).isLessThan(10.0); + assertThat(meanIterative).isEqualTo(10.0); + t.write(); + } + + /** Runs an HQL query in a transaction after setting one GUC for that transaction only (SET LOCAL semantics via set_config). */ + @SuppressWarnings("unchecked") + List run(String hql, float[] q, String guc, String value) { + return tx.execute(s -> { + em.createNativeQuery("select set_config(:k, :v, true)").setParameter("k", guc).setParameter("v", value).getSingleResult(); + return (List) em.createQuery(hql, Long.class).setParameter("q", q).getResultList(); + }); + } + + void ensureIndex() { + Integer rows = jdbc.queryForObject("select count(*) from chunk", Integer.class); + Integer idx = jdbc.queryForObject("select count(*) from pg_indexes where indexname = 'chunk_hnsw_cos'", Integer.class); + if (rows != ChunkData.ROWS || idx != 1) { + ChunkData.load(jdbc); + ChunkData.createIndex(jdbc); + } + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T07_SpringAiTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T07_SpringAiTest.java new file mode 100644 index 0000000..ee0a0e3 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T07_SpringAiTest.java @@ -0,0 +1,95 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.ai.document.Document; +import org.springframework.ai.vectorstore.SearchRequest; +import org.springframework.ai.vectorstore.pgvector.PgVectorStore; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +/** Spring AI's PgVectorStore on the same database, for comparison. Plain construction, no Spring context. */ +class T07_SpringAiTest { + + static final String URL = System.getProperty("pg.url", "jdbc:postgresql://127.0.0.1:55433/vec"); + + @Test + void pgVectorStoreForComparison() throws Exception { + SingleConnectionDataSource ds = new SingleConnectionDataSource(URL, "postgres", "", true); + JdbcTemplate jdbc = new JdbcTemplate(ds); + jdbc.execute("drop table if exists vector_store"); + String server = "PostgreSQL " + jdbc.queryForObject("select current_setting('server_version')", String.class).split(" ")[0] + + ", pgvector " + jdbc.queryForObject("select extversion from pg_extension where extname = 'vector'", String.class); + Transcript t = new Transcript("07-spring-ai", "Spring AI 2.1.0 PgVectorStore on the same database (hash-based stand-in embeddings, 32 dimensions)", server); + + PgVectorStore store = PgVectorStore.builder(jdbc, new HashingEmbeddingModel()) + .dimensions(HashingEmbeddingModel.DIMS) + .distanceType(PgVectorStore.PgDistanceType.COSINE_DISTANCE) + .indexType(PgVectorStore.PgIndexType.HNSW) + .initializeSchema(true) + .build(); + store.afterPropertiesSet(); + + t.heading("1. What the store created by itself"); + jdbc.query("select column_name, format_type(a.atttypid, a.atttypmod) as type from information_schema.columns c " + + "join pg_attribute a on a.attrelid = 'vector_store'::regclass and a.attname = c.column_name " + + "where table_name = 'vector_store' order by ordinal_position", + rs -> { t.line(String.format("%-10s %s", rs.getString(1), rs.getString(2))); }); + jdbc.query("select indexdef from pg_indexes where tablename = 'vector_store' order by indexname", rs -> { t.line(rs.getString(1)); }); + + store.add(List.of( + new Document("Hibernate maps float arrays to pgvector columns with hibernate-vector", Map.of("country", "IN")), + new Document("Spring Data JPA can run vector search methods that return SearchResults", Map.of("country", "IN")), + new Document("Sourdough starter needs flour water and patience", Map.of("country", "US")), + new Document("HNSW indexes in PostgreSQL trade recall for speed", Map.of("country", "US")))); + t.heading("2. similaritySearch(query = 'vector search with Hibernate and Spring Data', topK = 3)"); + List found = store.similaritySearch(SearchRequest.builder().query("vector search with Hibernate and Spring Data").topK(3).build()); + for (Document d : found) { + t.line(String.format(Locale.ROOT, " %.4f %s %s", d.getScore(), d.getMetadata().get("country"), d.getText())); + } + assertThat(found).hasSize(3); + + t.heading("3. The same search with filterExpression(\"country == 'US'\")"); + List us = store.similaritySearch(SearchRequest.builder().query("vector search with Hibernate and Spring Data").topK(3) + .filterExpression("country == 'US'").build()); + for (Document d : us) { + t.line(String.format(Locale.ROOT, " %.4f %s %s", d.getScore(), d.getMetadata().get("country"), d.getText())); + } + assertThat(us).hasSize(2); + + t.heading("4. The SQL PostgreSQL ran for the filtered search (auto_explain)"); + try (Connection c = DriverManager.getConnection(URL, "postgres", ""); Statement st = c.createStatement()) { + long offset = T05_HnswIndexTest.logLength(); + st.execute("load 'auto_explain'"); + st.execute("set auto_explain.log_min_duration = 0"); + // the same connection must run the search, so use a dedicated store on it + JdbcTemplate one = new JdbcTemplate(new SingleConnectionDataSource(c, true)); + PgVectorStore same = PgVectorStore.builder(one, new HashingEmbeddingModel()).dimensions(HashingEmbeddingModel.DIMS) + .distanceType(PgVectorStore.PgDistanceType.COSINE_DISTANCE).indexType(PgVectorStore.PgIndexType.HNSW).initializeSchema(false).build(); + same.similaritySearch(SearchRequest.builder().query("vector search").topK(3).filterExpression("country == 'US'").build()); + T05_HnswIndexTest.sleep(); + String log = T05_HnswIndexTest.readFrom(offset); + String sql = extractQueryText(log, "vector_store"); + t.line(sql); + assertThat(sql).contains("<=>").contains("vector_store"); + } + t.write(); + } + + static String extractQueryText(String log, String table) { + for (String line : log.split("\n")) { + int i = line.indexOf("Query Text:"); + if (i >= 0 && line.contains(table)) { + return line.substring(i + 11).strip(); + } + } + return "(not found)"; + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/T08_SchemaGenerationFailureTest.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/T08_SchemaGenerationFailureTest.java new file mode 100644 index 0000000..9d00a98 --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/T08_SchemaGenerationFailureTest.java @@ -0,0 +1,72 @@ +package com.ankurm.hibvector; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.ankurm.broken.BrokenIndexed; +import com.ankurm.broken.BrokenNote; +import java.util.Map; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** Two things that do not work in Hibernate 7.4.17, each bootstrapped by hand so the failure is the whole story. */ +class T08_SchemaGenerationFailureTest { + + static final String URL = System.getProperty("pg.url", "jdbc:postgresql://127.0.0.1:55433/vec"); + + @Test + void whatDoesNotWork() { + JdbcTemplate jdbc = new JdbcTemplate(new DriverManagerDataSource(URL, "postgres", "")); + String server = "PostgreSQL " + jdbc.queryForObject("select current_setting('server_version')", String.class).split(" ")[0] + + ", pgvector " + jdbc.queryForObject("select extversion from pg_extension where extname = 'vector'", String.class); + Transcript t = new Transcript("08-failures", "Two failures: Spring Data's Vector as an entity attribute, and an HNSW index from @Index", server); + + t.heading("1. @JdbcTypeCode(SqlTypes.VECTOR) @Array(length = 4) Vector embedding (org.springframework.data.domain.Vector)"); + String first = bootstrap(BrokenNote.class, "none"); + t.line(first); + assertThat(first).contains("UnknownBasicJavaType"); + + t.heading("2. @Table(indexes = @Index(columnList = \"embedding vector_cosine_ops\")) with hbm2ddl create"); + jdbc.execute("drop table if exists broken_indexed"); + String second = bootstrap(BrokenIndexed.class, "create"); + t.line(second); + t.line("index created: " + jdbc.queryForObject("select count(*) from pg_indexes where indexname = 'broken_idx'", Integer.class)); + jdbc.execute("drop table if exists broken_indexed"); + t.write(); + } + + static String bootstrap(Class entity, String hbm2ddl) { + var registry = new StandardServiceRegistryBuilder() + .applySettings(Map.of( + "jakarta.persistence.jdbc.url", URL, + "jakarta.persistence.jdbc.user", "postgres", + "jakarta.persistence.jdbc.password", "", + "hibernate.hbm2ddl.auto", hbm2ddl, + "hibernate.hbm2ddl.halt_on_error", "true")) + .build(); + try { + SessionFactory sf = new MetadataSources(registry).addAnnotatedClass(entity).buildMetadata().buildSessionFactory(); + sf.close(); + return "bootstrapped without error"; + } + catch (RuntimeException e) { + Throwable root = e; + StringBuilder sb = new StringBuilder(e.getClass().getSimpleName() + ": " + first(e.getMessage())); + while (root.getCause() != null && root.getCause() != root) { + root = root.getCause(); + sb.append("\n caused by ").append(root.getClass().getSimpleName()).append(": ").append(first(root.getMessage())); + } + return sb.toString(); + } + finally { + StandardServiceRegistryBuilder.destroy(registry); + } + } + + static String first(String m) { + return m == null ? "" : m.split("\n")[0]; + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/Transcript.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/Transcript.java new file mode 100644 index 0000000..cbb18cf --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/Transcript.java @@ -0,0 +1,48 @@ +package com.ankurm.hibvector; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Collects what a test observed and writes output/NN-name.txt; the tests assert the same facts. */ +final class Transcript { + + private final List lines = new ArrayList<>(); + private final Path file; + + Transcript(String name, String title, String serverInfo) { + this.file = Path.of("output", name + ".txt"); + line("# " + title); + line("# Hibernate ORM " + System.getProperty("h.version", "?") + " (on the classpath), " + serverInfo + ", JDK " + Runtime.version().feature()); + } + + Transcript line(String s) { + lines.add(s); + return this; + } + + Transcript heading(String s) { + line(""); + return line("== " + s); + } + + Transcript sql(String label, String sql) { + line("-- " + label); + for (String l : sql.strip().split("\n")) { + line(" " + l.stripTrailing()); + } + return this; + } + + void write() { + try { + Files.createDirectories(file.getParent()); + Files.write(file, lines); + } + catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/hibernate-vector/src/test/java/com/ankurm/hibvector/VectorTestBase.java b/hibernate-vector/src/test/java/com/ankurm/hibvector/VectorTestBase.java new file mode 100644 index 0000000..67a137d --- /dev/null +++ b/hibernate-vector/src/test/java/com/ankurm/hibvector/VectorTestBase.java @@ -0,0 +1,46 @@ +package com.ankurm.hibvector; + +import java.util.List; +import javax.sql.DataSource; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; + +@SpringBootTest(properties = "spring.jpa.properties.hibernate.session_factory.statement_inspector=com.ankurm.hibvector.SqlCapture") +abstract class VectorTestBase { + + @Autowired + protected DataSource dataSource; + + @Autowired + protected DocRepository docs; + + protected JdbcTemplate jdbc; + + @BeforeEach + void baseSetUp() { + jdbc = new JdbcTemplate(dataSource); + SqlCapture.clear(); + } + + /** "PostgreSQL 16.15, pgvector 0.8.7" for the transcript header. */ + protected String serverInfo() { + String v = jdbc.queryForObject("select current_setting('server_version')", String.class); + String ext = jdbc.queryForObject("select extversion from pg_extension where extname = 'vector'", String.class); + return "PostgreSQL " + v.split(" ")[0] + ", pgvector " + ext; + } + + /** The four hand-made axes: java, databases, cooking, finance. */ + protected void seedDocs() { + docs.deleteAll(); + docs.saveAll(List.of( + new Doc("Hibernate batch inserts", "tech", 0.7f, 0.7f, 0f, 0f), + new Doc("Spring Data repositories", "tech", 0.9f, 0.4f, 0f, 0f), + new Doc("Postgres index tuning", "tech", 0.1f, 0.95f, 0f, 0.1f), + new Doc("Sourdough starter basics", "food", 0f, 0f, 1f, 0f), + new Doc("Cast iron pan care", "food", 0f, 0f, 0.9f, 0f), + new Doc("Index funds for engineers", "finance", 0.1f, 0.1f, 0f, 0.95f), + new Doc("Hibernate batch inserts, long edition (same direction, 10x the length)", "tech", 7f, 7f, 0f, 0f))); + } +} diff --git a/hibernate-vector/xx/META-INF/LICENSE.txt b/hibernate-vector/xx/META-INF/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/hibernate-vector/xx/META-INF/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/hibernate-vector/xx/META-INF/MANIFEST.MF b/hibernate-vector/xx/META-INF/MANIFEST.MF new file mode 100644 index 0000000..f977237 --- /dev/null +++ b/hibernate-vector/xx/META-INF/MANIFEST.MF @@ -0,0 +1,63 @@ +Manifest-Version: 1.0 +Automatic-Module-Name: org.hibernate.orm.vector +Bundle-DocURL: https://hibernate.org/orm/releases/7.4 +Bundle-ManifestVersion: 2 +Bundle-Name: hibernate-vector +Bundle-SymbolicName: org.hibernate.orm.vector +Bundle-Vendor: Hibernate.org +Bundle-Version: 7.4.17.Final +Export-Package: org.hibernate.vector;version="7.4.17.Final",org.hibern + ate.vector.internal;version="7.4.17.Final";uses:="org.hibernate.boot. + model,org.hibernate.dialect,org.hibernate.engine.jdbc,org.hibernate.m + etamodel.mapping,org.hibernate.metamodel.model.domain,org.hibernate.q + uery.sqm.function,org.hibernate.query.sqm.produce.function,org.hibern + ate.query.sqm.produce.function.internal,org.hibernate.query.sqm.sql,o + rg.hibernate.query.sqm.tree,org.hibernate.service,org.hibernate.sql.a + st,org.hibernate.sql.ast.spi,org.hibernate.sql.ast.tree,org.hibernate + .sql.ast.tree.expression,org.hibernate.tool.schema.extract.spi,org.hi + bernate.type,org.hibernate.type.descriptor,org.hibernate.type.descrip + tor.java,org.hibernate.type.descriptor.jdbc,org.hibernate.type.descri + ptor.jdbc.spi,org.hibernate.type.descriptor.sql.internal,org.hibernat + e.type.spi,org.hibernate.vector" +Hibernate-JpaVersion: 3.2 +Hibernate-VersionFamily: 7.4 +Implementation-Title: hibernate-vector +Implementation-Url: https://hibernate.org/orm +Implementation-Vendor: Hibernate.org +Implementation-Vendor-Id: org.hibernate +Implementation-Version: 7.4.17.Final +Import-Package: java.lang,java.lang.invoke,java.lang.reflect,java.lang + .runtime,java.math,java.nio.charset,java.sql,java.util,java.util.func + tion,microsoft.sql;version="[13.2,14)",oracle.sql,org.hibernate;versi + on="[7.4,8)",org.hibernate.boot.model;version="[7.4,8)",org.hibernate + .boot.registry.classloading.spi;version="[7.4,8)",org.hibernate.diale + ct;version="[7.4,8)",org.hibernate.engine.jdbc;version="[7.4,8)",org. + hibernate.engine.jdbc.spi;version="[7.4,8)",org.hibernate.engine.spi; + version="[7.4,8)",org.hibernate.internal.util.collections;version="[7 + .4,8)",org.hibernate.metamodel.mapping;version="[7.4,8)",org.hibernat + e.metamodel.model.domain;version="[7.4,8)",org.hibernate.query.sqm;ve + rsion="[7.4,8)",org.hibernate.query.sqm.function;version="[7.4,8)",or + g.hibernate.query.sqm.produce.function;version="[7.4,8)",org.hibernat + e.query.sqm.produce.function.internal;version="[7.4,8)",org.hibernate + .query.sqm.sql;version="[7.4,8)",org.hibernate.query.sqm.tree;version + ="[7.4,8)",org.hibernate.query.sqm.tree.domain;version="[7.4,8)",org. + hibernate.query.sqm.tree.expression;version="[7.4,8)",org.hibernate.s + ervice;version="[7.4,8)",org.hibernate.sql.ast;version="[7.4,8)",org. + hibernate.sql.ast.spi;version="[7.4,8)",org.hibernate.sql.ast.tree;ve + rsion="[7.4,8)",org.hibernate.sql.ast.tree.expression;version="[7.4,8 + )",org.hibernate.tool.schema.extract.spi;version="[7.4,8)",org.hibern + ate.type;version="[7.4,8)",org.hibernate.type.descriptor;version="[7. + 4,8)",org.hibernate.type.descriptor.converter.spi;version="[7.4,8)",o + rg.hibernate.type.descriptor.java;version="[7.4,8)",org.hibernate.typ + e.descriptor.java.spi;version="[7.4,8)",org.hibernate.type.descriptor + .jdbc;version="[7.4,8)",org.hibernate.type.descriptor.jdbc.spi;versio + n="[7.4,8)",org.hibernate.type.descriptor.sql;version="[7.4,8)",org.h + ibernate.type.descriptor.sql.internal;version="[7.4,8)",org.hibernate + .type.descriptor.sql.spi;version="[7.4,8)",org.hibernate.type.spi;ver + sion="[7.4,8)",org.hibernate.vector;version="[7.4,8)",javax.transacti + on;version="[1.1,2)" +Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=17))" +Specification-Title: hibernate-vector +Specification-Vendor: Hibernate.org +Specification-Version: 7.4.17.Final + diff --git a/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.FunctionContributor b/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.FunctionContributor new file mode 100644 index 0000000..bf3db90 --- /dev/null +++ b/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.FunctionContributor @@ -0,0 +1,8 @@ +org.hibernate.vector.internal.PGVectorFunctionContributor +org.hibernate.vector.internal.OracleVectorFunctionContributor +org.hibernate.vector.internal.MariaDBFunctionContributor +org.hibernate.vector.internal.MySQLFunctionContributor +org.hibernate.vector.internal.DB2VectorFunctionContributor +org.hibernate.vector.internal.CockroachFunctionContributor +org.hibernate.vector.internal.HANAVectorFunctionContributor +org.hibernate.vector.internal.SQLServerVectorFunctionContributor \ No newline at end of file diff --git a/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.TypeContributor b/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.TypeContributor new file mode 100644 index 0000000..ea1206d --- /dev/null +++ b/hibernate-vector/xx/META-INF/services/org.hibernate.boot.model.TypeContributor @@ -0,0 +1,8 @@ +org.hibernate.vector.internal.PGVectorTypeContributor +org.hibernate.vector.internal.OracleVectorTypeContributor +org.hibernate.vector.internal.MariaDBTypeContributor +org.hibernate.vector.internal.MySQLTypeContributor +org.hibernate.vector.internal.DB2VectorTypeContributor +org.hibernate.vector.internal.CockroachTypeContributor +org.hibernate.vector.internal.HANAVectorTypeContributor +org.hibernate.vector.internal.SQLServerTypeContributor \ No newline at end of file