Skip to main content

Hibernate Vector Module: pgvector Similarity Search in HQL and Spring Data JPA

Map float[] embeddings with hibernate-vector 7.4.17, run cosine and L2 similarity search in HQL, Criteria and Spring Data JPA 4.2 on pgvector 0.8.7, prove with auto_explain when the HNSW index is used, and see four ways it silently is not. Includes recall vs ef_search measurements and a comparison with Spring AI PgVectorStore. Every output is from a committed test transcript.

You already store your product descriptions, support tickets or documentation chunks in PostgreSQL, and you already read and write them with Hibernate. Now you have computed an embedding for each one — a list of a few hundred floating-point numbers that a model produced — and you want one thing: given this new text, give me the ten rows whose meaning is closest. You do not want a second database for it, and you would like the answer to come back as ordinary entities.

Hibernate 7 has a module for exactly this, hibernate-vector, and Spring Data JPA 4.2 adds repository methods on top of it. This post is what happens when you actually use them against PostgreSQL with the pgvector extension: how to map the column, how to ask for nearest neighbours in HQL, Criteria and Spring Data, how to add an HNSW index, how to prove with EXPLAIN that your Hibernate query really uses it, and the handful of ways it silently stops. It ends with an honest comparison to Spring AI’s VectorStore, which solves the same problem from the other side.

Everything below was compiled and run. The companion module has eight tests; each writes a transcript to its output/ folder and every console block in this post is copied from one of those files. Where I could not run something, the post says so.

Versions this was run against. Hibernate ORM and hibernate-vector 7.4.17.Final (on Maven Central 2026-11-19; Spring Boot 4.2.0 manages 7.4.15.Final, so the module overrides it), Spring Boot 4.2.0 (Maven Central 2026-11-19) with Spring Data JPA 4.2.0, PostgreSQL 16.15 with pgvector 0.8.7 (released 2026-10-01, built from its git tag), PostgreSQL JDBC driver 42.7.14, Spring AI 2.1.0 (test scope, for the comparison only), JDK 25.0.5+2. No Docker in my sandbox, so PostgreSQL came from Ubuntu’s packages and pgvector was compiled from source by scripts/start-postgres.sh. Version facts were read from maven-metadata.xml, the Spring Boot BOM and pgvector’s own CHANGELOG, not from announcement posts.

1. An embedding is a point, and “similar” means “close”

An embedding model turns a piece of text into a list of numbers, say 384 or 1,536 of them. Think of that list as the coordinates of a point in a space with that many dimensions. The model is trained so that texts about similar things land near each other. “Find similar documents” therefore becomes “find the points nearest to this one”, and a database that can store the points and sort rows by distance can answer it.

To keep the numbers checkable by eye, the first examples in this post use four hand-picked dimensions instead of a real model: how much a text is about java, databases, cooking and finance. They are not real embeddings and the post never pretends otherwise. The mechanics — storage, distance functions, indexes — are identical at 4 dimensions and at 1,536.

“Close” has more than one meaning, and the choice matters. Cosine distance compares the direction of two vectors and ignores their length. L2 (Euclidean) distance is the straight-line distance between the two points, so length counts. The diagram has one document, “Hibernate batch inserts”, and a second copy of it that is ten times longer but points the same way (think of a long article that repeats the same topic). Cosine cannot tell them apart; L2 puts them 8.8 units apart.

Same direction, different length: cosine says identical, L2 says far apartjavadatabasesquerySpring Data repositoriesHibernate batch insertssame direction, 10x longer(continues off the chart)Cosine distance to the query (angle only)Hibernate batch inserts 0.0513… 10x long edition 0.0513Both rank in the top 3.L2 distance to the query (length matters)Hibernate batch inserts 0.3606… 10x long edition 8.8459The long edition drops to rank 7 of 7.

The picture’s argument is the one to carry through the rest of the post: the distance function is part of the meaning of your search, and later it will also decide whether your index is used at all. The numbers in the diagram come from output/02-hql-distance.txt (section 4 of that transcript).

Going deeper: normalised vectors, and which distance to pick

Many embedding models return vectors already scaled to length 1. For those, cosine distance and L2 distance give the same ranking, and the inner product is a cheaper way to compute it. The model’s documentation says which it produces; if it says “normalised”, you can use any of the three and should pick the one your index supports. If it does not, cosine is the safe default, because it does not care about length. I did not run a real embedding model for this post, so I cannot show you a model’s own output.

  • The four-dimension data and the exact vectors are in VectorTestBase.java (seedDocs).
  • pgvector README: the distance operators and which index operator class each one needs.

2. Map the column: a float[] and two annotations

The dependency is one extra artifact next to Hibernate. In a Spring Boot project the version is managed by the Boot BOM; this module pins it to the newest patch release so the post tests what is current.

<dependency>
  <groupId>org.hibernate.orm</groupId>
  <artifactId>hibernate-vector</artifactId>
</dependency>

That snippet is the dependency as it appears in pom.xml (the version comes from the hibernate.version property there). The entity is plain JPA plus two Hibernate annotations on a float[]:

@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;

This is Doc.java. @JdbcTypeCode(SqlTypes.VECTOR) says “this is a vector, not a generic array”, and @Array(length = 4) is the number of dimensions. Hibernate turns that into a vector(4) column, and writes the parameter with a cast. Both are visible in the transcript output/01-mapping.txt:

== 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]

Two things in that output are worth noticing before moving on. The read-back float[] equals what you stored, so the round trip is lossless at the default vector precision (32-bit floats). And Hibernate’s dirty checking works on the array contents: in the same transcript, changing one element of a loaded array inside a transaction produced an update doc set ... embedding=cast(? as vector) ... at commit, with no explicit save call.

The dimension is checked by the database, not by Hibernate. Saving a three-element array into a vector(4) column did not fail in Java; PostgreSQL rejected it: DataIntegrityViolationException -> PSQLException: ERROR: expected 4 dimensions, not 3 (same transcript). If you change the embedding model you change the dimension, and the column, the @Array(length) and every stored vector have to change together. A second trap from the same file: the cosine distance to the all-zero vector is NaN, not an error, so a model that can return a zero vector for empty text will poison your ordering silently.
Going deeper: half precision, other element types, other databases

The same float[] can be stored at half precision by switching the type code to SqlTypes.VECTOR_FLOAT16, which maps to pgvector’s halfvec. In the run, half_doc.embedding came back as halfvec(4) and the values 0.1, 0.2, 0.3, 0.7 were stored and read back as [0.099975586, 0.19995117, 0.30004883, 0.7001953]: half the storage, and visible rounding. pgvector’s README says a vector column can be indexed up to 2,000 dimensions and halfvec up to 4,000, which is why half precision matters for large models.

Looking inside the 7.4.17 hibernate-vector jar shows more than PostgreSQL: it contains function and type contributors for Oracle, DB2, SAP HANA, MariaDB, MySQL, SQL Server and CockroachDB, and SqlTypes has VECTOR_INT8, VECTOR_FLOAT32, VECTOR_FLOAT64 and VECTOR_BINARY beside VECTOR_FLOAT16. I only ran PostgreSQL with vector and halfvec; I did not run the others.

3. Ask for the nearest rows in HQL

With the column mapped, similarity search is an ORDER BY on a distance function. Hibernate registers the functions as HQL functions, so you write them like any other. This repository method returns the three nearest documents by cosine distance, together with the distance, in a small record:

@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<Hit> hitsByCosine(@Param("q") float[] q, @Param("n") int n);

This is from DocRepository.java. The parameter q is a plain float[]. Hibernate sends the following SQL, and the first three rows are what came back for the query vector [1, 0.5, 0, 0] (“java persistence”). Both blocks are from output/02-hql-distance.txt:

== 1. cosine_distance: the nearest three
   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

The HQL function cosine_distance became pgvector’s <=> operator; fetch first ? rows only is the limit. That exact shape — order by (column <=> vector) ... limit k — is what an index can accelerate later, so it is worth recognising now. The table lists the functions the 7.4.17 jar registers and what they become on PostgreSQL (names read from the jar, SQL from the transcript):

HQL functionSQL on PostgreSQLMeaning
cosine_distance(a, b)a <=> b1 minus cosine similarity; direction only
euclidean_distance(a, b) (alias l2_distance)a <-> bstraight-line distance
euclidean_squared_distance(a, b)(a <-> b)^2L2 squared
l1_distance(a, b) (alias taxicab_distance)l1_distance(a, b)sum of absolute differences
inner_product(a, b)(a <#> b) * -1the dot product, larger is closer
negative_inner_product(a, b)a <#> bwhat pgvector sorts by
vector_dims(a), vector_norm(a)same namesnumber of dimensions, length of the vector
hamming_distance, jaccard_distance<~>, <%>for binary vectors (VECTOR_BINARY), not run here

Now the surprise the first diagram promised. The same query with euclidean_distance ranks differently, because the “long edition” document is far away in L2 terms even though it points the same way:

== 3. Where the 10x-long document lands
cosine  rank of the long edition: 2
euclid. rank of the long edition: 7

Source: output/02-hql-distance.txt

Rank 2 under cosine, rank 7 of 7 under L2, from the same seven rows. If your embeddings are not normalised, picking the wrong function does not give an error — it gives a plausible-looking list in the wrong order.

Two rows tie, and ORDER BY does not say who goes first. “Hibernate batch inserts” and its long edition both have cosine distance 0.0513, so their order in the output (02-hql-distance.txt, section 1) is whatever PostgreSQL produced that time. A test that compared two result lists in order failed intermittently while I was writing this module for exactly that reason. If your application needs a stable order, add a tie-breaker such as , d.id.
Reference: every function on one row, thresholds and filters

The transcript runs all of the functions in a single query on the two “Hibernate batch inserts” rows. Read the table by columns: cosine is identical for both, every length-sensitive column differs by a factor of about ten, and the norm column confirms the length (0.9899 against 9.8995):

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

Two more patterns that appear in real code. A distance threshold goes in the where clause (where cosine_distance(d.embedding, :q) < :max, section 5 of the transcript), and a category filter sits next to the ordering (section 6: where d1_0.category=? order by (d1_0.embedding<=>cast(? as vector)) fetch first ? rows only). Both are fine on a four-row table. Section 7 shows what the threshold form does to an index.

4. Criteria works, but never pass the vector as a literal

The Criteria API has no vector-specific methods, so the distance function is called by name with cb.function. That works, and produces the same SQL as HQL apart from one cosmetic difference: when the distance is also in the select list, Hibernate renders the ordering as order by 2, a column position.

CriteriaQuery<Hit> cq = cb.createQuery(Hit.class);
Root<Doc> d = cq.from(Doc.class);
ParameterExpression<float[]> q = cb.parameter(float[].class, "q");
Expression<Double> 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));

From T03_CriteriaTest.java. The transcript output/03-criteria.txt shows the SQL and the same three rows as the HQL version:

== 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

Here is the trap. The natural first attempt is cb.literal(queryVector), and Hibernate rejects it, because a literal float[] is typed as a generic array rather than a vector. What surprised me is the aftermath: once that rejection has happened, cb.parameter(float[].class) is rejected too, in the same SessionFactory, even though the parameter had worked a moment earlier. I did not trace the cause; the order-dependence is reproducible, and the transcript shows it from both starting points:

== 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[]'

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[]'

The way out that worked in every run is an internal Hibernate method that takes the value together with an expression whose type it should borrow. It lives in an internal package, which is a real cost, so my advice is: write vector queries in HQL, and treat Criteria as the fallback.

SqmCriteriaNodeBuilder nb = (SqmCriteriaNodeBuilder) cb;
CriteriaQuery<Double> c1 = cb.createQuery(Double.class);
Root<Doc> d1 = c1.from(Doc.class);
Expression<float[]> typed = nb.value(T02_HqlTest.QUERY, (SqmExpression<float[]>) d1.<float[]>get("embedding"));
Expression<Double> dist1 = cb.function("cosine_distance", Double.class, d1.get("embedding"), typed);
c1.select(dist1).orderBy(cb.asc(dist1));

Source: T03_CriteriaTest.java

== 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
Going deeper: why not a typed metamodel, and what Spring Data does

I used string function names, so there is no compile-time check on "cosine_distance"; a typo fails when the query is built, not when the project compiles. The JPA metamodel would type the attribute path but cannot type a function name. Spring Data JPA 4.2 builds its own derived vector queries with Criteria internally; those are the repository methods in the next section, and they ran fine, so the internal rejection above is about how you call cb.function yourself.

  • T03_CriteriaTest.java: both starting points, each in its own application context so one cannot contaminate the other.
  • HQL alternative for dynamic queries: build the HQL string and bind :q as in section 3.

5. Spring Data JPA: a @Query you can rely on, and new methods you can try

There are two ways to run this from a Spring Data repository, and they differ in how much you trust the framework.

The dependable way is a @Query with the same HQL as before on an ordinary JpaRepository. It returns entities, it works on every Spring Data version, and the SQL is exactly what you wrote:

/** 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<Doc> nearestByCosine(@Param("q") float[] q, @Param("n") int n);

This is the first method in DocRepository.java. In output/04-spring-data.txt it produced:

== 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)

The newer way is Spring Data JPA 4.2’s vector-search support: repository methods that return SearchResults<T>, where each SearchResult carries the entity and a Score. The method names use Near or Within, and you pass a Vector and a score limit. The repository, from NoteRepository.java:

SearchResults<Note> searchByEmbeddingNear(Vector vector, ScoringFunction function);

SearchResults<Note> searchByEmbeddingNear(Vector vector, Score score);

SearchResults<Note> searchByEmbeddingNear(Vector vector, Similarity similarity);

/** Top-K: the Top keyword adds the LIMIT that the plain Near methods lack. */
SearchResults<Note> searchTop2ByEmbeddingNear(Vector vector, Score score);

SearchResults<Note> searchByCountryAndEmbeddingWithin(String country, Vector vector, Range<Similarity> range);

@Query("""
        select n, cosine_distance(n.embedding, :embedding) as distance from Note n
        where n.country = :country
        order by distance asc""")
SearchResults<Note> searchAnnotatedByCountry(String country, Vector embedding);

Running it against five notes with the same four-axis vectors gave the output below. Look at the score column: with a Score argument it is a distance (smaller is closer), with a Similarity argument it is a normalised similarity (larger is closer). In these runs the cosine similarity was 1 minus half the distance: the nearest note has distance 0.00103 in the first block and similarity 0.99948 in the second. The Top2 variant adds the fetch first ? rows only that the plain Near methods do not have.

== 2b. The same method with a Score that accepts everything (distance at most 2)
   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

Source: output/04-spring-data.txt

== 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

Source: output/04-spring-data.txt

Two things from the Spring Data reference page did not hold in my runs, and both cost me a failed test, so they go in a callout rather than a footnote:

The documented examples that failed on Spring Data JPA 4.2.0 + Hibernate 7.4.17.

1. searchByEmbeddingNear(Vector, ScoringFunction), the first form the reference page lists, threw InvalidDataAccessApiUsageException: Near/Within keywords must be used with a Score or Range<Score> type when called (04-spring-data.txt, section 2). Passing a Score works. Wrap the scoring function in Score.of(2.0, ScoringFunction.cosine()) if you want everything.

2. The page shows an entity attribute of type Vector. Hibernate 7.4.17 cannot start with that mapping: ClassCastException: ... UnknownBasicJavaType cannot be cast to ... BasicPluralJavaType (output/08-failures.txt, section 1). The entity in this module keeps a float[] and only the repository method parameter is a Vector. The reference page itself notes that Vector cannot be used in the domain model; its example contradicts that.
Going deeper: Score versus Similarity, and when to prefer which style

Use the @Query style when you need the nearest k rows of an entity, a join, a projection, or control over the SQL; it is the form I would put in production today, and the only one whose plan I verified on an index (section 7 runs it through EntityManager, which is the same SQL). Use SearchResults when you want the score returned with the entity without writing the projection, and when a distance or similarity threshold is the question. Note from the generated SQL in the transcript: the derived methods filter with (embedding<=>cast(? as vector))<=? and sort by column position, and only the Top variant limits the row count. I did not put an HNSW index under the derived methods, so I make no claim about their plans.

6. Without an index, every query reads every row

Everything so far sorted a handful of rows. On 20,000 rows of 64 dimensions the same query shape has to compute a distance for every row and keep the best ten. The next block is PostgreSQL’s own plan for the statement Hibernate sent, captured with the auto_explain module, so it is the real query and not a lookalike I typed into psql (the 64-number query vector is shown as <query vector>). From output/05-hnsw-explain.txt:

Query Text: select c1_0.id from chunk c1_0 order by (c1_0.embedding<=>cast($1 as vector)) fetch first 10 rows only
Limit  (cost=1452.19..1452.22 rows=10 width=16) (actual time=5.744..5.747 rows=10 loops=1)
  ->  Sort  (cost=1452.19..1502.19 rows=20000 width=16) (actual time=5.742..5.744 rows=10 loops=1)
        Sort Key: ((embedding <=> '[<query vector>]'::vector))
        Sort Method: top-N heapsort  Memory: 25kB
        ->  Seq Scan on chunk c1_0  (cost=0.00..1020.00 rows=20000 width=16) (actual time=0.006..3.997 rows=20000 loops=1)

The key line is Seq Scan on chunk reading rows=20000. That is fine at this size; it stops being fine as the table grows, because the cost is linear in rows. An approximate nearest-neighbour index trades a little accuracy for not reading most of them. pgvector’s HNSW index (Hierarchical Navigable Small World, from a 2016 paper) is a stack of graphs: the top layer has few nodes and long hops, the bottom layer has every row. A search enters at the top, hops to whichever neighbour is closer to the query, drops a layer, and repeats.

HNSW: walk down a stack of graphs instead of reading every rowtop layer: few nodes, long hopsmiddle layerbottom layer: every rowqueryOn the bottom layer the walk keeps a list of the best candidates it has seen. The size of that list is hnsw.ef_search (40 by default).Rows are returned from that list, so it caps both recall and how many rows a LIMIT can ever get back.Measured on 20,000 rows: a sequential scan reads all 20,000; the index scan above read the graph and returned 10 rows (section 6 and 7).

The diagram carries one idea to remember: the walk ends with a list of candidates, and rows come from that list. The size of the list is a setting, hnsw.ef_search, and section 8 measures what it does. First, building the index. Hibernate’s schema generator cannot create it (the transcript output/08-failures.txt shows @Index(columnList = "embedding vector_cosine_ops") producing ERROR: column "embedding vector_cosine_ops" does not exist, because JPA’s @Index has no place for using hnsw), so it goes in a migration. The module keeps it in hnsw-index.sql:

create index chunk_hnsw_cos on chunk using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64);

On this machine the build took about 4 seconds (indicative; machines vary) and the index is larger than the table it indexes. With it in place, the same HQL from the test produces this plan:

build time (indicative, this machine): 4044 ms
table size: 6192 kB, HNSW index size: 11 MB
Query Text: select c1_0.id from chunk c1_0 order by (c1_0.embedding<=>cast($1 as vector)) fetch first 10 rows only
Limit  (cost=167.05..171.49 rows=10 width=16) (actual time=1.037..1.052 rows=10 loops=1)
  ->  Index Scan using chunk_hnsw_cos on chunk c1_0  (cost=167.05..9048.00 rows=20000 width=16) (actual time=1.036..1.050 rows=10 loops=1)
        Order By: (embedding <=> '[<query vector>]'::vector)

Index Scan using chunk_hnsw_cos, ten rows, with the Hibernate-bound $1 parameter. The plan comparison is the thing to check in your own project: the index existing is not the same as the index being used. The next section is about the ways that silently fails.

Going deeper: build parameters and what they cost

m (connections per node, default 16) and ef_construction (candidate list while building, default 64) are the two build-time knobs; larger values give better recall and a slower, bigger index, according to the pgvector README. I used the defaults on 20,000 rows and did not sweep them. The README also says builds are much faster when the graph fits in maintenance_work_mem; at this size that was not a concern, and I did not test large builds. The cross-store post on this blog measured pgvector’s defaults against other vector stores at 30,000 documents.

7. Four ways your Hibernate query quietly stops using the index

Each of these returned correct rows in my runs. That is what makes them dangerous: nothing fails, the query just gets slow as the table grows. The flow chart summarises what the planner checks, and the transcript has the plan for every box.

What the planner checks before it will use the HNSW indexHQLcosine_distance(c.embedding, :q)SQLembedding <=> cast(? as vector)Index scan only if all three hold:1. ORDER BY exactly (embedding op vector)2. op matches the index opclass (<=> = vector_cosine_ops)3. there is a LIMITYes: Index Scan using chunk_hnsw_coscosine_distance … order by … limit 10Criteria shape with “order by 2” (section 7, step 7)Parameter bound as $1: still planned with the indexNo: Seq Scan on chunk (20,000 rows read)euclidean_distance order against a cosine index (step 4: the operator is <->, the index is <=>)where cosine_distance(..) < 0.3, no order, no limit (step 5: 7 rows kept, 19,993 filtered out)order by 1 – cosine_distance(..) desc (step 6: the sort key is no longer the operator)Index used, but filtered after the scanwhere c.category = 3 order by … limit 10plan: Filter: (category = 3), Rows Removed by Filter: 34returned 6 of the 10 rows asked for (step 8)

The chart says what to conclude: three conditions, all must hold, and a filter is a fourth thing to watch rather than a failure. Here are the four, with the plan line that gives each away. All are from output/05-hnsw-explain.txt.

1. The wrong distance for the index. The index was built with vector_cosine_ops, which serves <=>. An HQL euclidean_distance becomes <->, which the index cannot serve:

== 4. Trap: L2 distance against a cosine index: select c.id from Chunk c order by euclidean_distance(c.embedding, :q) limit 10
Limit  (cost=1452.19..1452.22 rows=10 width=16) (actual time=5.240..5.243 rows=10 loops=1)
  ->  Sort  (cost=1452.19..1502.19 rows=20000 width=16) (actual time=5.237..5.239 rows=10 loops=1)
        Sort Key: ((embedding <-> '[<query vector>]'::vector))
        Sort Method: top-N heapsort  Memory: 25kB
        ->  Seq Scan on chunk c1_0  (cost=0.00..1020.00 rows=20000 width=16) (actual time=0.006..3.476 rows=20000 loops=1)

2. A distance threshold with no ORDER BY ... LIMIT. “Everything within 0.3” is a natural thing to ask, and it is a plain filter to the planner. Seven rows qualified, and 19,993 were read and thrown away:

== 5. Trap: a distance threshold with no ORDER BY ... LIMIT: select c.id from Chunk c where cosine_distance(c.embedding, :q) < 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)
  Rows Removed by Filter: 19993

I dropped the long Filter: line to keep the block readable; it is in the transcript. 3. Ordering by similarity instead of distance. order by 1 - cosine_distance(c.embedding, :q) desc is the same ordering mathematically, but the sort key is no longer the bare operator, so the planner cannot use the index:

== 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
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 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)

Source: output/05-hnsw-explain.txt

Order by the distance, and convert to a similarity in the select list or in Java.

4. A filter next to the ordering. This one still uses the index, which is the point: it looks fine and returns too few rows. With where c.category = 3 (10% of the table) the plan reads the index and applies the filter afterwards:

== 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
Limit  (cost=167.05..211.48 rows=10 width=16) (actual time=0.947..0.986 rows=6 loops=1)
  ->  Index Scan using chunk_hnsw_cos on chunk c1_0  (cost=167.05..9053.00 rows=2000 width=16) (actual time=0.946..0.983 rows=6 loops=1)
        Order By: (embedding <=> '[<query vector>]'::vector)
        Filter: (category = 3)
        Rows Removed by Filter: 34

Source: output/05-hnsw-explain.txt

The scan returned 6 rows, not 10: Rows Removed by Filter: 34 means it looked at 40 candidates and 34 belonged to other categories. The number 40 is not an accident, and section 8 explains it.

One worry that turned out to be nothing. The Criteria query from section 4 renders order by 2 (a column position). I expected that to defeat the index. It did not: step 7 of the transcript shows Index Scan using chunk_hnsw_cos for that statement too, because PostgreSQL resolves the position back to the expression. Also, Hibernate binds the query vector as a parameter ($1) rather than inlining it, and the plans above are for those parameterised statements.
Going deeper: how the plans were captured, and a production habit

The plans come from auto_explain, loaded for one connection inside the same transaction as the Hibernate query, with log_min_duration = 0 and log_analyze = on; the test reads the server log and extracts the plan of the statement that mentions the table. That requires a local server and a readable log, so on a managed database you would use EXPLAIN (ANALYZE) on the statement text instead. The habit worth copying is a test that runs your real repository method and asserts the plan contains Index Scan using on a table of realistic size. Small tables are not a valid test: the planner will prefer a sequential scan on a handful of rows even when the index is perfectly usable. I did not measure where that crossover is.

8. HNSW is approximate: recall, ef_search and filters

An exact search returns the true ten nearest rows. An HNSW search returns ten rows that are probably the nearest, and the fraction it gets right is called recall. I measured it by running 100 queries with the index and again with enable_indexscan = off (which forces the exact answer), and counting how many of the exact ten came back. The bars are the numbers from output/06-recall-ef-search.txt.

Recall@10 against exact search, by hnsw.ef_search (100 queries, 20,000 rows)0.500.751.000.725ef_search 100.874ef_search 200.966ef_search 400.995ef_search 1000.999ef_search 200Green is the default (40). Raising it buys recall; the cost is time per query, which is noisy on this machine (see the transcript).

The chart’s message is that the default is a trade-off, not a guarantee: at the default hnsw.ef_search = 40 about 1 in 30 of the true neighbours is missed on this data, at 10 about 1 in 4. The setting is per session, so from Hibernate you set it inside the transaction that runs the query. This is the helper the test uses; set_config(..., true) is the function form of SET LOCAL, so the value disappears at commit and cannot leak to the next user of a pooled connection:

List<Long> 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<Long>) em.createQuery(hql, Long.class).setParameter("q", q).getResultList();
    });
}

That is the run method of T06_RecallTest.java. Two more results from the same transcript are the ones that bite in production:

== 2. LIMIT 100 with the default ef_search = 40
rows requested: 100, rows returned: 40
with hnsw.ef_search = 200:  rows returned: 100

Asking for 100 rows with the default setting returned 40. The candidate list is the ceiling on what an index scan can return, so a LIMIT larger than ef_search silently returns fewer rows, which is a classic cause of “page 3 of my search is empty”. And the filter case from the last section, measured over all 100 queries:

== 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

With a 10%-selective filter the average result was about 4 rows of the 10 requested, which is what pgvector’s README predicts for this situation. pgvector 0.8 added iterative index scans: with hnsw.iterative_scan = relaxed_order the scan keeps walking until it has enough matching rows, and all 100 queries returned a full 10.

Going deeper: iterative scan modes, partial indexes, and the cross-store view

The README lists two iterative modes: strict_order keeps the exact order of results, relaxed_order may return slightly out-of-order rows in exchange for speed. I ran only relaxed_order here. The other standard answers to filtered search — a partial index per category, or table partitioning — come from the README and I did not run them. The numbers are specific to my synthetic data (ten clusters of 64-dimension points, seeded so the run is reproducible); real embeddings cluster differently, so treat the recall figures as a demonstration of the shape, not a prediction. Latency is in the transcript but is noisy and includes Hibernate and transaction overhead, so I do not rank settings by it.

The same ef_search and iterative-scan behaviour was measured across pgvector, Redis, Qdrant and Elasticsearch through Spring AI in the vector store comparison; this section is the Hibernate-side view of one of those four, so I kept it short.

9. Hibernate or Spring AI’s VectorStore?

Spring AI’s PgVectorStore solves the same storage problem from the opposite direction. You give it Document objects (text plus metadata) and an EmbeddingModel; it creates the table, computes the embeddings, and runs the similarity query for you. You never see a column or an operator. To compare honestly I ran it on the same database. The embedding model is a word-hashing stand-in (so the scores below say nothing about meaning), because the point here is the plumbing. What it built by itself, from output/07-spring-ai.txt:

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)

A uuid key, the text, a json metadata column, a vector(32), and an HNSW index with cosine operator class — the same index type this post built by hand. Its filtered search, from the same transcript, is one SQL statement:

SELECT *, embedding <=> $1 AS distance FROM public.vector_store WHERE embedding <=> $2 < $3  AND metadata::jsonb @@ '$."country" == "US"'::jsonpath  ORDER BY distance LIMIT $4
It is the same pattern with the same traps. The statement filters with embedding <=> $2 < $3 and orders by the alias distance, so whether the index is used depends on the same planner rules as section 7 — and the metadata filter is a jsonb predicate applied alongside it. With four rows I did not look at its plan, because a four-row table proves nothing about index use.
Hibernate + hibernate-vectorSpring AI PgVectorStore
What you modelYour own entity; the embedding is one column among othersA generic document table: id, text, JSON metadata, vector
Who computes embeddingsYou (store a float[])The store, through an EmbeddingModel
Query languageHQL, Criteria, Spring Data methodssimilaritySearch(SearchRequest) with a filter expression
Joins to other tablesOrdinary HQL joinsNone; metadata is JSON
IndexYou create it in a migrationCreated by initializeSchema(true); HNSW cosine in this run
Swap to another vector databaseRewrite queries; Hibernate supports several SQL databasesChange the store bean
Going deeper: using both, and what I did not test

Nothing stops one application from using both against one PostgreSQL: Spring AI for the retrieval-augmented-generation pipeline where documents are generic, Hibernate where the vectors belong to entities that other tables reference. Spring AI’s table could also be mapped read-only as a Hibernate entity to query it with HQL; I did not try it. The stand-in embedding model (HashingEmbeddingModel) hashes words into 32 buckets, so it only sees word overlap; anything about retrieval quality needs a real model and a labelled question set, which is what Measuring RAG retrieval quality in Java does.

10. Should you do this in Hibernate at all?

Often yes, but I only measured a small case. Putting vectors in the database you already run, next to the entities they describe, gives you transactions, joins and one backup, and Hibernate’s part is genuinely small: one annotation pair and HQL functions. That is a good fit when the vector count is modest and the search is one feature among many. It is a weaker fit if the vector store is the product, if you need very large collections or specialised filtering, or if you want to swap the vector database later without touching queries; for those, Spring AI’s abstraction or a dedicated store is a better start. I ran 20,000 rows. I did not measure millions, concurrent writers, index maintenance under updates, or a real embedding model, so I cannot tell you where Postgres stops being the right answer. The honest rule is the one in section 7: write the query, build the index, and read the plan before you trust either.
Production checklist (every line traces to a transcript)
  1. Create the HNSW index in a migration, not with hbm2ddl. The schema generator cannot express using hnsw (08-failures.txt).
  2. Match the operator class to the HQL function. vector_cosine_ops serves cosine_distance only; an L2 query against it is a sequential scan (05-hnsw-explain.txt, step 4).
  3. Always order by distance limit k. A threshold alone, or order by 1 - distance, scans everything (steps 5 and 6).
  4. Keep LIMIT at or below hnsw.ef_search, and set it per transaction with set_config(..., true) so it cannot leak through the pool (06-recall-ef-search.txt).
  5. Decide what to do about filters. A selective where returned about 4 of 10 rows by default; hnsw.iterative_scan = relaxed_order returned 10 (section 3 of that transcript).
  6. Test the plan with a realistic row count and assert Index Scan using; four-row tables prove nothing.
  7. Treat the dimension as part of the schema. A wrong-length array fails in PostgreSQL, not in Java (01-mapping.txt).
  8. Guard against zero vectors. Cosine distance to a zero vector is NaN (01-mapping.txt).
  9. Add a tie-breaker if result order must be stable; identical distances tie.
  10. Bulk-load with JDBC batching. With IDENTITY ids Hibernate does not batch inserts; the module’s loader uses JdbcTemplate.batchUpdate.
  11. Prefer HQL over Criteria for the query vector. A rejected cb.literal(float[]) poisoned later parameters in the same SessionFactory (03-criteria.txt).
  12. Do not copy the Vector attribute type from the Spring Data page into an entity (08-failures.txt).
  13. Pin versions and re-run the module when you upgrade Hibernate, Spring Data or pgvector: ./scripts/run-all.sh regenerates every transcript, and the tests assert the same facts.
Not tested, so not claimed
  • IVFFlat indexes, halfvec or binary-quantised indexes, and any index parameter sweep.
  • A real embedding model; the 4-dimension data is hand-made, the 64-dimension data is seeded synthetic clusters, and Spring AI used a word-hashing stand-in.
  • Tables beyond 20,000 rows, concurrent load, index maintenance on update and delete.
  • Oracle, MariaDB, MySQL, SQL Server, DB2, SAP HANA and CockroachDB, although the jar has contributors for them.
  • Hibernate 8, and PostgreSQL versions other than 16.15 (the module needs 16 or newer only because that is what I installed).
  • An HNSW index under the Spring Data SearchResults methods.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.