All posts

pgvector in Laravel 13: Tenant Filters, HNSW and the Rows That Go Missing

November 11, 2026Michał Woliński24 min read
pgvector in Laravel 13: Tenant Filters, HNSW and the Rows That Go Missing

pgvector is the PostgreSQL extension that stores embeddings in a column and finds the rows nearest to a query vector, with an approximate index called HNSW to do it fast. Laravel 13 made it a two-line feature: $table->vector('embedding', dimensions: 384)->index() in a migration, and whereVectorSimilarTo('embedding', $query) in a query. The search documentation shows exactly that, with ->limit(10), and it works.

I wanted to know what those two lines do once the table is not a demo. I loaded 100,000 paragraphs of Simple English Wikipedia into PostgreSQL 18.6 with pgvector 0.8.7, embedded them through the Laravel AI SDK with a small local model, spread them over 200 teams the way tenants of a SaaS app differ in size, and measured what Laravel's helpers send and what comes back.

Five results are worth knowing before you ship semantic search in Laravel:

  • A tenant filter quietly loses rows, and only for your largest customers. With where('team_id', …) in front of whereVectorSimilarTo(), teams holding 1.5% to 8.5% of the rows got between 0.6 and 2.75 rows when they asked for 10. Small teams got exact answers, because Postgres used the B-tree on team_id for them. Which teams fall on which side changed from one ANALYZE to the next.
  • paginate() promises pages the index cannot fill. One query reported 931 results on 94 pages. Pages 1 to 4 had ten rows each, page 5 and every page after it were empty.
  • The fix for the first problem collides with Laravel's threshold. pgvector's iterative scan brings the missing rows back, but combined with the distance condition whereVectorSimilarTo() adds, a threshold that fewer than ten rows pass made each search walk about 20,000 index entries: around 70 ms instead of 3. The query shape pgvector's README recommends stays at 3 ms.
  • The best fix is a separate HNSW graph for each large tenant. A partial index or a partition per large team, plus iterative scan for the teams that share an index, returned all 20,000 rows asked for across the 200 teams, at a recall of at least 94% for every team.
  • ->index() in the create-table migration makes the import slow. Inserting 100,000 vectors into a table that already had the HNSW index took 223 and 304 seconds in two runs. Inserting them first and building the index afterwards took 17 and 20 seconds.

Everything is in the companion repository: Laravel 13.42, laravel/ai 1.4.0, PostgreSQL 18.6 with pgvector 0.8.7 in Docker (the image is pinned by digest), and 35 PHPUnit tests for every claim a test can assert, run against the imported data, next to the benchmark commands that produced the measured numbers. Every code snippet below is a real file there, and every measured number comes from a run file in its runs/ directory. Where I rely on pgvector's README or on reading Laravel's source, the text says so.

The vocabulary

Six terms carry the rest of the article.

TermWhat it means here
EmbeddingA list of numbers a model computes for a piece of text, so that texts with similar meaning get nearby lists. bge-small, the model I used, returns 384 numbers.
vector(384)pgvector's column type for one embedding of exactly 384 dimensions. Postgres refuses a vector of any other length.
Cosine distance, <=>pgvector's operator for how far apart two vectors point: 0 for the same direction, 1 for unrelated, up to 2 for opposite. Laravel's similarity is 1 minus this distance.
HNSWAn approximate nearest-neighbour index: a graph pgvector walks from an entry point towards the query. Fast, and usually but not always right.
hnsw.ef_searchHow many candidates the walk keeps, 40 by default. The index hands over at most that many rows per scan, unless iterative scan is on.
Iterative scanhnsw.iterative_scan, new in pgvector 0.8.0: when filters remove rows, the index keeps walking until the query has enough, or until it has seen about hnsw.max_scan_tuples (20,000) rows. strict_order returns rows exactly by distance, relaxed_order may return them slightly out of order.

Recall is the share of the true nearest rows the index actually returned. An exact search, which compares the query with every row, has a recall of 100% and costs a full table scan.

The setup: two lines of schema and a local model

The migration is the one the Laravel documentation suggests. Schema::ensureVectorExtensionExists() runs create extension if not exists "vector", and ->index() on a vector column is not a B-tree: Laravel's Blueprint turns it into vectorIndex(), which on PostgreSQL is HNSW with cosine distance.

<?php // database/migrations/2026_11_11_000001_create_documents_table.php (excerpt) Schema::ensureVectorExtensionExists(); Schema::create('documents', function (Blueprint $table) { $table->id(); $table->unsignedInteger('wiki_id')->unique(); $table->unsignedInteger('team_id')->index(); $table->string('title'); $table->text('body'); $table->vector('embedding', dimensions: 384)->index(); });

The index Postgres reports afterwards, checked by a test:

CREATE INDEX documents_embedding_vectorindex ON public.documents USING hnsw (embedding vector_cosine_ops)

That pairing is the right one. An HNSW index only serves the distance it was built for, and whereVectorSimilarTo() always uses <=>, cosine. Index and query match out of the box.

For the embeddings I skipped paid APIs. The Laravel AI SDK has an openai-compatible driver, and llama.cpp's llama-server speaks the OpenAI embeddings API, so a local model is one entry in config/ai.php:

<?php // config/ai.php (excerpt) 'bge' => [ 'driver' => 'openai-compatible', 'url' => env('BGE_URL', 'http://127.0.0.1:8091/v1'), 'key' => 'none', 'models' => [ 'embeddings' => ['default' => 'bge-small-en-v1.5', 'dimensions' => 384], ], ],

The import command reads 256 paragraphs at a time, asks for their embeddings in one request, and inserts them:

<?php // app/Console/Commands/ImportWiki.php (excerpt) $vectors = Embeddings::for(array_column($rows, 'body'))->generate('bge')->embeddings; DB::transaction(function () use ($rows, $vectors): void { foreach ($rows as $index => $row) { DB::table('documents')->insert([ 'wiki_id' => $row['wiki_id'], 'team_id' => Teams::of($row['wiki_id']), 'title' => $row['title'], 'body' => $row['body'], 'embedding' => json_encode($vectors[$index]), ]); } });

The corpus is the first paragraph of 200 to 1,200 characters from each of the first 100,000 articles in the November 2023 Simple English Wikipedia dump (CC BY-SA 4.0). Teams::of() assigns every article to one of 200 teams with Zipf-shaped sizes, the way customers of a SaaS product differ: team 1 holds 16,941 rows, team 11 holds 1,492, team 150 holds 108. The assignment is synthetic and depends only on the article id, so the run is repeatable.

The full import took 877 seconds, 392 of them waiting for embeddings (that run also embedded the first 10,000 paragraphs with a second model, used later). Most of the rest was Postgres inserting into a table that already had its HNSW index, which turned out to be the first thing worth fixing. I come back to it in Building the index.

What whereVectorSimilarTo sends

This is the SQL Laravel 13.42 builds for the documented call, read from toSql() in a test:

select * from "documents" where ("embedding" <=> ?) <= ? order by ("embedding" <=> ?) asc limit 10

Three details follow from the bindings. The query vector is sent twice, once for the filter and once for the sort, each time as a JSON string: for 384 dimensions that is over 7 KB per query. minSimilarity defaults to 0.6, so the filter is distance <= 0.4. And it is a filter, a WHERE, not just an ordering, which matters later.

With the limit(10), Postgres walks the HNSW index for all 50 test queries, and the search took a median of 2.8 ms on the server. Without the limit it is a different query:

Laravel callPlanServer time, median of 50Rows
whereVectorSimilarTo(...)->limit(10)->get()Index Scan on the HNSW index2.8 ms10
whereVectorSimilarTo(...)->get()Seq Scan, Sort36.5 msmedian 286.5, max 1,871
the count(*) that paginate(10) runs firstSeq Scan68.4 ms1

An HNSW index can only answer "the k nearest rows", so Postgres uses it only for ORDER BY distance LIMIT k. Without a limit, every row's distance is computed and the matches are sorted. At 100,000 rows that is tens of milliseconds. The times in this table are Postgres' own execution times from EXPLAIN ANALYZE, because the client-side timings went through Docker Desktop's port forwarder, which added about 14 ms to every reply larger than a few kilobytes on my Mac. With select *, ten rows carry the embedding column, about 4.7 KB of text each, so that overhead would have dominated.

paginate() and the empty page 5

The count is the cheaper half of the pagination problem. For the first held-out paragraph, paginate(10) reported 931 results, so the paginator rendered links to 94 pages. Page 4 had ten rows. Page 5 had none, and neither did any page up to 94:

<?php // tests/Feature/PaginationTest.php (excerpt) $first = $page(1); $this->assertSame(931, $first->total()); $this->assertSame(94, $first->lastPage()); $this->assertCount(10, $page(4)); // hnsw.ef_search = 40: the index hands over 40 rows and the scan ends $this->assertCount(0, $page(5)); $this->assertCount(0, $page(50));

Two different queries answer the two questions. The count is exact, a full scan with the distance filter. The page is limit 10 offset 40 through the index, and a scan with the default settings yields at most ef_search, 40, rows. Offset 40 skips all of them.

Turning on iterative scan moves the edge but does not remove it: with hnsw.iterative_scan = strict_order, pages 5 to 87 filled, page 88 had 7 rows, and pages 89 to 94 were empty. Strict order returned 877 of the 931 matching rows. I first assumed the 20,000-row cap stopped it, but raising hnsw.max_scan_tuples to 100,000 changed nothing, and with relaxed_order all 931 came back: strict order gives up rows the walk finds too late to return in order. For semantic search, a total count and a last page are the wrong interface. simplePaginate() fits it better, because it asks for one row more than the page and offers a next page only if that row came back: with the defaults, page 3 offered a next page, page 4 had ten rows and offered none. It stops where the index stops, instead of promising pages it cannot fill.

cursorPaginate(), the usual cure for offset pagination, does not work here at all in Laravel 13.42. With whereVectorSimilarTo() the first page loads, and building the cursor for the next one fails with array_flip(): Can only flip string and integer values, because the order is an expression, not a column. Ordering by a selectVectorDistance() alias gets one page further, and the second page fails in Postgres with bind message supplies 4 parameters, but prepared statement ... requires 6. A cursor written by hand, where distance > last distance, runs, but it is one more distance filter after the index scan: with the defaults it returned four full pages, then 3 rows, then nothing. For semantic search the honest interface is the one search engines use, a fixed top-k: ask for the 10 or 50 results you will show and stop.

Filtering by team: the largest teams lose rows

Almost every real application filters. In a multi-tenant app the filter is the tenant, and the natural Laravel query is:

<?php // tests/Feature/TenantFilterTest.php (excerpt) return DB::table('documents')->select('id') ->where('team_id', $team) ->whereVectorSimilarTo('embedding', $vector, minSimilarity: 0.0) ->limit(10);

I ran it for all 200 teams with 20 held-out paragraphs each, timed in PHP around queries that select only the id, and compared what came back with an exact search. The planner split the teams in two. For the 189 smaller teams, up to 1,426 rows each, it used the B-tree on team_id, computed the distance for that team's rows and sorted them: ten rows every time, the true nearest ones. For the 11 largest teams it used the HNSW index, and that is where rows went missing. Where exactly that line falls is not fixed, as the end of this section shows.

Line chart of how many rows each of the 30 largest teams got back when it asked for 10. With default settings, team 1 got 7.55 rows on average, team 2 got 2.75, and teams 3 to 11 got between 2.7 and 0.6. From team 12 on, the line jumps to 10. With hnsw.iterative_scan set to strict_order, every team got 10 rows.
Rows returned per search, out of 10 asked for, for teams 1–30. From team 12 on, the smaller teams, the planner uses the B-tree on team_id and the answer is exact. Data: runs/teams.json.

The mechanism is in pgvector's README, which puts it in one sentence: "With approximate indexes, filtering is applied after the index is scanned." The index walks the graph for the whole table and hands over its 40 nearest rows. The WHERE team_id = 8 then keeps those that belong to team 8. Team 8 holds about 2% of the rows, so on average less than one of the 40 belongs to it.

Diagram with three rows. Team 8, default settings: the HNSW index hands over its 40 nearest rows, WHERE team_id = 8 keeps about 2% of them, LIMIT 10 ends with 0.7 rows on average. Team 150: the B-tree on team_id gives every row of team 150, they are sorted by distance, and LIMIT 10 returns the 10 true nearest rows. Team 8 with iterative scan: the HNSW index keeps handing over rows until 10 pass or about 20,000 were seen, the filter works as before, and LIMIT 10 returns 10 rows, 85.5% of the true nearest.
The same query, three plans. The planner chooses between the first two by team size.
TeamRowsDefault: rows returnedDefault: recallstrict_order: rowsstrict_order: recallstrict_order: median time
116,9417.5570.5%1087%3.8 ms
28,5462.7527.5%1081.5%5.5 ms
44,1831.919%1087%7.2 ms
82,1250.77%1085.5%11.0 ms
111,4920.66%1090%13.9 ms
12 to 2001,426 or fewer10 (B-tree)100%10 (B-tree)100%about 2–5 ms

The 11 teams on HNSW hold 51,198 of the 100,000 rows. In a real product they would be the accounts with the most data, often the ones paying the most. Teams 8 to 11 got less than one result per search on average, team 2 less than three. Nothing fails: no exception, no warning, just a short list. A test suite with a handful of rows per team will not see it, because at that size the planner picks the B-tree and the answer is exact.

The default numbers are close to pgvector's own estimate: "If a condition matches 10% of rows, with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average." Team 1, at 17%, got 7.55. The fix the README offers next is iterative scan, and with strict_order it brought every team to ten rows. It did not make the answer exact: 81.5% to 90% of the returned rows were among the true ten nearest, and the median time grew from about 3 ms to 14 ms as the team got smaller, because the index has to walk further to find ten of its rows. relaxed_order did better, as the next section shows. The README also suggests partial indexes and list partitioning, which I measured in Partial indexes and partitions below.

One more property of this cut-off surprised me. The planner decides between the B-tree and HNSW from the estimated share of rows a team has, and that estimate comes from ANALYZE, which reads a sample of the table. I ran ANALYZE 20 times in a row and listed, after each, the teams that went to HNSW: between 10 and 12 teams, in 4 different sets. Team 11, with 1,492 rows, went to HNSW after 17 of the 20 runs, team 12, with 1,426, after 7, and each time it switched between an exact answer and about one row in ten. Autovacuum runs ANALYZE by itself once enough rows in the table have changed, so a customer's search can get worse overnight because other customers wrote data, with no deploy and no change in their own. Raising the statistics target, alter table documents alter column team_id set statistics 1000, made ANALYZE sample the whole table here, and the same 11 teams went to HNSW in all 10 runs. That makes the behaviour predictable. It does not make it correct.

The threshold and iterative scan collide

Iterative scan is a setting of the session, or of the transaction with SET LOCAL, and it changes every HNSW query there, including the ones that do not filter by team. That is where Laravel's query shape matters. whereVectorSimilarTo() puts the similarity threshold in the WHERE. For the index, that is just another filter applied after the scan. When the threshold is strict and few rows pass it, an iterative scan keeps looking for rows that can never come:

minSimilarityRows passing (avg)Laravel's query, iterative scan offLaravel's query, strict_orderSubquery form, strict_order
0.6103.1 ms3.2 ms2.6 ms
0.73.023.2 ms74.0 ms2.8 ms
0.80.13.4 ms72.7 ms2.7 ms
0.903.3 ms69.3 ms2.7 ms

Medians over 50 held-out paragraphs, limit 10, no team filter, measured in PHP around queries that select only the id. EXPLAIN ANALYZE shows why: with iterative scan off, the threshold of 0.9 removed 40 rows and the scan ended. With strict_order it removed 19,990, which is hnsw.max_scan_tuples, the cap.

pgvector's README anticipates this: "For queries that filter by distance, use a materialized CTE and place the distance filter outside of it for best performance." Laravel's query builder has no CTE, but a subquery in FROM does the same job here, because Postgres cannot move a WHERE inside a subquery that has a LIMIT. The index finds the ten nearest rows, and only then does the threshold drop the ones that are too far. The last column of the table is that form.

The subquery has a second use. pgvector's README says relaxed order "provides better recall", and suggests sorting its results again outside a materialized CTE. I measured the subquery form on teams 1 to 11, 20 searches each:

Iterative scanOuter sortRowsRecallSearches out of orderMedian time
strict_orderorder by distance2,200 of 2,20085.6%0 of 2208.8 ms
relaxed_orderorder by distance2,200 of 2,20092.7%84 of 2208.6 ms
relaxed_orderorder by distance + 02,200 of 2,20092.7%0 of 2208.0 ms

Relaxed order found 92.7% of the true nearest rows instead of 85.6%, at the same speed. The middle row is the trap the README warns about in a note, "+ 0 is needed for Postgres 17+": with a plain order by distance outside, Postgres 18 decided the subquery's rows were already sorted, dropped the outer sort, and 84 of 220 result lists came back out of order. distance + 0 is not something the planner can match to the subquery's order, so the sort stays.

Put together, the team filter and the threshold give the service class I would actually ship:

<?php // app/Search/SemanticSearch.php (excerpt) public function forTeam(int $team, array $vector, int $limit = 10, float $minSimilarity = 0.0): Collection { return DB::transaction(function () use ($team, $vector, $limit, $minSimilarity): Collection { DB::statement("set local hnsw.iterative_scan = 'relaxed_order'"); DB::statement('set local hnsw.ef_search = '.$this->efSearch); $nearest = DB::table('documents') ->select('id', 'title') ->selectVectorDistance('embedding', $vector, as: 'distance') ->where('team_id', $team) ->orderBy('distance') ->limit($limit); return DB::query() ->fromSub($nearest, 'nearest') ->select('id', 'title', DB::raw('1 - distance as similarity')) ->where('distance', '<=', 1 - $minSimilarity) // + 0: with a plain "order by distance" Postgres trusts the subquery's order and skips this sort ->orderByRaw('distance + 0') ->get(); }); }

Its tests check that every one of the 200 teams gets ten rows in order, that a threshold of 0.9 comes back empty quickly, and that neither setting is still active on the connection after the call. SET LOCAL lasts until the end of the transaction, so the settings cannot leak into the next request on a persistent connection, as they would with a plain SET under Octane or in a queue worker. Behind PgBouncer in transaction mode a plain SET is wrong for the same reason, as my PgBouncer article explains, while SET LOCAL inside the transaction travels with it.

One case the class cannot contain: called inside a transaction that is already open, in a job wrapped in DB::transaction() for example, Laravel turns its DB::transaction() into a savepoint, and SET LOCAL lasts until the outer transaction ends. A test shows the consequence: a plain whereVectorSimilarTo() with a threshold of 0.9, run later in the same outer transaction, again walked the index to the 20,000-row cap. Keep vector searches out of long transactions, or use the subquery form for every vector query in them.

Partial indexes and partitions

Iterative scan repairs the shared index after the fact. pgvector's README lists two ways to avoid the problem instead: a partial index, "if filtering by only a few distinct values", and list partitioning, "if filtering by many different values", which it also recommends for tenant isolation. Both give a team its own HNSW graph, so the index hands over only that team's rows and the filter has nothing left to remove. I measured both on the same rows and the same 20 searches per team, with iterative scan off:

LayoutTeamRows returned (of 200)RecallMedian time
Shared table, one HNSW index8147%4.8 ms
Shared table plus create index … where team_id = 8820098.5%2.0 ms
Partitioned, team 8 has its own partition8200100%4.3 ms
Partitioned, team 2 has its own partition220095%3.5 ms
Partitioned, team 13 in the default partition132010%4.0 ms
Same, with hnsw.iterative_scan = relaxed_order1320096%9.0 ms

The partial index for team 8 built in under half a second and gave the best answers in the article. The catch is that it covers one value: a partial index per tenant is 200 indexes for 200 tenants, and every new tenant is a migration. It also needs the planner to see the team id. Laravel's queries are planned with their values every time, so they used it, but a statement prepared once and run with a generic plan, as in a PL/pgSQL function, cannot prove team_id = 8: in a test it went back to the B-tree, still exact but no longer on the index you built for it.

The partitioned table, in scripts/partitions.sql, gives teams 1 to 11 a partition each and puts the other 189 teams in a default partition of 48,802 rows. Every team with its own partition got ten rows, at 95% to 100% recall, and the small partitions were even read with a sequential scan, which is exact. But the problem moved instead of disappearing. Team 13 has 1,297 rows. On the shared table the planner had given it the B-tree and an exact answer; in the default partition those rows are 2.7% of the partition, so it went to the partition's HNSW index and got 20 rows out of 200. Teams 12 and 14 did the same. Partitioning protects the tenants you give a partition, and creates a new set of large tenants among the rest.

It also changes the queries that do not filter by team. A search across all teams now walks 12 HNSW indexes and merges them: 11.2 ms instead of 4.5 ms in this run, at a recall of 97% instead of 94%. If your product never searches across tenants, that does not matter. If an admin screen does, it is the price.

So I measured the combination: a partial HNSW index for each of teams 1 to 12, and SemanticSearch, with its relaxed iterative scan, for all 200 teams, ten searches each. Every search returned ten rows, 20,000 of 20,000, at a recall of at least 94% for every team and 99.8% on average. The cost moved to the largest team without an index of its own: team 13 took a median of 38.6 ms, because the iterative scan has to walk far through the shared graph to collect ten of its rows. Watch that tier, and give it an index when it grows. I did not test partitioning every tenant, which is the README's answer for strict isolation and brings its own costs with thousands of partitions.

Is 0.6 a good threshold?

Similarity numbers are not calibrated across models, so a fixed default threshold is a guess. To see how good a guess, I wrote 40 plain questions with a known answer in the corpus, such as "black and white bear that eats bamboo" for the article Giant panda, and scored each against 10,246 articles: the first 10,000, plus the 40 answers wherever they were. I did that with bge-small and with a second model, nomic-embed-text v1.5, which has 768 dimensions and expects task prefixes such as search_query: in front of a question.

ModelRight article ranked 1stRight article in top 10Right article at 0.6 or moreArticles at 0.6 or more, the right one included (median per question)
bge-small-en-v1.525 of 4038 of 4038 of 4048
nomic-embed-text v1.5, with prefixes22 of 4035 of 4036 of 4039.5
nomic-embed-text v1.5, question without prefix24 of 4037 of 4036 of 4020.5

For these two models 0.6 happens to sit in a usable place: the right article usually passes, at a median similarity of 0.74 with bge. But it is not a relevance filter. With bge a median of 48 of the 10,246 articles passed it per question, the right one included, and for the held-out paragraphs used in the timings, a median of 286.5 of the 100,000 rows passed it. Ranking does the work, and the limit decides how many results you show. Models with a different similarity scale can pass far more or far fewer rows at 0.6, so measure your own before you rely on it. I expected the missing search_query: prefix to hurt nomic's ranking, which is what a plain string passed to whereVectorSimilarTo() gets. On these 40 questions it did not, and the difference is within what 40 questions can show.

One detail of passing a string: whereVectorSimilarTo('embedding', 'black and white bear') calls the embeddings provider through the Laravel AI SDK, and the query builder asks for the result to be cached. In laravel/ai 1.4.0 that cache lasts 30 days in your default cache store, even with 'cache' => false in config/ai.php. A test checks it: two identical searches 29 days apart make one HTTP request, a third after 31 days makes the second. That is usually what you want, but it means a model change needs a cache flush, and that every distinct search text lands in your cache store.

Recall and ef_search

Without any filter, how close is HNSW to the exact answer? I used 200 paragraphs that are not in the table as queries and compared the ten rows HNSW returned with the true ten nearest:

hnsw.ef_searchRecall@10Median time
1081.25%2.8 ms
2090.25%3.5 ms
40 (default)94.95%3.4 ms
8097.25%3.9 ms
16098.45%4.9 ms
32099.15%6.7 ms

The exact search, a sequential scan, took a median of 54 ms. At 100,000 rows of 384 dimensions, the default misses about one row in twenty, and doubling ef_search to 80 nearly halves that for half a millisecond. Set it the same way as the iterative scan, with SET LOCAL inside a transaction.

Building the index

The migration above creates the HNSW index on an empty table, so every one of the 100,000 inserts during the import also inserts into the graph. I measured the alternatives in psql, copying the same 100,000 vectors from the imported table, twice:

OrderRun 1Run 2
Index first, then insert (what ->index() in the create migration does)223 s304 s
Insert, then build, maintenance_work_mem = 512MB0.8 s + 16.4 s1.3 s + 18.9 s
Insert, then build, Postgres' default 64MB57.8 s62.1 s

At 64 MB the build printed pgvector's notice after about 28,000 rows: hnsw graph no longer fits into maintenance_work_mem. The builds used the two parallel maintenance workers Postgres allows by default, in a container with 8 CPUs.

For a table you fill in bulk, leave ->index() out of the create migration, import, and add the index in a later migration:

<?php // examples/migrations/2026_11_11_000002_add_embedding_index_to_documents.php (excerpt) public function up(): void { // Postgres' default is 64MB; at 64MB the graph stopped fitting after about 28,000 rows and the build took 58–62 s DB::statement("set maintenance_work_mem = '512MB'"); Schema::table('documents', function (Blueprint $table) { $table->vectorIndex('embedding'); }); }

A test runs it inside a transaction on the loaded table and checks that it builds the same index definition. Ongoing inserts after that are a different matter: the bulk insert into the indexed table worked out at 2 to 3 ms per row, which a single insert can afford and an import of a million rows cannot.

Dimensions: 1536, 3072 and halfvec

Two limits show up when you switch models. A vector of the wrong length fails loudly, which is good: inserting a 1,536-dimension embedding, the size of OpenAI's text-embedding-3-small, into vector(384) raises expected 384 dimensions, not 1536. Re-embedding with another model means a migration and a full re-import, not a config change.

The second limit fails at migration time. pgvector stores up to 16,000 dimensions in a vector column, but HNSW indexes only up to 2,000. A 3,072-dimension column, the size of text-embedding-3-large, with ->index() fails with column cannot have more than 2000 dimensions for hnsw index. The documented way out is to index a half-precision copy, halfvec, which HNSW takes up to 4,000 dimensions, with an expression index. Laravel has no helper for that index, so it is raw SQL. The query side works, because whereVectorSimilarTo() accepts an expression as the column:

<?php // tests/Feature/SchemaTest.php (excerpt) DB::statement('create index large_embeddings_halfvec on large_embeddings using hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops)'); DB::statement('set local enable_seqscan = off'); $vector = array_fill(0, 3072, 0.01); $plain = DB::table('large_embeddings')->whereVectorSimilarTo('embedding', $vector)->limit(10); $cast = DB::table('large_embeddings')->whereVectorSimilarTo(DB::raw('embedding::halfvec(3072)'), $vector)->limit(10); $this->assertStringNotContainsString('large_embeddings_halfvec', $this->plan($plain)); $this->assertStringContainsString('Index Scan using large_embeddings_halfvec', $this->plan($cast));

The query must cast exactly as the index does, or Postgres will not use it. The test sets enable_seqscan = off because its table is empty and the planner would otherwise prefer a scan. It proves the index can be used, not how it performs. I did not load 3,072-dimension data.

A puzzle: green in the tests, empty in production

A developer reads the section on teams and writes the shortest possible fix:

<?php // app/Search/NaiveSemanticSearch.php (excerpt) public function forTeam(int $team, array $vector): Collection { DB::statement("set local hnsw.iterative_scan = 'strict_order'"); return DB::table('documents')->select('id') ->where('team_id', $team) ->whereVectorSimilarTo('embedding', $vector, minSimilarity: 0.0) ->limit(10) ->get(); }

A feature test that uses RefreshDatabase searches team 8 and gets ten rows. The developer ships. In production, the same call for the same paragraph returns nothing. Same database, same data, same code. What is different?

The answer

RefreshDatabase wraps every test in a database transaction and rolls it back afterwards. Inside a transaction, SET LOCAL works until the transaction ends, so the search runs with iterative scan on and finds ten rows. In production there is no surrounding transaction. Each statement runs on its own, and SET LOCAL outside a transaction block does nothing. Postgres says so, but only as a warning, SET LOCAL can only be used in transaction blocks, and Laravel does not surface warnings. The search then runs with the defaults, the index hands over 40 rows, and none of them belong to team 8.

Both halves are tests in the repository, one with RefreshDatabase expecting ten rows and one without it expecting zero, against the same class. The fix is the DB::transaction() in SemanticSearch above. The lesson is wider than pgvector: any SET LOCAL your code depends on behaves differently under RefreshDatabase, so test that code once without it.

What to reach for

  • Always put a limit on vector search. Without one, Postgres skips the HNSW index and computes every row's distance. Show as many results as you ask for.
  • Do not use paginate() or cursorPaginate() on vector search. The count is a full scan, pages beyond ef_search come back empty, and the cursor fails to build. Show a fixed top-k, or use simplePaginate(), which stops offering pages when the index runs out.
  • Give your largest tenants their own HNSW graph. A partial index or a partition per large tenant gave them ten rows every time, at 95% to 100% recall. Keep iterative scan for the tenants that share an index, because the next tier down falls off it in turn.
  • For the tenants that share an index, turn on iterative scan for that query. SET LOCAL hnsw.iterative_scan = 'relaxed_order' inside DB::transaction(), with the nearest rows in a subquery and orderByRaw('distance + 0') outside it. Test it with your largest tenant, not a fixture with ten rows, and once without RefreshDatabase.
  • Pin the statistics of the tenant column. alter table … alter column team_id set statistics 1000 stops ANALYZE from moving tenants on and off the index between runs. It makes the problem stable, so your tests and your monitoring see the same tenants until the data itself shifts.
  • Apply the similarity threshold after the nearest rows are found. With iterative scan on, whereVectorSimilarTo()'s WHERE made a search more than 20 times slower here. Use a subquery with the limit inside and the threshold outside, as in SemanticSearch.
  • Do not trust 0.6. It is a default, not a property of your model. Rank, limit, and measure the threshold on questions with known answers if you need one.
  • Run pgvector 0.8.4 or later. According to its changelog, 0.8.3 (June 2026) fixed possible index corruption with HNSW vacuuming and 0.8.4 an error in the same code. A managed database can lag behind, so check select extversion from pg_extension where extname = 'vector'.
  • Build the index after a bulk import, with more maintenance_work_mem. Leave ->index() out of the create migration and add vectorIndex() in a later one.
  • Count short answers in production. Nothing errors when the index runs dry, so log or count the searches that return fewer rows than they asked for while the team has more than that. It is how the problems in this article would show up in production.
  • Raise ef_search when recall matters. 80 instead of 40 cost half a millisecond here and nearly halved the misses.
  • Above 2,000 dimensions, index halfvec. An expression index in raw SQL, and DB::raw() with the same cast as the column in whereVectorSimilarTo().

Scope and how this was checked

The repository's compose.yaml runs PostgreSQL 18.6 with pgvector 0.8.7 (pgvector/pgvector:0.8.7-pg18-trixie, pinned by digest), with shared_buffers of 1 GB and maintenance_work_mem of 512 MB. The application is Laravel 13.42.0 with laravel/ai 1.4.0 on PHP 8.5.12. Embeddings came from bge-small-en-v1.5 (f16) and nomic-embed-text v1.5 (Q8_0) in GGUF form, served by llama.cpp's llama-server on the Mac's GPU. php artisan wiki:import loads the corpus, wiki:nomic embeds the nomic sample, wiki:embed-queries stores the query vectors once, so the 35 tests and the benchmarks need the database but no model server. wiki:bench, scripts/thresholds.php, scripts/shapes.php, scripts/analyze-flips.php, scripts/partitions.sql and scripts/index-build.sql write the run files the tables come from, and scripts/check_article.py checks every number quoted here against them.

The limits matter. Everything ran on one machine, an Apple silicon Mac with Docker Desktop and 8 CPUs given to Docker, and single runs, except the index builds, which ran twice: the second was up to 36% slower. One dataset, one size: at a million rows or with 1,536 dimensions the times move, and the share of a table a filter must keep before the planner prefers HNSW will move with them. The teams are synthetic, assigned by a hash of the article id with Zipf-shaped sizes, and the query vectors for recall and filtering are paragraphs held out from the table, not user questions. The 40 hand-written questions are a small set, enough to show that 0.6 is not a relevance filter, not enough to rank models. I did not test IVFFlat, a partition for every tenant, relaxed_order outside the subquery form and the partitioned table, or MariaDB, which whereVectorSimilarTo() also supports. What Laravel sends comes from toSql() and from reading the 13.42.0 source, and what pgvector recommends comes from its README at the 0.8.7 tag.

Related Articles