Vector Search & pgvector
"By default, pgvector performs exact nearest neighbor search, which provides perfect recall. You can add an index to use approximate nearest neighbor search, which trades some recall for speed." — pgvector README, github.com/pgvector/pgvector
Summary: Vector search finds the rows whose embeddings are nearest to a query embedding; exact search is always right and slow, approximate indexes (HNSW, IVFFlat, DiskANN) are fast and can miss a neighbour, and every knob is a trade between recall, latency, memory and build time. Focus: Embeddings and dimensions, distance metrics, exact vs approximate search, HNSW and IVFFlat internals, quantization, pgvector types/operators/index knobs, filtering and the post-filter problem, hybrid search with RRF, multi-tenancy, freshness, re-embedding, chunking, evaluation, Postgres vs dedicated engines, and the Go and Laravel code. Learning goal: Choose a metric, an index and a filter strategy for a workload, measure recall against an exact baseline instead of trusting defaults, and operate the index (build memory, updates, model change) without surprises.
This page is the complete reference for vector search in a database: what an embedding is and why its dimension is a cost, the distance metrics (cosine, L2, inner product, L1, Hamming and Jaccard for binary vectors), exact kNN versus approximate nearest neighbour (ANN) search, the recall/latency trade-off, HNSW (layers, m, ef_construction, ef_search), IVFFlat (lists, probes), scalar, product and binary quantization, DiskANN and pgvectorscale's StreamingDiskANN, the pgvector types (vector, halfvec, sparsevec, bit), operators and operator classes, index build memory (maintenance_work_mem), metadata filtering and the post-filter problem, iterative scans (pgvector 0.8), partitioning, multi-tenancy, hybrid search (BM25 plus vectors, Reciprocal Rank Fusion), index freshness, embedding model versioning and re-indexing, chunking for RAG, evaluation with recall@k, and how PostgreSQL compares with Qdrant, Milvus, Weaviate, Pinecone, Vespa, Elasticsearch/OpenSearch and Redis vector sets. Keyword ranking and tsvector live in Full-Text Search; the B-tree/GIN/GiST family is in Indexing; partitions are in Partitioning & Sharding in PostgreSQL; tenancy models are in Multi-Tenancy Strategies; the full retrieval-augmented generation application is in RAG & LLM apps in Go. Everything verified on this page comes from the pgvector 0.8.7 README, the pgvectorscale and Redis vector-set READMEs, Elastic's kNN documentation, the RRF paper, the Laravel 13 documentation, and a lab run on PostgreSQL 17 with pgvector 0.8.7 (numbers are in the Lab). Statements about other products' internals that were not re-fetched are marked as general knowledge.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why vectors, and why approximate | Why vector search exists |
| History: HNSW paper, pgvector, DiskANN | Where it comes from |
| What an embedding is, dimensions, cost | Embeddings and dimensionality |
| Cosine vs L2 vs inner product vs Hamming vs Jaccard | Distance metrics |
| Exact kNN vs ANN, recall vs latency | Exact vs approximate |
HNSW graph, m, ef_construction, ef_search | HNSW |
IVFFlat, lists, probes | IVFFlat |
Scalar, product, binary quantization, halfvec | Quantization |
| DiskANN, StreamingDiskANN, pgvectorscale | DiskANN |
WHERE plus ANN returns too few rows | The post-filter problem and Iterative scans |
| Partition per tenant, partial indexes | Partitioning and multi-tenancy |
| BM25 plus vectors, RRF | Hybrid search |
| Inserts, updates, deletes, vacuum | Index freshness |
| Changing the embedding model | Model versioning |
| Splitting documents for RAG | Chunking |
| How good are my results | Evaluation |
| Types, operators, operator classes, knobs, errors | Mechanics |
| PostgreSQL vs Qdrant, Milvus, Weaviate, Pinecone, Vespa, Elasticsearch, Redis | Per-engine behaviour |
| Working SQL, Go and Laravel | Solving the classic problems |
| Generating embeddings from Ollama or OpenAI | Embedding generation |
| Which index and engine for which workload | Choosing |
| Monolith to many services | In architecture |
| 100k vectors, exact vs HNSW, filters | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The six distance functions pgvector ships. Every row is unpacked in Distance metrics.
| Metric | Operator | Operator class (HNSW/IVFFlat) | Plain words | Use it when |
|---|---|---|---|---|
| L2 (Euclidean) | <-> | vector_l2_ops | Straight-line distance | Embeddings trained for L2, image features |
| Inner product | <#> (returns the negative) | vector_ip_ops | Dot product; bigger means closer | Normalised embeddings (fastest), recommenders |
| Cosine distance | <=> | vector_cosine_ops | 1 minus the cosine of the angle; ignores length | Text embeddings in general |
| L1 (taxicab) | <+> | vector_l1_ops (HNSW only) | Sum of absolute differences | Sparse or count-like features |
| Hamming | <~> | bit_hamming_ops | Number of differing bits | Binary codes, binary quantization, image hashes |
| Jaccard | <%> | bit_jaccard_ops (HNSW only) | 1 minus overlap over union of set bits | Set similarity on bit vectors |
The two approximate indexes in pgvector.
| HNSW | IVFFlat | |
|---|---|---|
| Structure | Multilayer proximity graph | Inverted lists around k-means centroids |
| Needs data to build | No (empty table is fine) | Yes (k-means needs rows) |
| Build time and memory | Slower, more memory | Faster, less memory |
| Speed-recall trade-off | Better | Worse |
| Query knob | hnsw.ef_search (default 40) | ivfflat.probes (default 1) |
| Build knobs | m (16), ef_construction (64) | lists (rows / 1000, sqrt(rows) over 1M) |
| Incremental inserts | Good (links are added) | Degrades as data drifts from the centroids |
| Lab result (100k, 64-d) | Build about 5 to 10 s, 54 MB, recall 0.94 at ef_search = 40 | Build 0.9 s, 27 MB, recall 0.84 at probes = 10 |
The three things to do.
| Situation | Do this |
|---|---|
| Starting out | Exact search first. Add HNSW with defaults only when the scan is too slow, then measure recall@k against the exact result |
A WHERE clause plus ANN | Check rows returned = LIMIT; if not, B-tree on the filter, partial index, partition, or hnsw.iterative_scan |
| Changing the embedding model | New column or table, backfill, new index, switch reads, drop the old; never mix models in one index |
Why vector search exists
Keyword search matches the words you typed. Vector search matches what the text means, because a model has turned each item into a point so that similar items are close. The database problem that remains is purely geometric: given a query point, find the closest stored points quickly. Every row compared against every other is O(N * d), which is fine for 50,000 rows and not for 50 million.
| Choice | Weaker side | Stronger side |
|---|---|---|
| Exact scan | Latency grows linearly with rows | Perfect recall, no index to build or maintain |
| Approximate index | Can miss a true neighbour; filters interact badly; memory-hungry | Sub-linear latency, often milliseconds at millions of rows |
| Keep vectors in Postgres | Index tuning is your job; one machine's memory | Transactions, joins, SQL filters, backups, one system |
| Dedicated vector engine | Second datastore to sync and operate | Purpose-built indexes, quantization, sharding, filterable graphs |
| Higher dimension | Memory, build time and latency all grow | Often a little better relevance |
An everyday picture, reused below. A city of cafés. Exact search means walking into every café and measuring. HNSW is a road network (highways, main roads, side streets): you take the highway, exit near the target and walk the side streets. IVFFlat is a city divided into districts: you visit the district nearest to you, maybe the next one too. Metadata filtering is "only cafés that are open on Sunday": if you filter after arriving at the nearest ones, they may all be closed.
Three common misunderstandings, up front
- "Vector search returns the right answer." It returns the nearest points in the space a model built. If the model put two unrelated things close, the search is faithfully wrong. Retrieval quality has two parts: how good the embeddings are, and how much the index loses (recall). This page only controls the second.
- "An index only makes it faster." An approximate index changes the result set. The pgvector README says it directly: "Unlike typical indexes, you will see different results for queries after adding an approximate index."
- "Adding
WHERE tenant_id = 7just narrows the search." With an approximate index the filter runs after the index returns candidates, so it can leave you with 0 rows and no error. In the lab below, a 1% filter returned 0.4 rows on average forLIMIT 10.
Where it comes from
Nearest-neighbour search is older than databases; what changed is the input. Embedding models turn text, images and audio into fixed-length arrays of floats, and "similar" becomes "close in that space". How such models are trained is out of scope; for storage each item is a point with a fixed dimension such as 1536.
The graph index most systems use today is HNSW. Malkov and Yashunin submitted Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs to arXiv on 30 March 2016. Their abstract says:
"The maximum layer in which an element is present is selected randomly with an exponentially decaying probability distribution."
Starting the search from the sparse upper layer, where links are long, and descending is what the authors credit with "logarithmic complexity scaling" (arXiv:1603.09320). That is a claim about their benchmarks and construction, not a guarantee for every dataset. The inverted-file idea (IVF) and product quantization (PQ) come from the earlier image-retrieval literature (Jégou, Douze and Schmid, 2011 for PQ; general knowledge, not re-fetched here). DiskANN is a Microsoft Research graph index designed to keep most of the data on SSD; the pgvectorscale README says its StreamingDiskANN index is "inspired by the DiskANN algorithm, based on research from Microsoft".
pgvector is an open-source Postgres extension that adds the vector, halfvec, bit and sparsevec types, distance operators and two approximate indexes. Its README opens with "Store your vectors with the rest of your data." and lists "exact and approximate nearest neighbor search", "single-precision, half-precision, binary, and sparse vectors" and "L2 distance, inner product, cosine distance, L1 distance, Hamming distance, and Jaccard distance". The version used for this page is 0.8.7. Iterative index scans arrived in 0.8.0. Laravel 13 added native support: vector columns, the AsVector cast and whereVectorSimilarTo, documented for PostgreSQL with pgvector and MariaDB 11.7 or later.
Reciprocal Rank Fusion comes from Cormack, Clarke and Buettcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (SIGIR 2009): RRFscore(d) = sum over rankings of 1 / (k + r(d)) with k = 60 "fixed during a pilot investigation".
The concept catalogue
Embeddings and dimensionality Must-know
In plain words: An embedding is a list of numbers (say 1536 of them) that a model produced from a piece of text or an image, so that things with similar meaning get similar lists. The list length is the dimension, and it is fixed by the model.
Common misunderstanding: "More dimensions always means better search." Dimension is a property of the model. Past a point it only costs memory, build time and latency; many modern models can be truncated (Matryoshka-style) or reduced with little quality loss, and you should measure instead of assuming.
Definition: A dense embedding is a vector in R^d, where d is the model's output size. Examples of dimensions in use: 384 and 768 (small and base open models), 1024, 1536 (OpenAI text-embedding-3-small, the size used in the Laravel docs), 3072 (OpenAI text-embedding-3-large). A sparse embedding has a huge nominal dimension (a vocabulary of 30,000 or more) with few non-zero entries; pgvector stores those in sparsevec.
1 text: "reset my password"
2 embed(model): [0.012, -0.044, 0.130, ... 1533 more numbers ...] -- vector(1536)
3 stored as: 4 * 1536 + 8 = 6152 bytes in a pgvector `vector`
4 query: embed("I forgot my login") -> another 1536 numbers
5 search: nearest stored vector by cosine distance -> "reset my password"Real scenario: A support-article search over 2 million chunks; a product recommender using item embeddings; duplicate-image detection with 64-bit perceptual hashes stored as bit(64); code search; deduplicating customer records by name embeddings.
What provides it / what limits it:
| Engine / type | Max dimensions | Storage per vector |
|---|---|---|
pgvector vector column | 16,000 | 4 * dims + 8 bytes |
pgvector halfvec column | 16,000 | 2 * dims + 8 bytes |
pgvector bit column | n/a (bit string) | dims / 8 + 8 bytes |
pgvector sparsevec column | 16,000 non-zero elements | 8 * non-zero + 16 bytes |
pgvector HNSW or IVFFlat index on vector | 2,000 | the index stores a copy of the vector |
pgvector index on halfvec | 4,000 | half the size |
pgvector index on bit | 64,000 | 1 bit per dimension |
pgvector HNSW index on sparsevec | 1,000 non-zero elements | per non-zero element |
Elasticsearch dense_vector, Qdrant, Milvus, Weaviate, Pinecone | limits are product- and version-specific; check the docs of your version | general knowledge |
Fix / how to use it:
-- The dimension is part of the type: the column rejects any other length.
CREATE TABLE documents (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(1536) NOT NULL
);
-- Postgres refuses a wrong-sized vector at insert time:
-- ERROR: expected 3 dimensions, not 2
SELECT vector_dims(embedding), vector_norm(embedding) FROM documents LIMIT 1;// A length check before the INSERT gives a clearer error than the database's.
func checkDims(v []float32, want int) error {
if len(v) != want {
return fmt.Errorf("embedding has %d dimensions, column expects %d", len(v), want)
}
return nil
}// Laravel: the dimension is declared once, in the migration.
$table->vector('embedding', dimensions: 1536);Distance metrics Must-know
In plain words: A metric is the ruler used to decide how close two points are. Three rulers cover most work: straight-line distance (L2), the angle between the arrows (cosine), and the dot product (inner product).
Common misunderstanding: "Cosine and inner product are interchangeable." They give the same ranking only when every vector has length 1. Otherwise the length is part of the signal for inner product and ignored by cosine. Also, an index built with vector_cosine_ops is not used by a query that orders by <->.
Definition: For vectors a and b: L2 is the square root of the sum of squared differences; inner product is the sum of a_i * b_i; cosine distance is 1 - (a . b) / (|a| * |b|); L1 is the sum of |a_i - b_i|; Hamming is the count of differing bits; Jaccard distance on bit vectors is 1 - |a AND b| / |a OR b|.
1 a = [1,2,3] b = [3,2,1]
2 a <-> b = sqrt(4 + 0 + 4) = 2.828
3 a <#> b = -(3 + 4 + 3) = -10 -- negative inner product
4 a <=> b = 1 - 10 / (3.742*3.742) = 0.2857 -- cosine distance
5 a <+> b = 2 + 0 + 2 = 4 -- L1
6 '10101'::bit(5) <~> '10011'::bit(5) = 2 -- Hamming
7 '10101'::bit(5) <%> '10011'::bit(5) = 0.5 -- Jaccard (2 shared of 4 set bits)Real scenario: OpenAI-style embeddings are normalised to length 1, so inner product ranks like cosine and is the fastest operator (the pgvector README recommends it for that case). A recommender whose vector length encodes popularity wants inner product precisely because length matters. Perceptual image hashes use Hamming.
What provides it: the operator, the function and the operator class must agree.
| Metric | Operator | Function | vector / halfvec | sparsevec | bit |
|---|---|---|---|---|---|
| L2 | <-> | l2_distance | *_l2_ops | sparsevec_l2_ops | n/a |
| Inner product | <#> | inner_product (positive) | *_ip_ops | sparsevec_ip_ops | n/a |
| Cosine | <=> | cosine_distance | *_cosine_ops | sparsevec_cosine_ops | n/a |
| L1 | <+> | l1_distance | *_l1_ops | sparsevec_l1_ops | n/a |
| Hamming | <~> | hamming_distance | n/a | n/a | bit_hamming_ops |
| Jaccard | <%> | jaccard_distance | n/a | n/a | bit_jaccard_ops |
Why <#> is negative: the README says "<#> returns the negative inner product since Postgres only supports ASC order index scans on operators". Multiply by -1 to display the real value. Cosine similarity is 1 - (embedding <=> query).
Fix / how to use it:
-- Same ranking when vectors are unit length; inner product is the cheapest.
SELECT id, (embedding <#> :q) * -1 AS inner_product
FROM documents ORDER BY embedding <#> :q LIMIT 10;
-- Show similarity, but ORDER BY the bare operator so the index can be used.
SELECT id, 1 - (embedding <=> :q) AS cosine_similarity
FROM documents ORDER BY embedding <=> :q LIMIT 10;
-- This ORDER BY is an expression, not a distance operator: no index scan.
-- ... ORDER BY 1 - (embedding <=> :q) DESC LIMIT 10;// Normalising once at write time lets you use <#> everywhere.
func l2Normalize(v []float32) {
var sum float64
for _, x := range v {
sum += float64(x) * float64(x)
}
n := float32(math.Sqrt(sum))
if n == 0 {
return
}
for i := range v {
v[i] /= n
}
}// Laravel: whereVectorSimilarTo is cosine-based. For another metric or for the
// distance value, use selectVectorDistance / orderByVectorDistance.
Document::query()
->select('*')
->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
->orderByVectorDistance('embedding', $queryEmbedding)
->limit(10)
->get();Exact kNN vs ANN, and the recall/latency trade-off Must-know
In plain words: Exact search looks at every row and is always right; approximate search looks at a clever subset and is usually right, much faster. The share of the true top-k that approximate search finds is its recall.
Common misunderstanding: "Recall is a property of the index type, so HNSW has 99% recall." Recall is a number you measure on your data, for your query distribution, at your parameter values. The same HNSW index gave 0.67, 0.83, 0.94, 0.99 and 0.999 recall in the lab as ef_search went 10, 20, 40, 100, 200.
Definition: Exact kNN (also called brute force or a flat index) returns the true k nearest rows by computing every distance. ANN returns k rows that are close but not guaranteed to be the closest. recall@k = |approx top-k AND exact top-k| / k, averaged over many queries. The trade-off curve is recall versus latency (and memory, build time) as the search-effort knob (ef_search, probes) rises.
1 exact: query -> compute distance to all N rows -> keep k smallest recall 1.00
2 HNSW: query -> top layer -> hop -> drop -> ... -> layer 0, ef_search candidates
3 IVFFlat: query -> nearest `probes` centroids -> scan only those lists
4 recall@10 = |approx ∩ exact| / 10 , averaged over 100 queries
5 lab (100k x 64-d, cosine): ef_search 10 -> 0.67 40 -> 0.94 200 -> 0.999
6 latency 0.3 ms 0.7 ms 2.0 ms (exact: ~5 ms)Real scenario: A recommendation widget tolerates 0.90 recall to stay under 20 ms; a legal-discovery tool wants 0.99 and pays for it; a deduplication job uses exact search nightly because it runs offline.
What provides it:
| Engine | Exact path | Approximate path |
|---|---|---|
| PostgreSQL + pgvector | Default: sequential scan with ORDER BY ... LIMIT (parallelisable with max_parallel_workers_per_gather) | hnsw, ivfflat indexes |
| Elasticsearch | "Exact, brute-force kNN" (script_score) | "Approximate kNN" with k and num_candidates |
| Redis vector sets | VSIM ... TRUTH forces a linear scan | HNSW (default) |
| Qdrant, Milvus, Weaviate, Vespa, Pinecone | Flat / brute-force index or exact flag (general knowledge) | HNSW and others |
Elastic's documentation: "Exact, brute-force kNN is best for small datasets, pre-filtered subsets, or when you need precise scoring without approximate indexing." and "Approximate kNN is best for most production workloads where low latency and scale matter more than perfect recall."
Fix / how to use it: keep an exact baseline permanently.
-- Exact search inside one transaction: the index is ignored, nothing else changes.
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM documents ORDER BY embedding <=> :q LIMIT 10;
COMMIT;// recallAtK compares an approximate id list with the exact one (see fusion.RecallAtK).
recall := fusion.RecallAtK(exactIDs, approxIDs, 10)// A scheduled job can compute recall for a sample of queries and alert below a floor.
$hits = count(array_intersect($exactIds, $approxIds));
$recall = $hits / max(1, count($exactIds));HNSW Must-know
In plain words: HNSW is a road map with several levels of detail. The top level has a few points and long roads, the bottom level has every point and short roads. You enter at the top, get close fast, then refine on the lower levels.
Common misunderstanding: "ef_search is the number of results." It is the size of the candidate list kept while searching; you still get LIMIT rows back. If ef_search is below LIMIT, you cannot get LIMIT rows (pgvector caps results by the candidate list: "Results are limited by the size of the dynamic candidate list (hnsw.ef_search), which is 40 by default").
Definition: A Hierarchical Navigable Small World graph. Each vector is assigned a top layer at random with exponentially decaying probability. On each layer it is linked to up to m neighbours (the bottom layer allows more). Insert: descend greedily to the new vector's layer, then on every layer from there down find ef_construction candidates and link to the best m using a diversity heuristic. Search: enter at the top, greedy-descend with one candidate per layer, and on layer 0 run a best-first search with a candidate list of ef_search.
1 CREATE INDEX ... USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
2 insert x: level = floor(-ln(random()) * mL) -- exponential decay
3 descend from the entry point to level(x) -- greedy, 1 candidate
4 for each layer <= level(x): search ef_construction, link x to best m
5 query q: descend greedily from the top layer to layer 1
6 layer 0: keep ef_search candidates, expand the closest unexpanded one
7 stop when no candidate improves the list; return k nearest of the listReal scenario: The default choice for a RAG store that fits in RAM; a product catalogue with 5 million items under a 20 ms budget; a table that receives continuous inserts and cannot be rebuilt nightly.
What prevents / provides it: the knobs and their costs.
| Knob | Default | Where | Raising it | Cost |
|---|---|---|---|---|
m | 16 | CREATE INDEX ... WITH (m = ...) | More links, better recall ceiling | Bigger index, slower build and queries |
ef_construction | 64 | CREATE INDEX ... WITH (...) | Better graph: "better recall at the cost of index build time / insert speed" | Slower build and inserts |
hnsw.ef_search | 40 | SET (session) or SET LOCAL (transaction); valid range 1 to 1000 | Better recall | Slower queries |
maintenance_work_mem | server setting | build time | Graph fits in memory: "Indexes build significantly faster when the graph fits" | RAM on the server |
max_parallel_maintenance_workers | 2 | build time | Parallel build | CPU, shared memory |
Fix / how to use it:
CREATE INDEX documents_embedding_hnsw
ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT id FROM documents ORDER BY embedding <=> :q LIMIT 10;
COMMIT;// SET LOCAL inside a transaction: the pooled connection is not left changed.
func withEfSearch(ctx context.Context, db *sql.DB, ef int, fn func(*sql.Tx) error) error {
tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL hnsw.ef_search = %d", ef)); err != nil {
return err
}
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}// Laravel: wrap the query so SET LOCAL ends with the transaction.
DB::transaction(function () use ($tenantId, $embedding) {
DB::statement('SET LOCAL hnsw.ef_search = 100');
return Document::query()->whereVectorSimilarTo('embedding', $embedding)->limit(10)->get();
});IVFFlat Important
In plain words: IVFFlat sorts all vectors into a fixed number of buckets (lists) by which centre they are closest to. A query looks into the few buckets nearest to it and ignores the rest.
Common misunderstanding: "Create the index first, load data later." IVFFlat's centroids come from k-means over the rows present at build time. An index built on an empty or tiny table has bad centroids, and pgvector's FAQ says to drop it and rebuild: "The index was likely created with too little data for the number of lists."
Definition: An inverted-file index with flat (uncompressed) storage. Build: run k-means to find lists centroids, assign each vector to its nearest centroid. Query: find the probes nearest centroids and compute exact distances inside those lists. probes = lists is exact and the planner then stops using the index.
1 CREATE INDEX ... USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
2 phases (pg_stat_progress_create_index): initializing -> performing k-means -> assigning tuples -> loading tuples
3 query q: distance q to 100 centroids -> take the nearest `probes`
4 probes=1 -> scan ~1% of rows recall 0.26 (lab)
5 probes=10 -> scan ~10% of rows recall 0.84
6 probes=30 -> scan ~30% of rows recall 0.99
7 probes=100 = lists -> exactReal scenario: A nightly-rebuilt catalogue where build time and memory matter more than the last bit of recall; a very large table (the README suggests sqrt(rows) lists above 1M rows) that has to be built on a smaller machine.
What provides it:
| Knob | Default / rule | Effect |
|---|---|---|
lists | start at rows / 1000 up to 1M rows, sqrt(rows) above | More lists: faster queries at a given recall, worse recall at probes = 1 |
ivfflat.probes | 1; start at sqrt(lists) | More probes: better recall, slower |
ivfflat.iterative_scan | off; relaxed_order | Keep probing when a filter leaves too few rows |
ivfflat.max_probes | 32768 | Upper bound for iterative scans (if lower than probes, probes is used) |
| Training data | Create the index after the table has some data (README, first of its three keys) | Bad centroids otherwise |
Fix / how to use it:
-- After loading data. 100,000 rows -> lists = 100.
CREATE INDEX documents_embedding_ivf
ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
BEGIN;
SET LOCAL ivfflat.probes = 10; -- about sqrt(lists)
SELECT id FROM documents ORDER BY embedding <=> :q LIMIT 10;
COMMIT;// Rebuild when the data has drifted: a concurrent reindex does not block writes.
_, err := db.ExecContext(ctx, `REINDEX INDEX CONCURRENTLY documents_embedding_ivf`)DB::statement('REINDEX INDEX CONCURRENTLY documents_embedding_ivf');Quantization: scalar, product, binary, and halfvec Important
In plain words: Quantization stores each number with fewer bits so the vectors take less memory and compare faster, at the price of some accuracy. You then often re-check the best candidates with the full-precision vectors.
Common misunderstanding: "Quantization is free compression." It is lossy. Binary quantization of a 64-dimensional vector (as in the lab) lost most of the ranking information; it is meant for high-dimensional embeddings and for producing a shortlist that is re-ranked with the original vectors.
Definition:
- Half precision (
halfvec): 16-bit floats instead of 32-bit; half the memory. pgvector supports it as a column type and as an expression index over avectorcolumn. - Scalar quantization (SQ): map each float to an 8-bit (or 4-bit) integer using a per-dimension range; 4 times smaller than float32. Redis vector sets use
Q8by default. - Product quantization (PQ): split the vector into
msub-vectors, learn a codebook (typically 256 centroids) per sub-vector, store one byte per sub-vector; distances come from lookup tables. A 1536-float vector (6144 bytes) can shrink to a few dozen bytes. Used by Milvus (IVF_PQ), Weaviate and Qdrant (general knowledge); pgvector does not implement PQ. - Binary quantization (BQ): one bit per dimension (the sign), compared with Hamming distance; 32 times smaller than float32. pgvector:
binary_quantize(embedding)::bit(n)withbit_hamming_ops. pgvectorscale uses Statistical Binary Quantization (SBQ); its README says "This compression method improves on standard Binary Quantization". It usesnum_bits_per_dimension2 for under 900 dimensions and 1 otherwise.
1 float32 vector(1536) 6152 bytes exact baseline
2 halfvec(1536) 3080 bytes 2x smaller (2*1536 + 8)
3 int8 scalar (Q8) ~1536 bytes 4x smaller (Redis vector sets default)
4 PQ, 96 sub-vectors ~96 bytes ~64x smaller (typical, engine-specific)
5 bit(1536) binary 200 bytes ~31x smaller (1536/8 + 8)
6 search: shortlist on the small codes (e.g. 100) -> re-rank with float vectors -> top 10Real scenario: 50 million 768-dimensional vectors will not fit a single machine's RAM at float32 (about 150 GB for the data alone); a binary index with re-ranking keeps the graph in memory and the full vectors on disk.
What provides it:
| Engine | Half | Scalar | Product | Binary |
|---|---|---|---|---|
| pgvector 0.8.7 | halfvec type and expression index | no | no | binary_quantize(), bit + Hamming/Jaccard, re-rank query |
| pgvectorscale | via pgvector | no | no | SBQ inside StreamingDiskANN (storage_layout = memory_optimized) |
| Redis vector sets | no | Q8 (default) | no | BIN |
| Qdrant, Milvus, Weaviate | general knowledge: scalar, product and binary quantization are all available (names and options differ) | |||
| Elasticsearch | quantized dense_vector index options (int8, int4, BBQ in recent versions); check your version |
Fix / how to use it (from the pgvector README):
-- Index half precision while keeping the full vector in the table.
CREATE INDEX ON documents USING hnsw ((embedding::halfvec(1536)) halfvec_cosine_ops);
SELECT id FROM documents ORDER BY embedding::halfvec(1536) <=> :q::halfvec(1536) LIMIT 10;
-- Binary quantization with re-ranking by the original vectors.
CREATE INDEX ON documents USING hnsw ((binary_quantize(embedding)::bit(1536)) bit_hamming_ops);
SELECT * FROM (
SELECT * FROM documents
ORDER BY binary_quantize(embedding)::bit(1536) <~> binary_quantize(:q::vector)
LIMIT 100
) shortlist
ORDER BY embedding <=> :q LIMIT 10;// The shortlist size is a recall knob: 10 in the lab gave 0.13, 200 gave 0.55 on 64-d data.
const shortlist = 100DB::select(<<<'SQL'
SELECT * FROM (
SELECT * FROM documents
ORDER BY binary_quantize(embedding)::bit(1536) <~> binary_quantize(?::vector) LIMIT 100
) s ORDER BY embedding <=> ?::vector LIMIT 10
SQL, [$literal, $literal]);DiskANN and pgvectorscale StreamingDiskANN Good to know
In plain words: DiskANN is a graph index built so that the big part of the data can sit on SSD instead of RAM, with a small compressed copy in memory to steer the search.
Common misunderstanding: "StreamingDiskANN is a pgvector index type." It is not part of pgvector; it comes from the separate pgvectorscale extension (CREATE EXTENSION vectorscale) and works alongside pgvector's vector type.
Definition: DiskANN builds a single-layer navigable graph (Vamana) with pruning controlled by an alpha parameter, aimed at SSD-resident datasets. pgvectorscale's README describes "a new index type called StreamingDiskANN, inspired by the DiskANN algorithm", "Statistical Binary Quantization" and "label-based filtered vector search" based on Microsoft's Filtered DiskANN research.
1 CREATE EXTENSION vectorscale CASCADE; -- also installs pgvector
2 CREATE INDEX ON documents USING diskann (embedding vector_cosine_ops);
3 CREATE INDEX ON documents USING diskann (embedding vector_cosine_ops, labels); -- labels smallint[]
4 SELECT ... WHERE labels && ARRAY[1,3] ORDER BY embedding <=> :q LIMIT 10;
5 SET diskann.query_rescore = 400; -- rescore more candidates with full vectorsReal scenario: A corpus of tens of millions of embeddings on a single Postgres server where HNSW's memory use is the problem; a multi-tenant catalogue where the tenant is a small integer label.
What provides it:
| Parameter | Default (README) | Meaning |
|---|---|---|
storage_layout | memory_optimized | SBQ-compressed vectors, or plain for uncompressed |
num_neighbors | 50 | Max neighbours per node (like HNSW m) |
search_list_size | 100 | Build-time search list (S) |
max_alpha | 1.2 | Graph pruning alpha |
num_dimensions | 0 (all) | Index fewer dimensions (Matryoshka embeddings) |
num_bits_per_dimension | 2 under 900 dims, else 1 | SBQ bits |
diskann.query_search_list_size | 100 | Query-time candidate list |
diskann.query_rescore | 50 | Elements rescored with full vectors (0 disables) |
The pgvectorscale README reports, for 50 million Cohere 768-dimensional embeddings at 99% recall, "28x lower p95 latency" and "16x higher query throughput" than Pinecone's storage-optimized index, "all at 75% less cost when self-hosted on AWS EC2". That is the vendor's own benchmark, so reproduce it on your data before relying on it. The same README notes that for arbitrary WHERE conditions "the vector search happens first, and then the WHERE conditions are applied to the results"; only the label mechanism is filter-aware.
Fix / how to use it: see the SQL in the timeline above; from Go or Laravel it is ordinary SQL (the index type is chosen in the migration, the query is the same ORDER BY embedding <=> $1 LIMIT k).
Metadata filtering and the post-filter problem Must-know
In plain words: "Find the nearest documents, but only for tenant 7" sounds like one step. With an approximate index it is two: the index hands back its nearest candidates, and then the filter throws away those that are not tenant 7. If few survive, you get few rows.
Common misunderstanding: "If the query has LIMIT 10, I will get 10 rows." Not with a post-filter. The README's example: if a condition matches 10% of rows, "with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average". Postgres does not raise an error; it returns fewer rows.
Definition: Post-filtering applies the predicate after the ANN index returns candidates. Pre-filtering applies it before or during traversal. pgvector's HNSW and IVFFlat are post-filtering (plus iterative scans since 0.8.0). Filterable-graph engines (Qdrant, Vespa, Weaviate, Redis vector sets with FILTER, pgvectorscale labels) integrate the predicate into the search.
1 SELECT id FROM docs WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10;
2 plan: Limit -> Index Scan using docs_hnsw Filter: (tenant_id = 7) Rows Removed by Filter: 40
3 HNSW returned ef_search = 40 candidates; 40 were removed; 0 rows returned
4 lab: 1% filter -> 0.4 rows on average per query; 5% filter -> 2.1 rows (the README's arithmetic predicts 0.4 and 2)
5 a 0.1% filter (99 of 100,000 rows) returned 0.0 rows per query on average (recall 0.004)Real scenario: Per-tenant search in a SaaS app; "only published documents"; "only this product category"; permission filters (ACLs); a language filter; a date range.
What prevents it / what provides it:
| Fix | How | Advantage | Cost / limit |
|---|---|---|---|
| Index on the filter column | CREATE INDEX ON docs (tenant_id) | Postgres can scan matching rows exactly ("fast, exact nearest neighbor search in many cases") | Only wins when the filter is selective; the planner may still choose HNSW |
| Iterative index scan | SET hnsw.iterative_scan = relaxed_order | Keeps scanning until enough rows pass | Slower for very selective filters; bounded by hnsw.max_scan_tuples |
| Partial index | CREATE INDEX ... USING hnsw (...) WHERE (category_id = 123) | Smallest, fastest, exact filter | One index per value; the query must repeat the predicate |
| Partitioning | PARTITION BY LIST (tenant_id) | Planner prunes to one partition and uses its own index | Many partitions means many indexes; see partitioning |
Raise ef_search | SET LOCAL hnsw.ef_search = 400 | More candidates survive | Slower; a blunt tool |
| Filterable engine | Qdrant, Vespa, Weaviate, pgvectorscale labels | Filter-aware traversal | Another system or extension |
Fix / how to use it:
-- 1. Check the symptom: fewer rows than LIMIT.
SELECT count(*) FROM (SELECT 1 FROM docs WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10) t;
-- 2. Turn on iterative scans for this transaction.
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
SELECT id FROM docs WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10;
COMMIT;// pgxsearch.SearchTenant: SET LOCAL hnsw.iterative_scan inside a read-only transaction.
hits, err := pgxsearch.SearchTenant(ctx, pool, 7, query, 10, 100)// TenantSearch::search(): DB::transaction + SET LOCAL + whereVectorSimilarTo.
$chunks = (new TenantSearch)->search(tenantId: 7, queryEmbedding: $embedding, limit: 10);Iterative index scans (pgvector 0.8) Important
In plain words: When the filter leaves too few rows, an iterative scan simply asks the index for more candidates, again and again, until it has enough or hits a safety limit.
Common misunderstanding: "Iterative scans make filtered search exact." They improve recall for filtered queries, but the search is still approximate and still bounded: it stops at hnsw.max_scan_tuples (20,000 by default) or ivfflat.max_probes. A very selective filter can still return fewer than LIMIT rows.
Definition: Since 0.8.0, setting hnsw.iterative_scan to strict_order or relaxed_order (or ivfflat.iterative_scan = relaxed_order) lets the index scan continue. strict_order returns results in exact distance order; relaxed_order allows slightly out-of-order results but gives better recall, and strict order can be restored with a materialized CTE.
1 SET hnsw.iterative_scan = relaxed_order; -- off | relaxed_order | strict_order
2 SET hnsw.max_scan_tuples = 20000; -- stop after visiting this many tuples
3 SET hnsw.scan_mem_multiplier = 2; -- memory allowance, multiple of work_mem (default 1)
4 SET ivfflat.max_probes = 100; -- upper bound for IVFFlat iteration
5 lab, tenant_id = 7 (1%): off -> 0.4 rows relaxed -> 10 rows, recall 0.995 strict -> 10 rows, recall 0.959Real scenario: The multi-tenant query above; "published only" filters that match 30% of rows; date-range filters.
What provides it:
| Setting | Values / default | Notes |
|---|---|---|
hnsw.iterative_scan | off (default), relaxed_order, strict_order | Lab: both about 6 ms; recall 0.995 (relaxed) vs 0.959 (strict) |
hnsw.max_scan_tuples | 20,000 | "approximate and does not affect the initial scan" |
hnsw.scan_mem_multiplier | 1 | Increase if raising max_scan_tuples does not improve recall |
ivfflat.iterative_scan | off, relaxed_order | IVFFlat has no strict mode |
ivfflat.max_probes | 32768 | Ignored if lower than ivfflat.probes |
Fix / how to use it: strict ordering from a relaxed scan, from the README:
WITH relaxed_results AS MATERIALIZED (
SELECT id, embedding <-> :q AS distance FROM items WHERE category_id = 123 ORDER BY distance LIMIT 5
) SELECT * FROM relaxed_results ORDER BY distance + 0; -- "+ 0 is needed for Postgres 17+"// In Go the settings are plain statements inside the transaction (pgxsearch.SearchTenant).
_, err := tx.Exec(ctx, "SET LOCAL hnsw.iterative_scan = relaxed_order")DB::statement('SET LOCAL hnsw.iterative_scan = relaxed_order');Partitioning, partial indexes and multi-tenancy Important
In plain words: If every tenant has its own slice of the table (a partition), the nearest-neighbour search only ever sees that tenant's vectors, so a big tenant cannot crowd out a small one and a filter is no longer needed.
Common misunderstanding: "One shared HNSW index is fine for all tenants." The README warns: "sharing an approximate index between tenants means vectors from one tenant can affect recall (and speed) for other tenants." The graph is built over everyone.
Definition: For tenant isolation pgvector recommends list partitioning or separate tables. An ANN index defined on a partitioned table is created per partition (Postgres creates a matching index on each partition, as the lab's \d p1 shows). Partitioning by a low-cardinality filter value also solves the post-filter problem for that value.
1 CREATE TABLE chunks (tenant_id int NOT NULL, id bigint, embedding vector(1536)) PARTITION BY LIST (tenant_id);
2 CREATE TABLE chunks_t7 PARTITION OF chunks FOR VALUES IN (7);
3 CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops); -- one index per partition
4 SELECT id FROM chunks WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10;
5 plan: only chunks_t7 is scanned (partition pruning) and its own HNSW index is usedReal scenario: 50 enterprise tenants with very different sizes: list-partition the big ones and share a default partition for the long tail; per-region data residency; a tenant deleted in one DROP TABLE.
What provides it:
| Strategy | Isolation of recall/speed | Operational cost | Good for |
|---|---|---|---|
Shared table + shared index + WHERE tenant_id + iterative scan | Weak | Lowest | Many small tenants, soft isolation |
| Shared table + partial HNSW per big tenant | Good for those tenants | One index per tenant | A handful of large tenants |
| List partitions per tenant (index per partition) | Strong | Catalog and planning cost grows with partitions; thousands is heavy | Tens to low thousands of tenants |
| Table or schema or database per tenant | Strongest | Highest (see Multi-Tenancy) | Compliance-driven isolation |
Pinecone namespaces, Weaviate multi-tenancy, Qdrant payload partitioning (is_tenant) | Engine-provided | Managed by the engine | Dedicated engines (general knowledge) |
Fix / how to use it:
-- A partial index is a cheap way to give one hot tenant its own graph.
CREATE INDEX chunks_t7_hnsw ON chunks USING hnsw (embedding vector_cosine_ops) WHERE (tenant_id = 7);
-- The query must contain the same predicate for the planner to use it.
SELECT id FROM chunks WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10;// Create a partition for a new tenant in the onboarding flow.
_, err := db.ExecContext(ctx, fmt.Sprintf(
"CREATE TABLE IF NOT EXISTS chunks_t%d PARTITION OF chunks FOR VALUES IN (%d)", tenantID, tenantID))// tenantId is an int from your own tenant table, never user text.
DB::statement(sprintf('CREATE TABLE IF NOT EXISTS chunks_t%1$d PARTITION OF chunks FOR VALUES IN (%1$d)', $tenantId));Hybrid search: BM25 plus vectors, and RRF Important
In plain words: Keyword search is great when the exact word matters (a product code, an error number) and vector search is great when the meaning matters. Hybrid search runs both and merges the two ranked lists.
Common misunderstanding: "Just add the BM25 score and the cosine similarity." The two scores live on different scales and distributions, so a weighted sum needs per-query normalisation and tuning. Rank-based fusion avoids the problem because it only uses positions.
Definition: Hybrid search combines a lexical retriever (BM25 in Lucene-based engines; tsvector with ts_rank_cd in PostgreSQL, which is not BM25) with a vector retriever, usually followed by fusion and optionally a cross-encoder reranker. Reciprocal Rank Fusion scores a document by sum of 1 / (k + rank) over the lists it appears in; the original paper fixed k = 60.
1 query: "topic9 note7" (lab: exact tokens the vector model would blur)
2 semantic list : id 57663 rank 1, 99978 rank 2, 71320 rank 3, ...
3 keyword list : id 7 rank 1, 107 rank 2, ...
4 RRF(57663) = 1/(60+1) = 0.01639 RRF(7) = 1/(60+1) = 0.01639 RRF(99978) = RRF(107) = 0.01613
5 fused order: 7, 57663, 99978, 107, 71320 -> a document strong in either list surfacesReal scenario: Support search where users paste an error code and also ask vague questions; e-commerce search mixing SKU matches with "something to keep drinks cold"; legal search with citations plus concepts.
What provides it:
| Engine | Lexical side | Fusion |
|---|---|---|
| PostgreSQL | tsvector + ts_rank_cd (not BM25); BM25 through extensions (for example ParadeDB pg_search; general knowledge) | You write RRF in SQL (below); pgvector README links an RRF example and a cross-encoder example |
| Elasticsearch / OpenSearch | BM25 in Lucene | Elasticsearch has an RRF retriever; OpenSearch has hybrid queries with score normalisation (general knowledge, check your version) |
| Weaviate | BM25F | Built-in hybrid with rank or score fusion (general knowledge) |
| Qdrant, Milvus | sparse vectors / BM25-style | Built-in rank fusion such as RRF (general knowledge) |
| Vespa | bm25 rank feature | Ranking profiles combine features (general knowledge) |
| Pinecone | sparse-dense vectors | Weighted combination (general knowledge) |
Fix / how to use it:
-- Validated in the lab: both branches filter the same way; fusion happens in SQL.
WITH semantic AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> :'q') AS rnk
FROM docs ORDER BY embedding <=> :'q' LIMIT 40
), keyword AS (
SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, query) DESC) AS rnk
FROM docs, websearch_to_tsquery('simple', 'topic9 note7') AS query
WHERE tsv @@ query
ORDER BY ts_rank_cd(tsv, query) DESC LIMIT 40
)
SELECT coalesce(s.id, k.id) AS id,
coalesce(1.0 / (60 + s.rnk), 0) + coalesce(1.0 / (60 + k.rnk), 0) AS rrf
FROM semantic s FULL OUTER JOIN keyword k ON k.id = s.id
ORDER BY rrf DESC LIMIT 10;// fusion.RRF merges any number of ranked id lists (k = 60).
fused := fusion.RRF(60, semanticIDs, keywordIDs)// HybridSearch::search(): the same SQL with a tenant filter on both branches.
$rows = (new HybridSearch)->search(tenantId: 7, query: 'reset password error 0x80070005');Index freshness: inserts, updates, deletes and vacuum Important
In plain words: A vector in Postgres is a row like any other: you insert it, it is in the index at commit, and an update creates a new row version. Dedicated engines may make new data searchable only after a refresh or segment merge.
Common misunderstanding: "An ANN index is a snapshot I rebuild occasionally." pgvector HNSW and IVFFlat are maintained on every write. What does drift is quality: IVFFlat centroids were chosen for the data at build time, and HNSW leaves dead entries behind after deletes until vacuum cleans them.
Definition: pgvector participates in normal MVCC: indexes are WAL-logged ("pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery") and visible to the transaction that wrote them. Deleted and updated rows leave dead index entries until VACUUM. The README notes that "Vacuuming can take a while for HNSW indexes. Speed it up by reindexing first." and that NULL vectors (and zero vectors under cosine) are not indexed. See MVCC, VACUUM & Bloat.
1 T1 INSERT INTO docs (...) VALUES (...); COMMIT; -- searchable immediately, index updated
2 T2 UPDATE docs SET embedding = :new WHERE id = 5; -- new row version, new index entry; old one is dead
3 T3 DELETE FROM docs WHERE id = 9; -- dead tuple, still in the graph until VACUUM
4 after many deletes: fewer than ef_search live candidates -> "fewer rows than LIMIT"
5 fix: REINDEX INDEX CONCURRENTLY docs_hnsw; VACUUM docs; -- reindex first, then vacuum is fastReal scenario: Chat history that is embedded as it arrives; a catalogue whose descriptions are edited daily; GDPR deletions that must disappear from search at once (they do, at commit, as MVCC hides the row even though the graph still contains it).
What provides it:
| Engine | When is new data searchable | Delete behaviour |
|---|---|---|
| PostgreSQL + pgvector | At commit | Dead tuples until VACUUM; HNSW results can shrink until then |
| Elasticsearch / OpenSearch | After a refresh (default about 1 second) | Soft deletes until a segment merge (general knowledge) |
| Qdrant, Milvus, Weaviate | Near real time; some use a write-ahead log and a growing segment before indexing (general knowledge) | Tombstones, compaction |
| Redis vector sets | Immediately (VADD) | VREM |
| Pinecone | Freshness is eventual; check the current service docs |
Fix / how to use it:
-- Bulk loads: COPY first, build the index afterwards, build it concurrently in production.
COPY docs (id, tenant_id, embedding) FROM STDIN WITH (FORMAT BINARY);
CREATE INDEX CONCURRENTLY docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops);// Upsert keeps the vector and the model name together (pgxsearch.Upsert).
err := pgxsearch.Upsert(ctx, pool, 42, "text-embedding-3-small@1536", vec)// updateOrCreate is an upsert; the cast converts the PHP array to a vector.
DocumentChunk::updateOrCreate(['document_id' => 1, 'position' => 0], ['embedding' => $vector]);Embedding model versioning and re-indexing Must-know
In plain words: Vectors from two different models (or two versions of the same model) live in different spaces, so you cannot compare them. When you change the model you must re-embed everything and build a new index.
Common misunderstanding: "I will just switch the query embedding to the new model; old rows still work." The distances become meaningless: results are silently wrong, no error. Even the same model name served by a different provider can differ.
Definition: The model identity (name, version, dimension, normalisation, and any truncation) is part of the data. A zero-downtime change is a blue/green migration: a new column or table, a backfill, a new index, a read switch, then removal of the old column.
1 T0 documents.embedding_model = 'model-a@1536' for all rows; HNSW index A
2 T1 ALTER TABLE documents ADD COLUMN embedding_v2 vector(1024); -- or a new table
3 T2 backfill in batches: WHERE embedding_v2 IS NULL ORDER BY id LIMIT 500 (idempotent, resumable)
4 T3 CREATE INDEX CONCURRENTLY ... (embedding_v2 vector_cosine_ops)
5 T4 dual-read check: compare overlap of top-10 old vs new on sample queries
6 T5 switch the read path behind a flag; new writes embed with both models until T6
7 T6 DROP INDEX old; ALTER TABLE documents DROP COLUMN embedding;Real scenario: Moving from a 1536-dimension hosted model to a 1024-dimension open model to cut cost; a provider retires a model; adding a multilingual model for a new market.
What provides it:
| Approach | How | Cost |
|---|---|---|
Column per model (embedding_v2) | Same table, two indexes during the migration | Double storage during the switch |
| Table per model | document_chunks_v2, swap the repository | Joins needed; clean drop at the end |
One column without a fixed dimension plus a model_id and partial expression indexes | pgvector FAQ: embedding vector without (n), CREATE INDEX ... USING hnsw ((embedding::vector(3)) vector_l2_ops) WHERE (model_id = 123) | Query must repeat WHERE model_id = ... and the cast |
| Dedicated engines | Collection per model; aliases to swap | Engine-specific (general knowledge) |
Fix / how to use it:
-- Rows still on the old model:
SELECT count(*) FROM document_chunks WHERE embedding_model <> 'text-embedding-3-small@1536';
-- Batch to re-embed:
SELECT id, content FROM document_chunks WHERE embedding_model <> :model ORDER BY id LIMIT 500;// A resumable backfill loop: select a batch, embed it, update with the new model name.
for {
ids, texts := nextBatch(ctx, db, newModel, 500) // WHERE embedding_model <> $1
if len(ids) == 0 {
break
}
vecs, err := embed.OpenAI(ctx, apiKey, newModel, 1536, texts)
if err != nil {
return err
}
for i, id := range ids {
if err := pgxsearch.Upsert(ctx, pool, id, newModel, vecs[i]); err != nil {
return err
}
}
}// EmbedDocument::MODEL is bumped and the job is dispatched for every document.
Document::query()->select('id')->chunkById(500, fn ($docs) =>
$docs->each(fn (Document $d) => EmbedDocument::dispatch($d->id)));Chunking strategies for RAG Important
In plain words: Embedding a whole book gives one blurry point. Splitting it into passages gives one sharp point per passage, so a question can land on the passage that answers it.
Common misunderstanding: "Smaller chunks are always more precise." Very small chunks lose context ("it was approved" with no subject); very large ones dilute meaning and exceed the model's input limit. Chunk size is a tuned parameter, evaluated with recall@k on real questions.
Definition: A chunking strategy decides the unit of retrieval. Common ones: fixed-size windows (by tokens or characters) with overlap; sentence or paragraph boundaries; structure-aware (split at headings, keep the heading path as metadata); recursive splitting (try paragraph, then sentence, then word); semantic chunking (split where the embedding similarity of neighbouring sentences drops); parent-child ("small-to-big": retrieve a small chunk, return its larger parent); and contextual chunk prefixes (prepend the document title or a summary to each chunk before embedding). Typical sizes are a few hundred tokens with 10 to 20 percent overlap; treat that as a starting point, not a rule.
1 document (12 pages) --> split by heading --> sections
2 section --> window 1500 chars, overlap 200, cut at paragraph/sentence --> chunks
3 each chunk row: tenant_id, document_id, position, content, heading_path, embedding, embedding_model
4 query -> top 8 chunks -> (optional) expand to parent section -> prompt contextReal scenario: Help-centre articles chunked by heading; contracts chunked by clause with the clause number as metadata; code chunked by function; meeting transcripts chunked by speaker turn windows.
What provides it:
| Strategy | Strength | Weakness |
|---|---|---|
| Fixed window + overlap | Simple, predictable size | Cuts sentences, ignores structure |
| Sentence/paragraph | Natural units | Uneven sizes |
| Structure-aware (headings, clauses, functions) | Keeps meaning and gives metadata | Needs a parser per format |
| Semantic | Boundaries follow topic shifts | Extra embedding calls, tuning |
| Parent-child | Precise match, wide context | Two lookups, more storage |
The full retrieval pipeline (prompting, citation, evaluation harness) is covered in RAG & LLM apps in Go.
Fix / how to use it:
// Fixed windows with overlap, in runes so multi-byte text is not cut mid-character.
func chunk(text string, size, overlap int) []string {
r := []rune(text)
var out []string
for start := 0; start < len(r); {
end := min(start+size, len(r))
out = append(out, string(r[start:end]))
if end == len(r) {
break
}
start = end - overlap
}
return out
}// EmbedDocument::chunk() cuts at paragraph or sentence boundaries when one is near.Evaluation: recall@k and relevance Must-know
In plain words: You need two kinds of score. One says how faithfully the index reproduces the exact answer (recall). The other says whether the exact answer is what the user wanted (relevance). Fixing the second by tuning the first does nothing.
Common misunderstanding: "99% recall means the search is 99% good." It means the index returns 99% of what exact search would return. If exact search returns irrelevant passages, you have a 99% faithful copy of a bad result.
Definition: Index quality: recall@k against an exact baseline. Retrieval quality: judged question/answer sets scored with hit rate@k, MRR (mean reciprocal rank of the first relevant result) and nDCG (graded relevance with position discount). Latency: p50, p95 and p99 at a given concurrency. Build metrics: time, memory, index size.
1 sample 100-1000 real queries; store them
2 exact top-k (index off) -> ground truth ids
3 approximate top-k at each setting (ef_search, probes, quantization)
4 recall@10 = |approx ∩ exact| / 10 -- index faithfulness
5 hit@10, MRR, nDCG on a labelled set -- retrieval quality
6 plot recall vs p95 latency, choose the cheapest point above the floorReal scenario: A nightly job runs 200 stored queries, compares with exact search, and pages someone if recall@10 drops under 0.95 after a data load; a model upgrade is accepted only if MRR on the labelled set rises.
What provides it:
| Metric | Measures | Needs labels | Tool |
|---|---|---|---|
| recall@k | ANN vs exact | No | SQL with enable_indexscan = off, or fusion.RecallAtK |
| hit rate@k | Right document in top k | Yes | Labelled queries |
| MRR | Rank of first right result | Yes | Labelled queries |
| nDCG@k | Graded relevance with position discount | Yes (graded) | Labelled queries |
| p50/p95/p99 latency | Speed under load | No | EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements, a load tool |
Fix / how to use it: the README's own monitoring advice: "Monitor recall by comparing results from approximate search with exact search."
BEGIN;
SET LOCAL enable_indexscan = off; -- use exact search
SELECT id FROM docs ORDER BY embedding <=> :q LIMIT 10;
COMMIT;fmt.Printf("recall@10 = %.3f\n", fusion.RecallAtK(exact, approx, 10))$recall = count(array_intersect($exact, $approx)) / max(1, count($exact));The cost of dimensions Important
In plain words: Every extra dimension is four more bytes per vector in the table, four more in the index, more arithmetic per distance and more memory traffic per query.
Common misunderstanding: "Storage is cheap, so use the biggest model." The RAM needed to keep an HNSW index hot, not the disk, usually sets the cost, and query latency scales with dimension too.
Definition: Memory for raw vectors is N * (4 * d + 8) bytes in pgvector (vector); an HNSW index stores another copy plus the graph. A vector whose tuple exceeds about 2 KB is moved out of line (TOAST); the README advises STORAGE PLAIN where it fits, because TOAST adds a lookup per row.
1 N = 1,000,000 vectors
2 d = 384 -> 4*384+8 = 1,544 B -> 1.5 GB raw (+ index copy and graph)
3 d = 1536 -> 4*1536+8 = 6,152 B -> 6.2 GB raw (HNSW indexes at most 2000 dims)
4 d = 3072 -> 12,296 B -> 12.3 GB raw (needs halfvec 6,152 B to index; max 4000)
5 halfvec(1536) = 3,080 B -> 3.1 GB; bit(1536) = 200 B -> 0.2 GB
6 lab: 100k x 64-d: heap 30 MB, HNSW 54 MB, IVFFlat 27 MB, halfvec HNSW 41 MBReal scenario: A team moves from 1536 to 3072 dimensions for a small recall gain, doubles the index, falls out of RAM and sees latency jump tenfold; another truncates a Matryoshka-style model to 512 dimensions and halves cost with negligible loss.
What provides it:
| Lever | Effect | Caveat |
|---|---|---|
Smaller model or truncated dimension (dimensions parameter in OpenAI text-embedding-3 models; Matryoshka embeddings) | Linear savings | Must be supported by the model and evaluated |
halfvec | 2 times smaller, indexable to 4000 dims | Slight precision loss |
| Binary quantization + re-rank | About 32 times smaller index | Needs high dimensions and a shortlist |
STORAGE PLAIN | No TOAST lookup | Tuple must fit in a page |
More RAM / shared_buffers | Index stays hot | Hardware cost |
Fix / how to use it:
SELECT pg_size_pretty(pg_relation_size('docs_hnsw')) AS index, pg_size_pretty(pg_relation_size('docs')) AS heap;
CREATE TABLE items (embedding halfvec(1536) STORAGE PLAIN);// OpenAI text-embedding-3 models accept a dimensions parameter (embed.OpenAI(..., 512, ...)).
vecs, err := embed.OpenAI(ctx, apiKey, "text-embedding-3-small", 512, texts)$table->vector('embedding', dimensions: 512); // match the truncated model outputPer-engine behaviour
Matrix 1: index and search features
| Feature | PostgreSQL + pgvector 0.8.7 | pgvectorscale | Qdrant | Milvus | Weaviate | Pinecone | Vespa | Elasticsearch / OpenSearch | Redis vector sets |
|---|---|---|---|---|---|---|---|---|---|
| Exact search | Default (seq scan) | Same | Flat / exact flag | FLAT index | Flat index | n/a (managed) | Exact nearest-neighbour option | Brute-force kNN (script_score) | VSIM ... TRUTH |
| Main ANN index | HNSW, IVFFlat | StreamingDiskANN | HNSW | HNSW, IVF family, DiskANN, GPU indexes | HNSW (plus flat, dynamic) | Proprietary, managed | HNSW | HNSW (Lucene) | HNSW |
| Quantization | halfvec, binary | SBQ | scalar, product, binary | SQ, PQ and others | PQ, BQ, SQ | managed | int8, binary tensors | int8, int4, BBQ (version-dependent) | Q8 (default), BIN, NOQUANT |
| Filtering | post-filter + iterative scans | labels (filter-aware), else post-filter | payload filter integrated into HNSW | scalar filtering, partitions | pre-filter with ACORN-style traversal (version-dependent) | metadata filter | filter integrated | filter inside knn | FILTER expression, FILTER-EF |
| Hybrid (lexical + vector) | tsvector + SQL RRF | same | sparse vectors + fusion | sparse vectors + RRF ranker | BM25F + vector fusion | sparse-dense | BM25 + nearestNeighbor ranking | BM25 + kNN, RRF retriever | no lexical side |
| Multi-tenancy | partitions, partial indexes, RLS | labels | payload partition per tenant | partition key, database per tenant | first-class tenants | namespaces | tensors per document, grouping | index or alias per tenant, filters | key per tenant |
| Transactions and joins | Full SQL | Full SQL | no | no | no | no | no | no | no |
Only the pgvector, pgvectorscale, Elasticsearch (the exact vs approximate wording and k/num_candidates) and Redis columns come from documents fetched for this page. The other columns are general knowledge about the products at the time of writing; verify against the docs of the version you run before relying on a cell.
Matrix 2: what each system really does
| System | Type | Notes that matter in practice |
|---|---|---|
| PostgreSQL + pgvector | General database with a vector extension | Vectors live with relational data: transactions, joins, WAL, replicas, PITR. Index quality and filters are your job. Single-node memory bounds HNSW; scale with replicas, Citus or other sharding |
| pgvectorscale | Extension on top of pgvector (Timescale) | StreamingDiskANN, SBQ, label filtering; its own README warns of a newer approach, pg_vectorsearch, in early alpha |
| Qdrant | Dedicated engine | HNSW with payload filtering, quantization, named and sparse vectors; open source and cloud. Qdrant's own guide: "Traditional and vector databases aren't rivals; they solve different problems." |
| Milvus | Dedicated, distributed | Described by its docs as "a high-performance, highly scalable vector database that runs efficiently across a wide range of environments, from a laptop to large-scale distributed systems"; many index types, disaggregated storage and compute |
| Weaviate | Dedicated engine | Objects + vectors + schema, hybrid search, built-in tenants |
| Pinecone | Managed service | No self-hosting; namespaces and metadata filters; vendor explainer: "A vector database indexes and stores vector embeddings for fast retrieval and similarity search" |
| Vespa | Search and ranking engine | One engine for lexical, vector and tensor ranking with multi-phase ranking |
| Elasticsearch / OpenSearch | Search engine with a vector field | You may already run it for text; knn with k and num_candidates; hybrid is natural; sync from your database is the price |
| Redis vector sets | A data type (Redis 8) | "a new Redis data type similar to Sorted Sets but having string elements associated to a vector instead of a score"; VADD, VSIM, FILTER; memory-resident |
| MongoDB, MySQL/HeatWave, SQL Server, Oracle, SQLite | General databases adding vector types | Oracle AI Vector Search, MongoDB Atlas Vector Search, SQLite via extensions such as sqlite-vec (general knowledge); Laravel 13's whereVectorSimilarTo also lists MariaDB 11.7 and MongoDB |
| CockroachDB | Distributed SQL | Added vector types and indexes in recent versions (general knowledge; check the release you run) |
Mechanics
pgvector types, operators and functions Must-know
| Type | Element | Storage | Dimension limit | Indexable (HNSW / IVFFlat) | Written as |
|---|---|---|---|---|---|
vector(n) | float32 | 4 * n + 8 bytes | 16,000 | 2,000 / 2,000 | '[1,2,3]' |
halfvec(n) | float16 | 2 * n + 8 bytes | 16,000 | 4,000 / 4,000 | '[1,2,3]' |
bit(n) | 1 bit | n / 8 + 8 bytes | n/a | 64,000 / 64,000 | '101' |
sparsevec(n) | float32, non-zero only | 8 * nnz + 16 bytes | 16,000 non-zero | 1,000 non-zero / no | '{1:1,3:2,5:3}/5' (1-based indices) |
Useful functions (all from the README reference): vector_dims, vector_norm, l2_normalize, subvector(v, start, count), binary_quantize, l2_distance, cosine_distance, inner_product, l1_distance, hamming_distance, jaccard_distance, avg(vector), sum(vector). Arithmetic: +, -, * (element-wise) and || (concatenate, 0.7.0). Elements must be finite.
The planner: when the index is used Must-know
The README's rule: "The query needs to have an ORDER BY and LIMIT, and the ORDER BY must be the result of a distance operator (not an expression) in ascending order."
1 ORDER BY embedding <=> :q LIMIT 10 -- index scan possible
2 ORDER BY 1 - (embedding <=> :q) DESC LIMIT 10 -- expression: sequential scan + sort
3 WHERE embedding <-> :q < 5 -- no LIMIT: no ordered index scan
4 index built with vector_cosine_ops, query uses <-> -- index not used
5 tiny table, or very selective WHERE -- planner may prefer a seq scan (cost-based; do not rely on it)
6 BEGIN; SET LOCAL enable_seqscan = off; ... COMMIT; -- encourage the index while testing
7 EXPLAIN (ANALYZE, BUFFERS) SELECT ... -- the README's debugging toolLab plans (cosine, 100k rows, 64 dimensions): HNSW Index Scan using docs_hnsw, 1236 buffer hits, 2 ms. Exact Gather Merge over a Parallel Seq Scan, 3921 buffer hits, 6 ms (an earlier run of the same query). The expression ORDER BY 1 - (embedding <=> q) gave the parallel sequential scan even with the HNSW index present.
Building an index: index build memory, parallelism, progress Must-know
| Concern | Knob or fact | Notes |
|---|---|---|
| Memory | maintenance_work_mem | HNSW "build significantly faster when the graph fits"; message NOTICE: hnsw graph no longer fits into maintenance_work_mem after 8650 tuples followed by "Building will take significantly more time." Lab: 100k vectors, 8 MB: 67 s; 256 MB: about 7 s |
| Do not overshoot | The README: do not set it "so high that it exhausts the memory on the server" | |
| Parallelism | max_parallel_maintenance_workers (2), possibly max_parallel_workers (8) | In Docker, parallel builds need shared memory: the lab failed with could not resize shared memory segment ... No space left on device until --shm-size=1g |
| Order | Load first, index after ("faster to create an index after loading your initial data") | COPY ... WITH (FORMAT BINARY) for bulk loads |
| Production | CREATE INDEX CONCURRENTLY | Avoids blocking writes; Laravel: public $withinTransaction = false; in the migration |
| Progress | pg_stat_progress_create_index | HNSW phases initializing, loading tuples; IVFFlat initializing, performing k-means, assigning tuples, loading tuples |
| Size | pg_relation_size('index') | Lab: HNSW 54 MB, IVFFlat 27 MB, halfvec HNSW 41 MB, binary HNSW 30 MB for a 30 MB heap |
| Cheaper builds | halfvec expression index, binary quantization, defaults for m and ef_construction | "use the defaults unless seeing low recall" |
SET maintenance_work_mem = '2GB';
SET max_parallel_maintenance_workers = 7;
CREATE INDEX CONCURRENTLY docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops);
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;Error messages you will meet Must-know
Verified on PostgreSQL 17 with pgvector 0.8.7.
| Message | Cause | Fix |
|---|---|---|
ERROR: expected 3 dimensions, not 2 | Inserting a vector whose length differs from the column | Check the model's dimension; validate before insert |
ERROR: different vector dimensions 3 and 2 | Distance between two vectors of different length | Both sides must come from the same model |
ERROR: NaN not allowed in vector | A non-finite element | Sanitise embeddings; a bad model response can produce it |
ERROR: column cannot have more than 2000 dimensions for hnsw index | vector indexed above 2000 dimensions | halfvec (4000), binary quantization (64,000), subvector, dimension reduction |
ERROR: column cannot have more than 4000 dimensions for hnsw index | halfvec above 4000 | Binary quantization or reduce dimensions |
ERROR: dimensions for type vector cannot exceed 16000 | Column type limit | Reduce dimensions |
ERROR: 2000 is outside the valid range for parameter "hnsw.ef_search" (1 .. 1000) | ef_search out of range | Use at most 1000 |
ERROR: invalid value for parameter "hnsw.iterative_scan": "foo" with HINT: Available values: off, relaxed_order, strict_order. | Typo in the setting | Use a listed value |
no error, fewer rows than LIMIT | Post-filter, small ef_search, dead tuples, IVFFlat built on little data | Post-filter problem, freshness |
no error, NULL embedding never matches | NULL vectors (and zero vectors with cosine) are not indexed | Make embedding NOT NULL |
Server tuning that matters here Important
| Setting | Why | Source |
|---|---|---|
shared_buffers (about 25% of RAM as a start) | Keep the index and heap hot | pgvector README, "Tuning" |
maintenance_work_mem | Index build speed | README |
max_parallel_workers_per_gather | Speeds up exact search | README, "Exact Search" |
work_mem and hnsw.scan_mem_multiplier | Memory for iterative scans (multiple of work_mem) | README |
ALTER TABLE ... SET STORAGE PLAIN / min_parallel_table_scan_size / parallel_setup_cost | Out-of-line (TOAST) storage hides cost from the planner; the README explains parallel scans and the fix | README, "Troubleshooting" |
pg_stat_statements, PgHero | Latency by query | README, "Monitoring"; see Database Observability |
Solving the classic problems
Semantic search without scanning every row
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Load all rows and rank in the app | "Before" code below | Trivial | Whole table over the network, O(N) memory and CPU per request |
ORDER BY embedding <=> $1 LIMIT k | Exact, in SQL | Correct, simple | Linear in table size |
| Same plus HNSW | "After" code below | Milliseconds at millions | Tune and measure recall |
Same plus whereVectorSimilarTo | Laravel | One line | Cosine only; ->index() DDL should be checked |
Go: before. The service loads every row, parses each embedding and ranks in application memory. Correct on a demo table; each request reads the whole table.
// Package before ranks documents by loading every row and computing cosine
// similarity in application memory. It works on a small table and fails quietly
// as the table grows: each query reads the whole table over the network and does
// O(N * d) arithmetic with no index.
package before
import (
"context"
"database/sql"
"errors"
"math"
"sort"
"strconv"
"strings"
)
// Scored is one search result.
type Scored struct {
ID int64
Content string
Similarity float64
}
// Search returns the k most similar documents to query.
func Search(ctx context.Context, db *sql.DB, query []float32, k int) ([]Scored, error) {
// No WHERE clause and no LIMIT: every row crosses the wire on every request.
// embedding::text is the pgvector text form, e.g. "[0.1,0.2,0.3]".
rows, err := db.QueryContext(ctx, `SELECT id, content, embedding::text FROM documents`)
if err != nil {
return nil, err
}
defer rows.Close()
var all []Scored
for rows.Next() {
var (
id int64
content string
raw string
)
if err := rows.Scan(&id, &content, &raw); err != nil {
return nil, err
}
vec, err := parseVector(raw)
if err != nil {
return nil, err
}
sim, err := cosine(query, vec)
if err != nil {
return nil, err
}
all = append(all, Scored{ID: id, Content: content, Similarity: sim})
}
if err := rows.Err(); err != nil {
return nil, err
}
// Sort the whole result set just to keep k rows.
sort.Slice(all, func(i, j int) bool { return all[i].Similarity > all[j].Similarity })
if len(all) > k {
all = all[:k]
}
return all, nil
}
func parseVector(raw string) ([]float32, error) {
raw = strings.TrimSuffix(strings.TrimPrefix(raw, "["), "]")
parts := strings.Split(raw, ",")
out := make([]float32, 0, len(parts))
for _, p := range parts {
f, err := strconv.ParseFloat(strings.TrimSpace(p), 32)
if err != nil {
return nil, err
}
out = append(out, float32(f))
}
return out, nil
}
func cosine(a, b []float32) (float64, error) {
if len(a) != len(b) {
return 0, errors.New("dimension mismatch")
}
var dot, na, nb float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
na += float64(a[i]) * float64(a[i])
nb += float64(b[i]) * float64(b[i])
}
if na == 0 || nb == 0 {
return 0, nil
}
return dot / (math.Sqrt(na) * math.Sqrt(nb)), nil
}Go: after. Ranking happens in Postgres: ORDER BY ... <=> ... LIMIT lets the planner use the HNSW index, and only k rows come back. The vector is bound as a parameter and cast on the server. SET LOCAL runs inside a transaction because a plain SET would stay on the pooled connection.
// Package after ranks documents in Postgres with pgvector, using the <=> cosine
// distance operator and an HNSW index. Only k rows leave the database.
package after
import (
"context"
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
)
/*
Schema and index, created once in a migration. The dimension must match the
embedding model's output.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3) NOT NULL
);
CREATE INDEX documents_embedding_hnsw
ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
*/
// Scored is one search result. Similarity is 1 minus cosine distance.
type Scored struct {
ID int64
Content string
Similarity float64
}
// vectorLiteral renders a []float32 in pgvector's text form, e.g. "[0.1,0.2,0.3]".
// The result is bound as a query parameter below, never concatenated into SQL.
func vectorLiteral(v []float32) string {
var b strings.Builder
b.WriteByte('[')
for i, x := range v {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(strconv.FormatFloat(float64(x), 'g', -1, 32))
}
b.WriteByte(']')
return b.String()
}
// Search returns the k nearest documents to query. efSearch sets hnsw.ef_search
// for this query: higher values improve recall and cost more time.
func Search(ctx context.Context, db *sql.DB, query []float32, k, efSearch int) ([]Scored, error) {
if efSearch < 1 || k < 1 {
return nil, errors.New("efSearch and k must be positive")
}
// A transaction pins one pooled connection, so the setting applies to this
// query. SET LOCAL reverts at COMMIT or ROLLBACK, so the pool is not left
// with a changed ef_search for other callers. efSearch is an int, not user
// text, so formatting it into the statement is safe.
tx, err := db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return nil, err
}
defer tx.Rollback() // no-op after a successful Commit
if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL hnsw.ef_search = %d", efSearch)); err != nil {
return nil, err
}
// ORDER BY on the <=> operator with LIMIT lets the planner use the HNSW index.
// $1 is bound as text and cast to vector on the server.
rows, err := tx.QueryContext(ctx, `
SELECT id, content, 1 - (embedding <=> $1::vector) AS similarity
FROM documents
ORDER BY embedding <=> $1::vector
LIMIT $2`,
vectorLiteral(query), k)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Scored
for rows.Next() {
var s Scored
if err := rows.Scan(&s.ID, &s.Content, &s.Similarity); err != nil {
return nil, err
}
out = append(out, s)
}
if err := rows.Err(); err != nil {
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
return out, nil
}Go with pgx and pgvector-go. database/sql has no vector type, so the plain version sends the text form [0.1,0.2,0.3] and casts with $1::vector. With pgx, the pgvector-go package registers the types in the pool's AfterConnect hook and accepts pgvector.NewVector([]float32{...}) as a parameter (the README's pgxvec.RegisterTypes pattern). It also supports GORM, Bun, Ent and sqlx. This file also contains the tenant-filtered, iterative-scan search and the upsert used by the re-embedding loop.
// Package pgxsearch uses pgvector-go with pgx: typed vector parameters, a
// filtered search with iterative scans, and a per-tenant helper.
package pgxsearch
import (
"context"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/pgvector/pgvector-go"
pgxvec "github.com/pgvector/pgvector-go/pgx"
)
// NewPool registers the vector types on every new connection. Without
// RegisterTypes pgx does not know how to encode pgvector.Vector.
func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
return pgxvec.RegisterTypes(ctx, conn)
}
return pgxpool.NewWithConfig(ctx, cfg)
}
// Hit is one search result.
type Hit struct {
ID int64
Distance float64
}
// SearchTenant returns the k nearest documents of one tenant. The filter is a
// post-filter on an HNSW index, so the query turns on iterative scans: the
// index keeps scanning until k rows pass the WHERE clause or the scan limits
// (hnsw.max_scan_tuples) are reached. SET LOCAL needs a transaction.
func SearchTenant(ctx context.Context, pool *pgxpool.Pool, tenantID int, query []float32, k, efSearch int) ([]Hit, error) {
tx, err := pool.BeginTx(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly})
if err != nil {
return nil, err
}
defer tx.Rollback(ctx) // no-op after Commit
// efSearch is an int, so formatting it into the statement is safe.
if _, err := tx.Exec(ctx, fmt.Sprintf("SET LOCAL hnsw.ef_search = %d", efSearch)); err != nil {
return nil, err
}
if _, err := tx.Exec(ctx, "SET LOCAL hnsw.iterative_scan = relaxed_order"); err != nil {
return nil, err
}
rows, err := tx.Query(ctx, `
SELECT id, embedding <=> $1 AS distance
FROM docs
WHERE tenant_id = $2
ORDER BY embedding <=> $1
LIMIT $3`,
pgvector.NewVector(query), tenantID, k)
if err != nil {
return nil, err
}
hits, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Hit, error) {
var h Hit
err := r.Scan(&h.ID, &h.Distance)
return h, err
})
if err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
// relaxed_order may return rows slightly out of order; sort again if the
// caller needs a strict order (or use strict_order and pay for it).
return hits, nil
}
// Upsert stores one embedding together with the model that produced it, so a
// later re-embedding job can find the rows still on the old model.
func Upsert(ctx context.Context, pool *pgxpool.Pool, id int64, model string, v []float32) error {
_, err := pool.Exec(ctx, `
INSERT INTO docs (id, embedding, embedding_model)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO UPDATE
SET embedding = EXCLUDED.embedding, embedding_model = EXCLUDED.embedding_model`,
id, pgvector.NewVector(v), model)
return err
}Laravel: before. All documents are loaded and compared in a PHP loop.
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
// Loads every document, parses each embedding in PHP, and sorts in memory.
// Every search moves the whole table out of Postgres and ranks it in one PHP
// process, so cost and memory grow with the number of rows.
final class SemanticSearch
{
/**
* @param list<float> $queryEmbedding
* @return list<array{id: int, title: string, similarity: float}>
*/
public function search(array $queryEmbedding, int $limit = 10): array
{
$rows = DB::table('documents')->select(['id', 'title', 'embedding'])->get();
$scored = $rows->map(function (object $row) use ($queryEmbedding): array {
// The pgvector text form "[0.1,0.2,0.3]" is valid JSON.
$vector = json_decode($row->embedding, true);
return [
'id' => $row->id,
'title' => $row->title,
'similarity' => $this->cosine($queryEmbedding, $vector),
];
})->all();
usort($scored, fn (array $a, array $b): int => $b['similarity'] <=> $a['similarity']);
return array_slice($scored, 0, $limit);
}
/**
* @param list<float> $a
* @param list<float> $b
*/
private function cosine(array $a, array $b): float
{
if (count($a) !== count($b)) {
throw new InvalidArgumentException('Embedding dimensions do not match.');
}
$dot = 0.0;
$normA = 0.0;
$normB = 0.0;
foreach ($a as $i => $x) {
$y = $b[$i];
$dot += $x * $y;
$normA += $x * $x;
$normB += $y * $y;
}
if ($normA == 0.0 || $normB == 0.0) {
return 0.0;
}
return $dot / (sqrt($normA) * sqrt($normB));
}
}Laravel: after. The migration calls Schema::ensureVectorExtensionExists(), declares the column with vector() and adds ->index(). The AsVector cast converts between PHP float arrays and the database format. whereVectorSimilarTo filters by cosine similarity, orders by relevance and takes a minSimilarity between 0.0 and 1.0.
<?php
// database/migrations/2026_01_01_000000_create_documents_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Loads the pgvector extension on PostgreSQL before the vector column is created.
Schema::ensureVectorExtensionExists();
Schema::create('documents', function (Blueprint $table) {
$table->id();
// Used by the tenant-filtered and hybrid examples.
$table->unsignedBigInteger('tenant_id')->index();
$table->string('title');
$table->text('content');
// The dimension must match the embedding model's output (1536 for text-embedding-3-small).
// index() adds a vector index on the column; the migration docs describe it
// as a cosine-distance index, the search docs as an HNSW index.
$table->vector('embedding', dimensions: 1536)->index();
$table->timestamps();
});
// Generated full-text column for the keyword side of hybrid search.
DB::statement("ALTER TABLE documents ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || content)) STORED");
DB::statement('CREATE INDEX documents_tsv_gin ON documents USING gin (tsv)');
}
public function down(): void
{
Schema::dropIfExists('documents');
}
};<?php
// app/Models/Document.php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\AsVector;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class Document extends Model
{
protected $fillable = ['tenant_id', 'title', 'content', 'embedding'];
protected function casts(): array
{
// Converts between PHP float arrays and the database's vector format.
return ['embedding' => AsVector::class];
}
/** @return HasMany<DocumentChunk, $this> */
public function chunks(): HasMany
{
return $this->hasMany(DocumentChunk::class);
}
}<?php
// app/Services/SemanticSearch.php
namespace App\Services;
use App\Models\Document;
use Illuminate\Database\Eloquent\Collection;
final class SemanticSearch
{
/**
* Cosine-similarity search. Postgres computes the ranking, applies the
* index, and returns only $limit rows.
*
* @param list<float> $queryEmbedding
* @return Collection<int, Document>
*/
public function search(array $queryEmbedding, int $limit = 10): Collection
{
return Document::query()
->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
->limit($limit)
->get();
}
}The Laravel docs say: "the whereVectorSimilarTo query builder method uses vector embeddings stored in PostgreSQL with the pgvector extension or MariaDB", and it "requires PostgreSQL with the pgvector extension or MariaDB 11.7 or later, as well as the Laravel AI SDK". If you pass a plain string instead of an array, Laravel generates the embedding with the AI SDK. The same docs list selectVectorDistance, whereVectorDistanceLessThan and orderByVectorDistance, and Schema::ensureVectorExtensionExists(). The migration docs say ->index() "creates a vector index using cosine distance" while the search docs call it "an HNSW (Hierarchical Navigable Small World) index"; look at the generated DDL before tuning, or create the index yourself as in the chunk migration below. $table->vectorIndex('embedding') and dropVectorIndex also exist.
Tenant-filtered search and the explicit HNSW migration
A multi-tenant chunk table, an explicit CREATE INDEX CONCURRENTLY ... USING hnsw with the operator class and parameters you choose, the model name stored per row, and a search service that turns on iterative scans.
<?php
// database/migrations/2026_01_02_000000_add_tenant_and_model_to_chunks.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
// CREATE INDEX CONCURRENTLY cannot run inside a transaction block.
public $withinTransaction = false;
public function up(): void
{
Schema::ensureVectorExtensionExists();
Schema::create('document_chunks', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('tenant_id')->index();
$table->foreignId('document_id')->constrained()->cascadeOnDelete();
$table->unsignedInteger('position');
$table->text('content');
// The model name travels with the vector: vectors from different models
// are not comparable, and this column drives re-embedding backfills.
$table->string('embedding_model')->index();
$table->vector('embedding', dimensions: 1536);
$table->unique(['document_id', 'position']);
});
// Explicit HNSW with the operator class and build parameters we want,
// built without blocking writes. cosine matches whereVectorSimilarTo.
DB::statement(<<<'SQL'
CREATE INDEX CONCURRENTLY document_chunks_embedding_hnsw
ON document_chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64)
SQL);
}
public function down(): void
{
Schema::dropIfExists('document_chunks');
}
};<?php
// app/Models/DocumentChunk.php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\AsVector;
use Illuminate\Database\Eloquent\Model;
final class DocumentChunk extends Model
{
public $timestamps = false;
protected $fillable = ['tenant_id', 'document_id', 'position', 'content', 'embedding', 'embedding_model'];
protected function casts(): array
{
return ['embedding' => AsVector::class];
}
}<?php
// app/Services/TenantSearch.php
namespace App\Services;
use App\Models\DocumentChunk;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
final class TenantSearch
{
/**
* Nearest chunks for one tenant. The tenant filter is a post-filter on a
* shared HNSW index, so iterative scans keep the index scanning until
* $limit rows pass the filter.
*
* @param list<float> $queryEmbedding
* @return Collection<int, DocumentChunk>
*/
public function search(int $tenantId, array $queryEmbedding, int $limit = 10): Collection
{
return DB::transaction(function () use ($tenantId, $queryEmbedding, $limit): Collection {
// SET LOCAL lasts until the end of this transaction only.
DB::statement('SET LOCAL hnsw.iterative_scan = relaxed_order');
DB::statement('SET LOCAL hnsw.ef_search = 100');
return DocumentChunk::query()
->where('tenant_id', $tenantId)
->where('embedding_model', 'text-embedding-3-small@1536')
->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.3)
->limit($limit)
->get();
});
}
/**
* Same search with the distance returned, e.g. to show a score or to cut off
* weak matches in application code.
*
* @param list<float> $queryEmbedding
* @return Collection<int, DocumentChunk>
*/
public function searchWithDistance(int $tenantId, array $queryEmbedding, int $limit = 10): Collection
{
return DocumentChunk::query()
->select('*')
->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
->where('tenant_id', $tenantId)
->orderByVectorDistance('embedding', $queryEmbedding)
->limit($limit)
->get();
}
}Hybrid search with RRF
SQL above; in Go the lists can come from two queries and be merged with fusion.RRF; in Laravel the whole statement is one DB::select.
// Package fusion holds two small pieces of search plumbing that need no
// database: Reciprocal Rank Fusion of ranked id lists, and recall@k.
package fusion
import "sort"
// RRF merges ranked lists of ids. Each list contributes 1/(k+rank) for every id
// it contains (rank starts at 1); k = 60 is the constant from the original paper.
// The result is sorted by fused score, best first, with ties broken by id.
func RRF(k int, lists ...[]int64) []int64 {
score := map[int64]float64{}
for _, list := range lists {
for i, id := range list {
score[id] += 1.0 / float64(k+i+1)
}
}
ids := make([]int64, 0, len(score))
for id := range score {
ids = append(ids, id)
}
sort.Slice(ids, func(a, b int) bool {
if score[ids[a]] != score[ids[b]] {
return score[ids[a]] > score[ids[b]]
}
return ids[a] < ids[b]
})
return ids
}
// RecallAtK is the share of the exact top-k ids that the approximate result
// also returned. exact is the ground truth from a sequential scan.
func RecallAtK(exact, approx []int64, k int) float64 {
if k > len(exact) {
k = len(exact)
}
if k == 0 {
return 1
}
want := make(map[int64]struct{}, k)
for _, id := range exact[:k] {
want[id] = struct{}{}
}
hits := 0
for i, id := range approx {
if i >= k {
break
}
if _, ok := want[id]; ok {
hits++
}
}
return float64(hits) / float64(k)
}<?php
// app/Services/HybridSearch.php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class HybridSearch
{
/**
* Keyword (full-text) and vector retrieval, fused with Reciprocal Rank Fusion
* in one SQL statement. Both branches apply the same tenant filter.
*
* @return list<object{id: int, title: string, rrf: float}>
*/
public function search(int $tenantId, string $query, int $limit = 10): array
{
// One embedding call per search; cache it if the same query repeats.
$embedding = Str::of($query)->toEmbeddings();
$literal = '[' . implode(',', $embedding) . ']';
$sql = <<<'SQL'
WITH semantic AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> ?::vector) AS rnk
FROM documents
WHERE tenant_id = ?
ORDER BY embedding <=> ?::vector
LIMIT 40
), keyword AS (
SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rnk
FROM documents, websearch_to_tsquery('english', ?) AS q
WHERE tenant_id = ? AND tsv @@ q
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 40
)
SELECT d.id, d.title,
coalesce(1.0 / (60 + s.rnk), 0) + coalesce(1.0 / (60 + k.rnk), 0) AS rrf
FROM semantic s
FULL OUTER JOIN keyword k ON k.id = s.id
JOIN documents d ON d.id = coalesce(s.id, k.id)
ORDER BY rrf DESC
LIMIT ?
SQL;
// The statement runs in a transaction so SET LOCAL applies to this query only.
return DB::transaction(function () use ($sql, $literal, $tenantId, $query, $limit): array {
DB::statement('SET LOCAL hnsw.ef_search = 100');
DB::statement('SET LOCAL hnsw.iterative_scan = relaxed_order');
return DB::select($sql, [$literal, $tenantId, $literal, $query, $tenantId, $limit]);
});
}
}Embedding generation: Ollama and OpenAI (compile-only)
| Provider | Endpoint | Request | Response | Notes |
|---|---|---|---|---|
| Ollama (local) | POST http://localhost:11434/api/embed | {"model": "...", "input": ["a", "b"]} | {"embeddings": [[...], [...]]} | Run ollama pull <model> first; dimension depends on the model; nothing leaves your machine |
| OpenAI | POST https://api.openai.com/v1/embeddings | {"model": "...", "input": [...], "dimensions": 512} | {"data": [{"index": 0, "embedding": [...]}]} | dimensions is supported by the text-embedding-3 models; send an Authorization: Bearer header; sort by index |
| Laravel AI SDK | Str::of('text')->toEmbeddings(), Embeddings::for([...])->generate() | Strings | $response->embeddings | Provider and caching are configured in the SDK (composer require laravel/ai) |
The Go helpers below only build requests and decode responses, so they compile and vet without a server or key.
// Package embed generates embeddings over HTTP from a local Ollama server and
// from the OpenAI API. It only builds requests and decodes responses, so it
// compiles and vets without a network; calling it needs a running server or key.
package embed
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
var client = &http.Client{Timeout: 30 * time.Second}
func post(ctx context.Context, url, bearer string, body, out any) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("embedding request failed: %s", resp.Status)
}
return json.NewDecoder(resp.Body).Decode(out)
}
// Ollama calls POST /api/embed on a local server (default http://localhost:11434).
// The response carries one vector per input string.
func Ollama(ctx context.Context, baseURL, model string, inputs []string) ([][]float32, error) {
var out struct {
Embeddings [][]float32 `json:"embeddings"`
}
err := post(ctx, baseURL+"/api/embed", "", map[string]any{"model": model, "input": inputs}, &out)
if err != nil {
return nil, err
}
if len(out.Embeddings) != len(inputs) {
return nil, errors.New("ollama returned a different number of embeddings than inputs")
}
return out.Embeddings, nil
}
// OpenAI calls POST /v1/embeddings. Pass dimensions > 0 to ask a text-embedding-3
// model for a shortened vector; pass 0 to keep the model's native size.
func OpenAI(ctx context.Context, apiKey, model string, dimensions int, inputs []string) ([][]float32, error) {
body := map[string]any{"model": model, "input": inputs}
if dimensions > 0 {
body["dimensions"] = dimensions
}
var out struct {
Data []struct {
Index int `json:"index"`
Embedding []float32 `json:"embedding"`
} `json:"data"`
}
if err := post(ctx, "https://api.openai.com/v1/embeddings", apiKey, body, &out); err != nil {
return nil, err
}
vecs := make([][]float32, len(inputs))
for _, d := range out.Data {
if d.Index < 0 || d.Index >= len(vecs) {
return nil, errors.New("openai returned an out-of-range index")
}
vecs[d.Index] = d.Embedding
}
return vecs, nil
}<?php
// app/Jobs/EmbedDocument.php
namespace App\Jobs;
use App\Models\Document;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Laravel\Ai\Embeddings;
final class EmbedDocument implements ShouldQueue
{
use Queueable;
// Bump this when the embedding model changes. Rows whose embedding_model
// differs are the ones a re-embedding backfill still has to visit.
public const MODEL = 'text-embedding-3-small@1536';
public function __construct(public readonly int $documentId) {}
public function handle(): void
{
$document = Document::query()->findOrFail($this->documentId);
// Split the body into chunks first; one embedding per chunk, not per document.
$chunks = $this->chunk($document->content, maxChars: 1500, overlap: 200);
$response = Embeddings::for($chunks)->generate();
foreach ($response->embeddings as $position => $vector) {
$document->chunks()->updateOrCreate(
['position' => $position],
[
'tenant_id' => $document->tenant_id,
'content' => $chunks[$position],
'embedding' => $vector,
'embedding_model' => self::MODEL,
],
);
}
}
/**
* Fixed-size chunks with overlap, cut at a paragraph or sentence boundary
* when one is near. A starting point, not a recommendation for every corpus.
*
* @return list<string>
*/
private function chunk(string $text, int $maxChars, int $overlap): array
{
$chunks = [];
$length = mb_strlen($text);
$start = 0;
while ($start < $length) {
$end = min($start + $maxChars, $length);
if ($end < $length) {
$window = mb_substr($text, $start, $end - $start);
$cut = max(mb_strrpos($window, "\n\n") ?: 0, mb_strrpos($window, '. ') ?: 0);
if ($cut > $maxChars / 2) {
$end = $start + $cut + 1;
}
}
$chunks[] = trim(mb_substr($text, $start, $end - $start));
if ($end >= $length) {
break;
}
$start = max($end - $overlap, $start + 1);
}
return array_values(array_filter($chunks, fn (string $c): bool => $c !== ''));
}
}Retries and failure handling
Embedding generation is a network call to a rate-limited service, so ingestion is the part that fails.
| Failure | Meaning | Retry? | What to do |
|---|---|---|---|
| HTTP 429 from the provider | Rate limit | Yes, with backoff and jitter | Respect Retry-After; batch inputs; queue the work |
| HTTP 5xx or timeout | Provider trouble | Yes, bounded | Idempotent job; same chunk can be re-embedded safely |
| HTTP 400 input too long | Chunk exceeds the model limit | No | Re-chunk smaller; truncate deliberately |
Dimension mismatch on insert (expected 3 dimensions, not 2) | Wrong model or truncation setting | No | Fix configuration; do not coerce |
Postgres 57014 statement timeout during index build | Long CREATE INDEX | After raising the timeout | Run the build with a longer statement_timeout in a maintenance session |
| Out of memory during build | maintenance_work_mem too high for the host | After lowering | Lower the setting or build on a bigger node |
Search returns fewer rows than LIMIT | Filter / small candidate list | Not a retry problem | Iterative scans, B-tree, partition |
Rules: make ingestion idempotent with ON CONFLICT (document_id, position) DO UPDATE; record the model name per row so a crashed backfill resumes; cache query embeddings for repeated queries; never retry a search by raising ef_search blindly, measure first.
// A bounded retry with exponential backoff around any embedding call.
func withRetry[T any](ctx context.Context, attempts int, fn func() (T, error)) (T, error) {
var zero T
delay := 500 * time.Millisecond
for i := 0; i < attempts; i++ {
v, err := fn()
if err == nil {
return v, nil
}
select {
case <-ctx.Done():
return zero, ctx.Err()
case <-time.After(delay):
delay *= 2
}
}
return zero, errors.New("embedding failed after retries")
}// Laravel: the job retries with backoff declared on the class.
public int $tries = 5;
public function backoff(): array { return [5, 30, 120, 600]; }Choosing
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Up to about 50k to 100k vectors, no latency pressure | Exact search, no index | max_parallel_workers_per_gather | Perfect recall, nothing to maintain (lab: exact about 5 ms at 100k x 64) |
| RAG store that fits in RAM, millions of chunks | pgvector HNSW, cosine or inner product | halfvec, tune ef_search against recall@10 | Best speed-recall trade-off in pgvector, handles inserts |
| Build time or memory is the constraint | IVFFlat | Build after load, probes about sqrt(lists) | Faster build, smaller index |
| Tens of millions of vectors on one Postgres | pgvectorscale StreamingDiskANN, or binary quantization + re-rank | num_bits_per_dimension, query_rescore | Memory-efficient |
| Strong filters (tenant, ACL, category) | Partition or partial index; iterative scans for the rest | B-tree on the filter | Post-filter problem |
| Keyword and meaning both matter | Hybrid with RRF | Cross-encoder rerank | Rank fusion needs no score calibration |
| Hundreds of millions of vectors, many QPS, team without DB-tuning time | Dedicated engine (Qdrant, Milvus, Weaviate, Pinecone, Vespa) | Quantization, sharding | Purpose-built scaling |
| Already run Elasticsearch/OpenSearch for text | Add dense_vector kNN there | RRF | One search stack |
| Tiny, memory-resident, simple set per key | Redis vector sets | FILTER | Low latency, small ops footprint |
| Compliance: vectors must follow row-level security and PITR | PostgreSQL | RLS, WAL archiving | Vectors are rows |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith with PostgreSQL. Add CREATE EXTENSION vector, a vector(n) column next to the content, an embedding job on write, and ORDER BY embedding <=> $1 LIMIT k on read. Start without an index; add HNSW when the exact scan exceeds your latency budget. Example: a help-centre with 30,000 chunks needs nothing more. Transactions keep the text and its vector consistent: either both are committed or neither is.
Modular monolith and multiple databases
Each module owns its tables, including its embeddings; a "search" module owns the chunk table and exposes an interface rather than letting others join into it. Use one schema per module, one embedding model per column, and embedding_model on the row. If a read-heavy search module needs its own Postgres, give it a logical replica or a separate database fed by an outbox (see Replication, Read Replicas & Failover).
Microservices: embedding pipeline, search service
Two services with different SLOs: an ingestion service (slow, rate-limited, retries) and a query service (fast, p95 budget). The flow:
1 content-service --(ContentChanged event, outbox)--> broker
2 embedding-worker <-- consumes, chunks, calls the embedding API (idempotent per chunk)
3 embedding-worker --> UPSERT document_chunks (embedding, embedding_model, tenant_id)
4 search-service <-- query: embed(query) -> hybrid SQL (RRF) -> top-k ids + snippets
5 search-service --> returns ids; the owning service resolves permissions and renders
6 failure: the event is redelivered; ON CONFLICT makes the upsert idempotentAcross the service boundary you get eventual consistency: a document is searchable only after its chunks are embedded and upserted. A saga-less design works because every step is idempotent; deleting a document must publish a delete event so its chunks disappear (see Messaging).
Distributed data: replicas, caches and dedicated engines
Read replicas serve search (pgvector uses the WAL, so replication works), at the cost of replica lag: a document written a second ago may not be searchable on the replica yet, so read-your-writes needs routing the author to the primary. Cache query embeddings and popular result lists, keyed by (model, normalised query); invalidate on model change. When sharding, either shard by tenant (all of a tenant's vectors on one shard, which also avoids the shared-index recall problem) or scatter-gather top-k from every shard and merge (each shard must return more than k to preserve recall). Dedicated engines shard and replicate internally, and add their own sync problem: the system of record is still your database, so index freshness depends on your change-data-capture or outbox pipeline.
Scaling path: 1×, 10×, 100×
| Scale | Vectors | Design |
|---|---|---|
| 1x | up to about 100k | Exact search, parallel seq scan; no index |
| 10x | about 1M | HNSW with defaults; halfvec; tune ef_search on recall@10; partial indexes for big tenants |
| 100x | 10M to 100M | maintenance_work_mem sized builds, binary quantization + re-rank or StreamingDiskANN, partitions by tenant, replicas for read scale; consider a dedicated engine if the vector workload dominates |
| 1000x | billions | Dedicated distributed engine (Milvus, Vespa, Qdrant cluster, Pinecone), tiered storage, quantization everywhere, offline index builds |
Lab
Everything here was run for this page on PostgreSQL 17 with pgvector 0.8.7 in Docker on a laptop; the scripts below are the ones that produced the numbers (the hybrid and binary-quantization snippets in experiment 4 and the B-tree line in experiment 2 were first run as ad hoc statements and are reproduced here). Numbers are illustrative: the data is random (two runs of the same script differed by about 0.01 in recall and by tens of percent in latency), your hardware and caches will differ, and the shape of the curves is what matters. The data is synthetic (24 latent factors mixed into 64 dimensions plus noise) so that nearest neighbours are meaningful; real embeddings should be measured the same way.
Setup. --shm-size=1g avoids the parallel-build shared-memory error.
docker run -d --name vec-lab --shm-size=1g -e POSTGRES_PASSWORD=lab -p 55433:5432 pgvector/pgvector:pg17
docker exec -i vec-lab psql -U postgres -v ON_ERROR_STOP=1 < lab-setup.sql
docker exec -i vec-lab psql -U postgres -v ON_ERROR_STOP=1 < lab-recall.sql
docker exec -it vec-lab psql -U postgreslab-setup.sql: 100,000 documents (tenant_id 1..100, 21 categories where category 1 matches 99 rows) and 100 query vectors.
CREATE EXTENSION IF NOT EXISTS vector;
DROP TABLE IF EXISTS docs, queries, basis;
DROP FUNCTION IF EXISTS make_vectors(int, int);
SELECT setseed(0.42);
-- 24 latent factors mixed into 64 dimensions by a fixed random matrix, plus noise.
CREATE TABLE basis AS
SELECT j, k, (random() * 2 - 1) AS w
FROM generate_series(1, 64) AS j, generate_series(1, 24) AS k;
CREATE FUNCTION make_vectors(first_id int, last_id int)
RETURNS TABLE (id int, v vector(64)) LANGUAGE sql AS $$
WITH z AS (
SELECT g, k, (random() + random() + random() - 1.5) AS zk
FROM generate_series(first_id, last_id) AS g, generate_series(1, 24) AS k
), cell AS (
SELECT z.g, b.j, sum(b.w * z.zk) + (random() - 0.5) * 2.5 AS x
FROM z JOIN basis b ON b.k = z.k
GROUP BY z.g, b.j
)
SELECT g, array_agg(x::real ORDER BY j)::vector(64) FROM cell GROUP BY g
$$;
CREATE TABLE docs (
id bigserial PRIMARY KEY,
tenant_id int NOT NULL,
category int NOT NULL,
embedding vector(64) NOT NULL
);
INSERT INTO docs (id, tenant_id, category, embedding)
SELECT id, 1 + (id % 100), CASE WHEN id % 1009 = 0 THEN 1 ELSE 2 + (id % 20) END, v
FROM make_vectors(1, 100000);
CREATE TABLE queries AS SELECT id, v AS embedding FROM make_vectors(200001, 200100);
ANALYZE docs;lab-recall.sql: lab_recall(k, filter) runs the 100 queries twice (index on, then off) and returns recall@k, average rows returned and average milliseconds for each.
CREATE OR REPLACE FUNCTION lab_recall(k int, flt text DEFAULT NULL)
RETURNS TABLE (recall numeric, avg_rows numeric, approx_ms numeric, exact_ms numeric)
LANGUAGE plpgsql AS $$
DECLARE
q record; t0 timestamptz;
approx_t interval := '0'; exact_t interval := '0';
a bigint[]; e bigint[];
hits int := 0; want int := 0; got int := 0; n int := 0;
sql text := format(
'SELECT array_agg(id) FROM (SELECT id FROM docs %s ORDER BY embedding <=> $1 LIMIT %s) s',
CASE WHEN flt IS NULL THEN '' ELSE 'WHERE ' || flt END, k);
BEGIN
FOR q IN SELECT embedding FROM queries LOOP
PERFORM set_config('enable_indexscan', 'on', true);
t0 := clock_timestamp();
EXECUTE sql INTO a USING q.embedding;
approx_t := approx_t + (clock_timestamp() - t0);
PERFORM set_config('enable_indexscan', 'off', true);
t0 := clock_timestamp();
EXECUTE sql INTO e USING q.embedding;
exact_t := exact_t + (clock_timestamp() - t0);
want := want + coalesce(cardinality(e), 0);
got := got + coalesce(cardinality(a), 0);
hits := hits + coalesce(cardinality(ARRAY(SELECT unnest(a) INTERSECT SELECT unnest(e))), 0);
n := n + 1;
END LOOP;
PERFORM set_config('enable_indexscan', 'on', true);
RETURN QUERY SELECT round(hits::numeric / NULLIF(want, 0), 3), round(got::numeric / n, 1),
round(extract(epoch FROM approx_t) * 1000 / n, 2),
round(extract(epoch FROM exact_t) * 1000 / n, 2);
END $$;Experiment 1: exact baseline, then HNSW, then the ef_search sweep
SELECT * FROM lab_recall(10); -- no index yet: both columns are exact
-- recall 1.000 | rows 10.0 | approx_ms ~5 | exact_ms ~5 (sequential scan, parallel workers)
SET maintenance_work_mem = '256MB';
\timing on
CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);
-- Time: about 5 to 10 s \timing off
SELECT pg_size_pretty(pg_relation_size('docs_hnsw')) AS idx, pg_size_pretty(pg_relation_size('docs')) AS heap;
-- idx 54 MB | heap 30 MB
SET hnsw.ef_search = 10; SELECT * FROM lab_recall(10); -- recall 0.671 | approx 0.33 ms | exact 5.15 ms
SET hnsw.ef_search = 20; SELECT * FROM lab_recall(10); -- recall 0.825 | approx 0.41 ms
SET hnsw.ef_search = 40; SELECT * FROM lab_recall(10); -- recall 0.937 | approx 0.65 ms
SET hnsw.ef_search = 100; SELECT * FROM lab_recall(10); -- recall 0.990 | approx 1.15 ms
SET hnsw.ef_search = 200; SELECT * FROM lab_recall(10); -- recall 0.999 | approx 1.98 msRead it: recall climbs and latency climbs with ef_search; the knee here is about 40 to 100. At 100k rows the exact scan is only about 5 ms, which is why "no index" is a legitimate answer at this size. Also run EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM docs ORDER BY embedding <=> (SELECT embedding FROM queries WHERE id = 200001) LIMIT 10; and compare Index Scan using docs_hnsw (about 1,200 buffers) with the plan after SET enable_indexscan = off (parallel seq scan, about 3,900 buffers).
Experiment 2: filter plus ANN
SET hnsw.ef_search = 40;
SELECT * FROM lab_recall(10, 'category = 1'); -- 0.1% of rows
-- recall 0.004 | rows 0.0 | approx 0.59 ms | exact 2.99 ms -> post-filter: almost nothing survives
SELECT * FROM lab_recall(10, 'tenant_id = 7'); -- 1% of rows
-- recall 0.043 | rows 0.4 | approx 0.53 ms | exact 2.84 ms -> 0.4 rows of 10
SELECT * FROM lab_recall(10, 'category = 2'); -- 5% of rows
-- recall 0.209 | rows 2.1 | approx 0.50 ms -> 2.1 rows of 10
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT id FROM docs WHERE tenant_id = 7 ORDER BY embedding <=> (SELECT embedding FROM queries WHERE id = 200001) LIMIT 10;
-- Index Scan using docs_hnsw Filter: (tenant_id = 7) Rows Removed by Filter: 40 (actual rows=0)
SET hnsw.iterative_scan = relaxed_order;
SELECT * FROM lab_recall(10, 'tenant_id = 7'); -- recall 0.995 | rows 10.0 | approx 6.07 ms
SET hnsw.iterative_scan = strict_order;
SELECT * FROM lab_recall(10, 'tenant_id = 7'); -- recall 0.959 | rows 10.0 | approx 5.99 ms
-- Optional: a B-tree on the filter column. In an earlier run it made the exact path about 0.3 ms
-- (bitmap scan), yet the planner still chose HNSW for the 1% filter (recall stayed 0.043).
SET hnsw.iterative_scan = off;
CREATE INDEX docs_tenant ON docs (tenant_id);
SELECT * FROM lab_recall(10, 'tenant_id = 7');Read it: the filter is a post-filter, so a 1% filter with ef_search = 40 leaves 0.4 rows, exactly the README's arithmetic (40 times 1%), and a 0.1% filter leaves essentially none. (In an earlier run the planner switched to an exact sequential scan for the 0.1% filter and returned 10 rows; that choice is cost-based and not something to depend on.) Iterative scans repair the row count, but here the repaired query (about 6 ms) is slower than the exact scan (about 2.5 ms) because 100k rows fit in cache. At 10 million rows, the exact scan with a filter would no longer be cheap. A B-tree on tenant_id made the exact path 0.3 ms (bitmap scan) but the planner still picked HNSW for the 1% filter; partial indexes or partitions are the way to force the right plan.
Experiment 3: IVFFlat
DROP INDEX docs_hnsw;
SET maintenance_work_mem = '256MB';
\timing on
CREATE INDEX docs_ivf ON docs USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); -- 0.87 s
\timing off
SELECT pg_size_pretty(pg_relation_size('docs_ivf')); -- 27 MB
SET ivfflat.probes = 1; SELECT * FROM lab_recall(10); -- recall 0.256 | approx 0.15 ms
SET ivfflat.probes = 5; SELECT * FROM lab_recall(10); -- recall 0.673 | approx 0.57 ms
SET ivfflat.probes = 10; SELECT * FROM lab_recall(10); -- recall 0.841 | approx 1.14 ms
SET ivfflat.probes = 30; SELECT * FROM lab_recall(10); -- recall 0.986 | approx 3.25 ms
SET ivfflat.probes = 100; SELECT * FROM lab_recall(10); -- recall 1.000 | approx 5.09 ms (= lists: exact)Read it: IVFFlat builds about eight times faster and is half the size, but needs far more probing than HNSW needs ef_search for the same recall, and at probes = 100 it is no faster than the exact scan.
Experiment 4: build memory, quantization, hybrid
SET maintenance_work_mem = '8MB'; SET max_parallel_maintenance_workers = 0;
CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops);
-- NOTICE: hnsw graph no longer fits into maintenance_work_mem after 8650 tuples (the number varies by run)
-- DETAIL: Building will take significantly more time.
-- HINT: Increase maintenance_work_mem to speed up builds.
-- Time: about 67 s (the same build took about 7 s with 256MB)
SET maintenance_work_mem = '256MB'; RESET max_parallel_maintenance_workers;
CREATE INDEX docs_hnsw_half ON docs USING hnsw ((embedding::halfvec(64)) halfvec_cosine_ops); -- 41 MB
CREATE INDEX docs_hnsw_bin ON docs USING hnsw ((binary_quantize(embedding)::bit(64)) bit_hamming_ops); -- 30 MB
-- Binary quantization recall: shortlist by Hamming distance, re-rank by cosine, compare with exact.
CREATE OR REPLACE FUNCTION lab_recall_bq(k int, shortlist int)
RETURNS numeric LANGUAGE plpgsql AS $$
DECLARE q record; a bigint[]; e bigint[]; hits int := 0; want int := 0;
BEGIN
FOR q IN SELECT embedding FROM queries LOOP
PERFORM set_config('enable_indexscan', 'on', true);
SELECT array_agg(id) INTO a FROM (
SELECT id FROM (
SELECT id, embedding FROM docs
ORDER BY binary_quantize(embedding)::bit(64) <~> binary_quantize(q.embedding) LIMIT shortlist) c
ORDER BY embedding <=> q.embedding LIMIT k) s;
PERFORM set_config('enable_indexscan', 'off', true);
SELECT array_agg(id) INTO e FROM (SELECT id FROM docs ORDER BY embedding <=> q.embedding LIMIT k) s;
hits := hits + cardinality(ARRAY(SELECT unnest(a) INTERSECT SELECT unnest(e)));
want := want + cardinality(e);
END LOOP;
PERFORM set_config('enable_indexscan', 'on', true);
RETURN round(hits::numeric / want, 3);
END $$;
SELECT lab_recall_bq(10, 10), lab_recall_bq(10, 50), lab_recall_bq(10, 100), lab_recall_bq(10, 200);
-- 0.127, 0.302, 0.397, 0.546 in one run
-- Hybrid setup: a lexical column that the RRF query from the hybrid section can use.
ALTER TABLE docs ADD COLUMN body text,
ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', body)) STORED;
UPDATE docs SET body = 'topic' || category || ' tenant' || tenant_id || ' note' || (id % 50);
CREATE INDEX docs_tsv ON docs USING gin (tsv);
VACUUM ANALYZE docs;Binary quantization with a re-rank shortlist on this 64-dimensional set (lab_recall_bq above): shortlist 10 gave recall 0.13, 50 gave 0.30, 100 gave 0.40, 200 gave 0.55. It is a poor fit for 64 dimensions; it is designed for hundreds to thousands of dimensions. Measure it on your own embeddings before adopting it. For hybrid search, run the RRF SQL from the hybrid section against the tsv column created above; in the lab it fused one keyword hit (id 7) and the vector neighbours as shown there.
Common misconceptions
| Belief | Reality |
|---|---|
| "Adding an HNSW index only makes queries faster" | It changes the result set; recall must be measured against exact search |
"ef_search is how many rows I get" | It is the candidate list size; results are capped by it, but you still receive LIMIT rows when enough candidates pass the filter |
| "Cosine and inner product are the same" | Same ranking only for unit-length vectors; <#> returns the negative inner product |
"WHERE narrows the ANN search" | With an approximate index it filters the candidates afterwards and can return too few rows |
| "IVFFlat can be created on an empty table" | Its centroids come from k-means over existing rows; build after loading |
| "More dimensions means better relevance" | It means more memory and latency; relevance depends on the model; truncation often loses little |
| "I can switch the query model and keep old vectors" | Different models live in different spaces; re-embed and re-index |
| "99% recall means 99% good answers" | It means the index matches exact search 99% of the time; relevance is a separate measurement |
| "Binary quantization is free" | It is lossy and needs high dimensions plus a re-rank step |
| "A vector database is always better than Postgres" | At moderate scale with relational filters, pgvector is often enough; at very large scale or with heavy filtered ANN, dedicated engines win |
| "Dedicated engines are consistent with my database" | They are a copy; freshness depends on your sync pipeline |
| "StreamingDiskANN ships with pgvector" | It comes from pgvectorscale, a separate extension |
Cheat sheet
| Topic | What to remember |
|---|---|
| Operators | <-> L2, <#> negative inner product, <=> cosine, <+> L1, <~> Hamming, <%> Jaccard |
| Operator class must match | vector_cosine_ops for <=>, vector_ip_ops for <#>, vector_l2_ops for <-> |
| Query shape for an index | ORDER BY embedding <op> :q LIMIT k, bare operator, ascending |
| HNSW defaults | m = 16, ef_construction = 64, hnsw.ef_search = 40 (range 1 to 1000) |
| IVFFlat rules | Build after load; lists = rows/1000 (or sqrt(rows) over 1M); probes about sqrt(lists) |
| Dimension limits | vector index 2000, halfvec index 4000, bit index 64,000, sparsevec 1000 non-zero |
| Storage | 4d + 8 bytes (vector), 2d + 8 (halfvec), d/8 + 8 (bit) |
| Build speed | Enough maintenance_work_mem, parallel workers, load before index, CONCURRENTLY in production |
| Filters | B-tree on filter, partial index, partition, or hnsw.iterative_scan |
| Iterative scans | off, relaxed_order, strict_order; bounded by hnsw.max_scan_tuples (20,000) |
| Per query settings | SET LOCAL inside a transaction, never plain SET on a pool |
| Measure recall | Exact baseline with enable_indexscan = off; recall@k over a sample of queries |
| Hybrid | Lexical + vector, fuse with RRF (1/(60+rank)), rerank the top |
| Model change | New column or table, backfill, new index, switch, drop; store embedding_model |
| Multi-tenancy | Shared index leaks recall between tenants; partition or partial index per tenant |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does ORDER BY 1 - (embedding <=> :q) DESC LIMIT 10 not use an HNSW index, and how do you fix it? Important
Answer
Answer: The planner needs the ORDER BY to be a bare distance operator in ascending order. Order by embedding <=> :q ascending and compute 1 - distance in the SELECT list.
2 — A query with WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10 returns 0 rows although the tenant has thousands of documents. Why, and what are three fixes? Important
Answer
Answer: HNSW returns ef_search (40) candidates for the whole table and the filter removes those of other tenants. Fixes: hnsw.iterative_scan = relaxed_order, a partial index or partition per tenant, a B-tree on tenant_id (so the planner can choose an exact plan), or a filter-aware engine.
3 — When are cosine and inner product rankings identical? Important
Answer
Answer: When all vectors are normalised to length 1. Then inner product is the cheapest operator; pgvector returns the negative inner product so index scans can run in ascending order.
4 — What is recall@10 and how do you measure it in Postgres? Must-know
Answer
Answer: The share of the exact top 10 that the approximate search also returned, averaged over many queries. Get the exact result with SET LOCAL enable_indexscan = off in a transaction and intersect the id lists.
5 — Why must IVFFlat be built after data is loaded? Must-know
Answer
Answer: Its lists centroids come from k-means over the existing rows. With too little data they are poor and recall is bad; the README says to drop the index until the table has more data.
6 — HNSW build takes 67 seconds instead of 7 seconds. What is the most likely cause? Important
Answer
Answer: maintenance_work_mem too small: the NOTICE "hnsw graph no longer fits into maintenance_work_mem after N tuples" appears. Raise it (without exhausting server memory) and use parallel workers.
7 — You switch embedding models from 1536 to 1024 dimensions. What is the safe sequence? Must-know
Answer
Answer: Add a new column or table, backfill in idempotent batches recording the model name, build the new index concurrently, compare results on sample queries, switch reads behind a flag, then drop the old column and index. Never mix models in one index.
8 — What does hnsw.iterative_scan = strict_order guarantee, and what does it not? Good to know
Answer
Answer: Results come back in exact distance order among the candidates scanned; it does not make the search exact or unbounded, because scanning stops at hnsw.max_scan_tuples.
9 — Why is a shared HNSW index across tenants a recall risk? Important
Answer
Answer: The graph is built over all vectors, so one tenant's vectors affect recall and speed for others; the README recommends list partitioning or separate tables.
10 — When is a dedicated vector database a better choice than pgvector? Must-know
Answer
Answer: When the vector workload dominates and needs its own scaling (hundreds of millions of vectors, high QPS), when filtered ANN at scale is central, or when you need its index types and quantization; otherwise keeping vectors with transactional data is a strong default.
11 — Why use Reciprocal Rank Fusion instead of adding BM25 and cosine scores? Good to know
Answer
Answer: The scores are on different scales; RRF uses only ranks (1/(k+rank), k = 60), so no normalisation or per-query tuning is required.
12 — How big is a 1536-dimension vector and a halfvec of the same size? Good to know
Answer
Answer: 4 * 1536 + 8 = 6152 bytes and 2 * 1536 + 8 = 3080 bytes.
Glossary
| Term | Meaning |
|---|---|
| Embedding | A fixed-length array of numbers a model produces for text, an image or audio so that similar items are close |
| Dimensionality | The length of an embedding; fixed by the model and a direct cost in memory and latency |
| Vector database | A system whose main job is storing embeddings and answering nearest-neighbour queries |
| kNN (exact) | Nearest-neighbour search that compares the query to every row; perfect recall |
| ANN | Approximate nearest neighbour search through an index; faster, may miss true neighbours |
| Recall (recall@k) | Share of the exact top-k that the approximate search returns |
| Latency (p50/p95/p99) | Query time percentiles |
| L2 / Euclidean distance | Straight-line distance, operator <-> |
| Inner product | Dot product; pgvector <#> returns its negative |
| Cosine distance | 1 minus cosine similarity, operator <=>; ignores length |
| L1 / taxicab distance | Sum of absolute differences, operator <+> |
| Hamming distance | Count of differing bits, operator <~> |
| Jaccard distance | 1 minus overlap over union of set bits, operator <%> |
| Operator class | The index definition tying an index to a distance function, for example vector_cosine_ops |
| HNSW | Hierarchical Navigable Small World: multilayer proximity graph index |
| Layer | One level of the HNSW graph; upper layers are sparse with long links |
m | HNSW maximum connections per layer (default 16) |
ef_construction | HNSW build-time candidate list size (default 64) |
hnsw.ef_search | HNSW query-time candidate list size (default 40) |
| IVFFlat | Inverted-file index with uncompressed vectors in lists |
lists | Number of k-means clusters in an IVFFlat index |
ivfflat.probes | Number of lists searched per query (default 1) |
| k-means | Clustering algorithm used to choose IVF centroids |
| Centroid | The centre of a list/cluster |
| Quantization | Storing vectors with fewer bits per element, lossy |
| Scalar quantization | Each float becomes an 8- or 4-bit integer |
| Product quantization (PQ) | Sub-vectors replaced by codebook indices |
| Binary quantization (BQ) | One bit per dimension, compared with Hamming distance |
| SBQ | Statistical Binary Quantization in pgvectorscale |
| Re-ranking | Re-scoring a shortlist with full-precision vectors |
halfvec | pgvector half-precision vector type |
sparsevec | pgvector sparse vector type, {index:value,...}/dims |
bit | Postgres bit string used for binary vectors |
| DiskANN | Microsoft graph index designed for SSD-resident data |
| StreamingDiskANN | pgvectorscale's DiskANN-inspired index (USING diskann) |
| pgvector | Open-source Postgres extension for vector types, operators and indexes |
| pgvectorscale | Timescale extension adding StreamingDiskANN, SBQ and label filtering |
maintenance_work_mem | Memory for index builds; the HNSW graph should fit |
| Post-filter | A WHERE applied after the ANN index returned its candidates |
| Pre-filter | A predicate applied before or during traversal |
| Iterative scan | pgvector 0.8 feature: keep scanning the index until enough rows pass the filter |
hnsw.max_scan_tuples | Cap on tuples visited by an iterative HNSW scan (20,000) |
| Partial index | An index with a WHERE predicate |
| List partitioning | PARTITION BY LIST; one partition per value, e.g. per tenant |
| Hybrid search | Lexical plus vector retrieval, fused |
| BM25 | Probabilistic lexical ranking function used by Lucene-based engines |
| RRF | Reciprocal Rank Fusion: sum of 1/(k+rank) over rankings, k = 60 |
| Cross-encoder / reranker | A model that scores query-document pairs to reorder top candidates |
| Chunking | Splitting documents into passages before embedding |
| RAG | Retrieval-augmented generation: retrieve passages, give them to an LLM |
| Matryoshka embedding | An embedding whose first dimensions are usable on their own, so it can be truncated |
| Model versioning | Recording which model produced each vector and migrating when it changes |
| MRR / nDCG / hit rate | Retrieval-quality metrics on labelled queries |
| TOAST | Postgres out-of-line storage for large values; STORAGE PLAIN disables it |
| Qdrant, Milvus, Weaviate, Pinecone, Vespa | Dedicated vector or search engines |
| Redis vector sets | Redis 8 data type holding elements with vectors (VADD, VSIM) |
dense_vector / knn | Elasticsearch field and search option; k and num_candidates control the ANN search |
AsVector | Laravel Eloquent cast between PHP arrays and the vector format |
whereVectorSimilarTo | Laravel query builder method for cosine-similarity search |
Schema::ensureVectorExtensionExists() | Laravel migration helper that enables pgvector |
| pgvector-go | Go package adding pgvector types for pgx, GORM, Bun, Ent, sqlx |
| Ollama | Local model server whose /api/embed endpoint returns embeddings |
References
- pgvector README (version 0.8.7): github.com/pgvector/pgvector
- pgvector-go README: github.com/pgvector/pgvector-go
- pgvectorscale README: github.com/timescale/pgvectorscale
- Redis vector sets README: github.com/redis/redis (modules/vector-sets)
- Elastic, kNN search documentation: elastic.co/docs/solutions/search/vector/knn
- Yu. A. Malkov and D. A. Yashunin, HNSW, arXiv:1603.09320: arxiv.org/abs/1603.09320
- G. V. Cormack, C. L. A. Clarke and S. Buettcher, Reciprocal Rank Fusion, SIGIR 2009: plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
- Qdrant, "What is a Vector Database?": qdrant.tech/articles/what-is-a-vector-database/
- Milvus documentation, "What is Milvus": milvus.io/docs/overview.md
- Pinecone, "What is a Vector Database & How Does it Work?": pinecone.io/learn/vector-database/
- PostgreSQL documentation,
SET: postgresql.org/docs/current/sql-set.html - Laravel 13: Search, Database Queries, Migrations, AI SDK, Release notes
- Go documentation,
database/sql: pkg.go.dev/database/sql