A search index is a precomputed shortcut from a question to its few best rows: an inverted index maps each word to the rows that contain it, a vector index maps a point in meaning-space to its neighbours, and every design on this page is a trade between how fresh, how exact and how cheap that shortcut is.
One question, two shortcuts, one SQL statement: the whole page on one picture. It searches the six stored questions that section 3 indexes (Q1 "What is the step by step guide to invest in share market?", Q2 "How do I invest in share market?", Q3 "... in stock market?", Q4 "How can I get started in stock market?", Q5 "What is the share market?", Q6 "What is the story of Kohinoor (Koh-i-Noor) Diamond?"); the timings are from the whole table.
invest, share, start. The inverted index (GIN) reads 3 postings lists, never the texts: the GIN lookup took 0.25 ms against 258 ms for LIKE.Every timing and score was measured for this page on PostgreSQL 18.6 with pgvector 0.8.7 over 522,931 real Quora questions (Apple M1 Pro, 2026-10-04) measured; times are plus or minus 30%: other jobs shared the machine. The six-question BM25, cosine and fusion values are computed from the same measured lexemes and embeddings. The faint points around the question are other stored questions, placed for illustration.
You need: tables, indexes and query plans from the parent Topic: databases; what an embedding is from Embedding models. How ANN indexes work inside (IVF, PQ, HNSW, DiskANN, filtered ANN) is Vector indexes from the inside's; this page uses them as Postgres and the vector databases ship them. Retrieval metrics (recall@k, nDCG) are defined on RAG and retrieval evaluation.
New terms, each defined where it first appears:
The running example. The parent page's chat product wants, when a user types a question, the earlier questions that ask the same thing (reuse an answer, merge duplicates, suggest help articles). The real stand-in is the public BEIR copy of Quora duplicate questions: 522,931 real questions plus 10,000 test questions whose true duplicates people labelled, so every method can be scored. Each question was embedded with all-MiniLM-L6-v2 (384 numbers, 142 seconds for the whole set on the laptop's GPU) and loaded into one table, q(id, body, embedding vector(384)) measured. The Retrievers side by side tab shows real test questions answered five ways, with the labelled duplicates marked.
| Piece | The problem it solves | How, in one line | What it costs here |
|---|---|---|---|
| Inverted index | LIKE '%word%' reads every row | Word to list of documents, built once; a query reads only the lists of its words | 20 MB of GIN index for 523k short questions; slower writes |
| BM25 | Thousands of matches: which first? | Rare words count more, repeats count less and less, long documents are discounted | Postgres's built-in ts_rank is not BM25 (no rarity weight) |
| Embeddings | "start investing in shares" should find "how do I invest in stock market" | A model maps meaning to a point; close points, close meaning | A model call per text; 1,544 bytes per 384-number vector |
| Exact kNN | Find the nearest vectors | Compare the question with every stored vector | 91 ms per query on 523k vectors |
| HNSW | Exact is too slow | A layered graph walked greedily towards the question | 0.76 ms at 0.989 recall; 1,069 MB index, 61 s to build |
| Filtered search | "Nearest, but only this user's" | Iterative index scans, or a plain index then exact search | Naive post-filtering returned 0.38 rows of 10 at a 1% filter |
| Hybrid search | Words and meaning each miss things | Run both, fuse the rankings with RRF | Two queries; not always a win (SciFact yes, Quora no) |
The user types "How do I start investing in shares?". Stored are "How do I invest in share market?" (three shared words) and "How do I invest in stock market?" (one shared word, same meaning). A good search returns both above "What is the share market?", which shares words but asks something else.
Compares words. Exact, explainable ("it matched invest and share"), cheap, no model, and strong on names, codes, error messages and rare terms (ERR_SSL_PROTOCOL, a product SKU). Blind to synonyms: "stock" is not "share".
Compares meaning through embeddings. Finds paraphrases and other languages, works on images. Needs a model at write and query time, is hard to explain, and can miss exact identifiers (a part number embeds close to other part numbers).
Each side needs a way to find candidates fast (an index) and a way to order them (a score): sections 2 to 6 for words, 7 to 10 for vectors, 11 combines them, 12 and 13 choose and run the system.
Before text can be indexed it is cut into the units a search compares: analysis (Lucene's word; Postgres says a parser plus dictionaries). It runs twice, when a document is stored and when a query arrives, and if the two runs differ nothing matches. The figure beside this text puts the running question through PostgreSQL 18.6's English configuration, read from its ts_debug output measured.
Postgres stores the result as a tsvector, sorted lexemes with word positions, and turns a query into a tsquery by the same rules, with & (and), | (or), ! (not) and <-> (followed by): plainto_tsquery('english', 'how do I invest in the share market') gives , every remaining word required.
default_text_search_config, which initdb sets from the server's locale; the built-in fallback is simple, which lower-cases but neither stems nor drops stop words (PostgreSQL docs, 12.1 and 19.11). Name the configuration in both index and query (to_tsvector('english', body)): an index built under one configuration is not used by a query written under another.Tokens are usually words and numbers, with punctuation-aware pieces (an email address, a hyphenated word, a URL); normalising lower-cases and often strips accents. Lemmatisation instead looks words up in a dictionary to return the real base form ("better" to "good"); it is slower and language-specific (Manning, Raghavan and Schuetze, section 2.2.4). A stored question with a hyphenated name, as ts_debug prints it: the hyphenated word is kept whole and as its parts.
Stored as .
Seven words become three lexemes: stop words vanish, endings are cut
english.stop list has 127. A stemmer cuts endings by rule so "investing" and "invests" become one lexeme, invest (the classic is Porter (1980), now its successor Snowball); it can produce non-words ("stori" for "story").An inverted index is the index at the back of a book: a dictionary of every term and, for each, a postings list, the sorted ids of the documents that contain it, usually with how often (term frequency) and where (positions). "Inverted" because a document maps to its words and the index maps each word back. The figure builds one for six real questions (rows are lexemes, columns are questions, a block's height is the term frequency), answers the running query, then runs the same query without an index.
invest, share and start. The same tokeniser must run at index time and at query time, or nothing matches.LIKE '%invest%'. Without an inverted index the database must read every stored text and look for the substring, character by character. A substring test also knows nothing about words: "invest" matches "investing" only because it is a prefix; "shares" would not match "share".Lexemes and positions printed by Postgres to_tsvector('english', ...) for six real Quora questions measured; the last step but one ranks with the BM25 formula of section 4.
Predict, then look: on the whole table, how much faster is the GIN lookup for "diamond" than a scan with ILIKE '%diamond%': ten times, a hundred, a thousand?
Postgres keeps postings in a GIN (generalized inverted) index, "the preferred text search index type" (PostgreSQL docs, 12.9). On the 522,931 rows, the stored tsvector column took 6 s and 43 MB to add, and the GIN index 0.6 s and 20 MB for 87,014 distinct lexemes measured. The cost moves to writes: every insert adds an entry to the postings list of each of its words, which GIN softens with a pending list merged later (Storage engines and indexes owns GIN's pending list and fastupdate).
Ids in a postings list are sorted, so engines store the gaps between them (5, 9, 12 becomes 5, 4, 3) in as few bits as each gap needs; common words compress best. Lucene adds skip data so an AND query can jump through a long list instead of reading it all (Lucene postings format). Postgres's GIN is a B-tree over the terms whose leaf entries hold the posting list, or a pointer to a posting tree when the list is long. GiST can also index a tsvector, but it stores a fixed-size signature per document, so it is lossy and every hit must be rechecked.
Lucene never edits an index file in place: new documents go to a new small segment, deletes are marks, and segments are merged in the background, the write pattern of the LSM-trees taught on Storage engines and indexes. Section 6 steps through it.
The index reads a few postings; the scan reads all 522,931 texts (about a thousand times slower)
ILIKE (155 rows) also matched "TheDiamondMinecart", a channel name the tokeniser keeps as one word; full-text (154) matches "diamonds" too, by stemming. A trigram index (section 5) is how to make arbitrary LIKE '%...%' fast when you truly need substrings.The index finds the matches; it does not order them. Three intuitions, each fixing the flaw of the one before: term frequency (a text using the word more is more about it, but "the" would win and ten mentions are not ten times better); inverse document frequency (a word in few documents tells more: "start" in 1 of 6 questions beats "invest" in 3 of 6; tf times idf is TF-IDF); and saturation with length normalisation (repeats level off, and a long text that mentions a word once counts less than a short one). BM25 puts all three in one formula and is the default ranking in Lucene, Elasticsearch (since 5.0, docs) and OpenSearch. The figure draws the part of BM25 that depends on a document: how it grows with repeats and shrinks with length.
The whole formula, with the six questions worked in the card beside it (move k1 and b):
ts_rank (term frequency, optionally weighted by document part) and ts_rank_cd (cover density: how close the matched terms sit), and "the ranking functions do not use any global information" (PostgreSQL docs, 12.3.3): no idf, so "market" counts as much as "kohinoor". On 1,000 Quora test questions, ranking the OR-matches by ts_rank scored nDCG@10 0.627; BM25 over exactly the same Postgres lexemes scored 0.733 measured. Same tokens, same matches, different order. For real BM25 inside Postgres use an extension (ParadeDB's pg_search, section 6) or compute it yourself. nDCG@10 is 1 when the labelled relevant results fill the top in the ideal order, discounted further down.The BM25 knobs swept on real data, and why the tokeniser matters more than k1 and b, are on The retrieval pipeline (its section 2); this page keeps BM25 as Postgres and Lucene configure it.
BM25 ("Best Match 25") comes from the Okapi system at City University London, first run at TREC-3 in 1994; theory in Robertson and Zaragoza 2009. Lucene's BM25Similarity uses this idf and these defaults. Since Lucene 8.0 it drops the (k1+1) factor from the numerator, which multiplies every score by the same constant and so "doesn't affect ordering" (CHANGES.txt, LUCENE-8563); this page keeps the textbook form. Lucene also stores each document's length in one byte, so its lengths are slightly rounded.
BM25 on the six questions. Query "How do I start investing in shares?", lexemes from Postgres. Predict before you drag: with b at 0, does the long "step by step guide" question rise or fall?
At b = 0 the long question rises, because its length no longer counts against it; at k1 = 0 every match of a term scores just its idf. "start" (in one question) carries the largest idf, which is why "How can I get started in stock market?" ranks high on one word.
Phrases work because postings keep positions: phraseto_tsquery('english', 'share market') becomes ("share" immediately followed by "market") and matched 86 questions, against 157 that merely contain both words measured. websearch_to_tsquery takes what users type: "share market" -india or stocks becomes . Prefixes: to_tsquery('english', 'invest:*') matches every lexeme starting with invest, Postgres's search-as-you-type, supported by GIN.
Typos are not fixed by stemming: "kohinor diamnd" matched 0 questions through full-text measured. Postgres's pg_trgm cuts words into overlapping three-letter pieces and counts the shared ones (show_trgm('kohinor') is ); with a GIN trigram index (3 s to build, 82 MB) the misspelt query found these in 7 ms measured:
Word similarity: the share of trigrams in the best-matching stretch of the question; this run kept results at 0.5 or more (the default threshold for <% is 0.6, docs). A common production pattern: try full-text first, fall back to trigrams when it returns nothing. Search engines use edit distance instead (Levenshtein: single-letter insertions, deletions or substitutions): Lucene's fuzzy queries allow up to 2 edits (FuzzyQuery: maxEdits is capped at MAXIMUM_SUPPORTED_DISTANCE, 2); Meilisearch allows 1 typo in words of 5 or more letters and 2 from 9 letters by default (Meilisearch docs).
Most large search deployments use a separate search engine built on Apache Lucene, a Java library of inverted indexes, BM25 and, since 9.0 (2021-12-07), HNSW vector search. Elasticsearch and its fork OpenSearch wrap it in a distributed JSON server. What surprises people coming from Postgres is the write path: a write is durable at once but searchable only later. The figure steps one document through a shard.
index.translog.durability: request), the same idea as Postgres's write-ahead log. It is durable now, but no search can find it.The clock in the figure is illustrative; the defaults are Elastic's: index.refresh_interval, near real-time search, translog.
Three consequences follow. A write acknowledged now may not appear in a search for about a second: near real-time, where Postgres full-text is consistent with the last commit. An index is split into a fixed number of primary shards at creation (changing it needs the split or shrink APIs, docs), each copied to replicas that refresh independently, so two identical searches can briefly disagree: reads are eventually consistent. And reindexing is routine: an existing field's type or analyser cannot change in place, so you create a new index, copy every document with the Reindex API, and switch an alias (docs; section 13 draws it).
| Choose | When | What you give up |
|---|---|---|
| Postgres full-text (tsvector, GIN) | Search over data already in Postgres, modest volume, filters and joins with business rows, results consistent with the last commit | BM25 (only ts_rank), typo tolerance beyond pg_trgm, facets at scale, depth of language analysis |
| Elasticsearch / OpenSearch | Large volumes, logs, facets and aggregations, many languages, relevance tuning, horizontal scale | A second system to run and feed; about one second of staleness; reindexing on every mapping change |
| Typesense / Meilisearch | Product or help-centre search-as-you-type that fits on one machine | Scale beyond one node's memory (Typesense); log analytics |
| ParadeDB pg_search | BM25 quality while staying in Postgres | A young extension (0.x, AGPL); a heavier index to maintain on writes |
Versions are in the one dated table of section 12.
A vector is an ordered list of numbers; an embedding model is trained so that texts with similar meaning get vectors pointing in similar directions. all-MiniLM-L6-v2 turns the running question into 384 numbers, the first eight , with length (norm) 1.0000 because the model normalises its output. No single number means anything on its own; only distances between vectors do. Training, choosing and judging models is Embedding models's. For the test question "Which question should I ask on Quora?" the three nearest stored questions by cosine were "What question can I ask on Quora?" (0.886), "What is the best question to question on Quora?" (0.854) and "What's the best question to ask in Quora?" (0.848) measured.
| Measure | Formula | pgvector operator | Reads as |
|---|---|---|---|
| Dot product | a·b = Σ aibi | <#> (returns the negative, so smaller is closer) | bigger is closer; depends on length too |
| Cosine | a·b / (|a| |b|) | <=> returns 1 − cosine | the angle only |
| Euclidean (L2) | √Σ(ai−bi)2 | <-> | straight-line distance |
<#> took 76 ms against 91 ms with cosine measured. Without normalisation dot product favours long vectors, and length can carry meaning (some recommendation models let it encode popularity): use the measure the model was trained with, and index with the matching operator class, or the index is not used.What a vector costs. pgvector stores a vector(n) as 4 bytes per number plus 8 of header: 384 × 4 + 8 = 1,544 bytes (confirmed by pg_column_size measured), and 6,152 for the common 1,536-dimension models (README). The 522,931 vectors take 807 MB, 78% of the whole 1,031 MB table: the texts are tiny next to them. At 100 million 1,536-dimension vectors that is 615 GB before any index.
Exact k-nearest-neighbour (kNN) search computes the distance to every stored vector: 522,931 × 384 = about 201 million multiply-adds per query. Postgres ran ORDER BY embedding <=> $1 LIMIT 10 as a parallel sequential scan with a top-N heap sort, reading 126,020 pages of 8 KB from memory, in 91 ms median (118 ms p95) measured: fine for a nightly job, too slow for a search box, and linear in the table. An approximate nearest-neighbour (ANN) index looks at a small part of the data and sometimes misses a true neighbour; its quality is recall@k, the share of the true k nearest it returns. Quote recall and latency together: any index is fast at low enough recall.
pgvector offers two ANN indexes and you choose one (there is no default). HNSW is a layered graph of near neighbours walked greedily; hnsw.ef_search (default 40) is the number of candidates a query keeps, its recall dial. IVFFlat files each vector under its nearest of lists k-means centroids and scans the closest ivfflat.probes lists (default 1). How both work inside is taught on Vector indexes from the inside (IVF in section 3, HNSW in section 6, on the same 522,931 Quora vectors). Here is what they buy in Postgres. Predict: at the defaults, how many times faster than exact is HNSW, and what share of the true top 10 does it return?
CREATE INDEX q_hnsw ON q USING hnsw (embedding vector_cosine_ops); -- m 16, ef_construction 64 SET hnsw.ef_search = 40; -- per session, or SET LOCAL per transaction SELECT id FROM q ORDER BY embedding <=> $1 LIMIT 10;
HNSW at its defaults is about 119 times faster than exact and finds 98.9% of the true top 10
Every point measured on PostgreSQL 18.6 with pgvector 0.8.7: 1,000 test queries, recall@10 against exact search computed outside the database, latency of the whole SQL query from a client on the same machine (second pass, warm; shared_buffers 4 GB holds the table and every index) measured. Slide HNSW m 16 from ef_search 10 to 640, then pick IVFFlat and the binary index.
| Knob (pgvector name) | Default | What it does | Raising it costs |
|---|---|---|---|
m | 16 | links per vector per layer; layer 0 keeps up to 2·m (pgvector's HnswGetLayerM, as the paper recommends) | build time, index size, slower inserts |
ef_construction | 64 | candidate list size while inserting | build time |
hnsw.ef_search | 40 | candidate list size per query; also caps the rows one index scan returns | query latency |
lists (IVFFlat) | none: you set it | number of k-means cells, fixed at build time | build time; too many makes each probe miss more |
ivfflat.probes | 1 | lists scanned per query | query latency |
The README's starting points for IVFFlat: lists = rows / 1000 up to 1M rows, √rows above; probes = √lists (README, IVFFlat). Build it after the data is loaded, or the centroids describe the wrong data, and rebuild it as new data drifts away from them. HNSW (Malkov and Yashunin, arXiv 2016) has no training step, so it can be created on an empty table; builds are slower, the graph is fastest in RAM, every insert searches the graph, and deletes leave holes repaired only by VACUUM (section 13).
Exact search is still right when the set is small (thousands to roughly 100,000 vectors; the old page's "below about 100k" is a rule of thumb, not a measured line: at 100k vectors of 384 numbers it would be about a fifth of the time measured here), when a filter has already cut the candidates to a few thousand (section 10), and for the ground truth that measures an ANN index's recall.
Not in pgvector: product quantisation, int8, a disk-resident graph. Tiger Data's open pgvectorscale extension adds a StreamingDiskANN index (GitHub); Azure Database for PostgreSQL has pg_diskann (GA May 2025); Google AlloyDB has the alloydb_scann index (AlloyDB docs).
alloydb_scann extension (formerly postgres_scann), a managed-service feature.Most of the memory is the vectors themselves, so quantisation, fewer bits per number, is the lever (how scalar, binary and product quantisation work is Vector indexes from the inside's sections 4 and 5). pgvector offers two forms beside float32 vector (6,144 bytes of floats at 1,536 dimensions): halfvec (float16, 0.7.0+), 3,072 bytes, with a very small recall loss, and it lifts HNSW's limit from 2,000 to 4,000 dimensions; and bit via binary_quantize (the sign of each number), 192 bytes, compared by Hamming distance. Both are on the chart above.
Binary needs re-ranking, and a model that tolerates it. Alone, the 1-bit index found 0.728 of the true top 10: 384 signs keep too little of a small model's meaning. Fetching more candidates by Hamming distance and re-ordering them with the full vectors recovers it (0.984 with 100 candidates, 0.997 with 400) measured; larger models lose less.
CREATE INDEX ON q USING hnsw ((binary_quantize(embedding)::bit(384)) bit_hamming_ops); SELECT id FROM ( SELECT id, embedding FROM q ORDER BY binary_quantize(embedding)::bit(384) <~> binary_quantize($1) LIMIT 100 -- needs hnsw.ef_search >= 100 ) s ORDER BY embedding <=> $1 LIMIT 10;
Indexes on an expression, so the table keeps full float32 vectors for re-ranking measured:
Fewer dimensions. Models trained with Matryoshka representation learning (Embedding models) keep a usable embedding in the first 256 or 512 numbers: index subvector(embedding, 1, 256)::vector(256) and re-rank with the full vector. all-MiniLM-L6-v2 was not trained this way, so it was not tested here. A 3,072-dimension vector exceeds HNSW's 2,000 limit for vector: index it as halfvec or shortened.
Real queries carry conditions: "nearest questions from this workspace". An ANN index orders by distance only and knows nothing of tenant_id. The general strategies (post-filter, pre-filter, filter-aware graphs such as ACORN) and where each breaks are Vector indexes from the inside's section 9; in pgvector they come down to three choices:
ef_search candidates, then WHERE drops the rest. If the condition keeps 1% of rows, the 40 candidates of a default scan hold on average 0.4 matching rows (pgvector README, Filtering).hnsw.iterative_scan = strict_order or relaxed_order resumes the scan until enough rows pass, up to hnsw.max_scan_tuples (20,000 by default).Predict before you look: with a filter that keeps 1% of rows and iterative scans off, how many of the 10 requested rows come back? The figure lays out the 1,000 stored vectors nearest one query in the order an HNSW scan meets them, 40 to a row; the tenant's rows are green (their positions are illustrative, every number is measured over 1,000 test queries, as in the chart further down).
ef_search of 40 the scan hands over its 40 nearest candidates and the filter keeps the tenant's: 0.38 rows on average instead of 10, none at all for 68% of queries, recall 0.04, in 0.99 ms. Fast and wrong.hnsw.iterative_scan on, the scan resumes batch after batch until 10 rows pass, about 1,000 candidates at a 1% filter (capped by hnsw.max_scan_tuples, 20,000). strict_order returned 10 rows at recall 0.935 in 22.7 ms; relaxed_order at recall 0.975 in 15.6 ms.EXPLAIN ANALYZE: Rows Removed by Filter: 41, rows=0): it assumes the index scan can return as many rows as it needs, while it stops at ef_search candidates.SET hnsw.iterative_scan = relaxed_order; (wrap in a materialised CTE and re-sort if exact order matters, as the README shows).EXPLAIN ANALYZE: Rows Removed by Filter: 41, rows=0) measured. The planner does not know the index scan stops at ef_search candidates. Check the plan, and force the pre-filter with a materialised CTE when you know the filter is selective.CREATE INDEX ... WHERE tenant_id = 7); for many, list partitioning by tenant so each partition has its own small index. The README notes that a shared index lets one tenant's vectors affect another's recall and speed.Post-filtering a 1% filter returns almost nothing; iterative scans and pre-filtering fix it at different prices
tenant column (row id modulo 100 keeps 1%, modulo 10 keeps 10%), HNSW at defaults, recall against the exact filtered top 10 measured. Bar length is recall; the label adds rows returned of 10 and median latency. Pre-filtering wins when the filter is selective (exact search over about 5,230 rows is cheap) and loses at 10% (about 52,300 distances per query).With a 1% filter and iterative scans off, the HNSW scan returned 0.38 rows on average instead of 10 (68% of queries returned nothing; recall 0.04). strict_order returned 10.00 rows at recall 0.935 in 22.7 ms; relaxed_order 10.00 rows at recall 0.975 in 15.6 ms; the B-tree pre-filter with exact search was always right (recall 1.000) in 6.6 ms. With a 10% filter and iterative scans off, the HNSW scan returned 3.97 rows on average instead of 10 (1% of queries returned nothing; recall 0.40). strict_order returned 10.00 rows at recall 0.961 in 1.6 ms; relaxed_order 10.00 rows at recall 0.979 in 1.6 ms; the B-tree pre-filter with exact search was always right (recall 1.000) in 154.0 ms. Iterative scans fix the empty results; the price is latency and, at the 1% filter, the 20,000-tuple scan limit. Pre-filtering wins when the filter is selective, because exact search over about 5,230 rows is cheap; at 10% it must compute about 52,300 distances per query.
BM25 misses paraphrases ("stock" for "share"); vectors miss exact identifiers and rare names. The two scores cannot be added (a BM25 of 12.3 and a cosine of 0.81 are on unrelated scales), so the usual merge is reciprocal rank fusion (RRF) (Cormack, Clarke and Buettcher, SIGIR 2009): each document scores Σ 1 / (k + rank) over the lists it appears in, with k = 60. Why that works, what it throws away and the score-fusion family it competes with are The retrieval pipeline's (section 4). This section measures it in Postgres, on 1,000 Quora test questions and all 300 SciFact claims over 5,183 scientific abstracts (the set the evaluation page uses), top 100 from each retriever. Predict: does fusion beat the better single retriever on both?
Fusion wins when both retrievers are comparably strong (SciFact), and costs a little when one is much stronger (Quora)
The SQL you would deploy is one statement (the pattern of pgvector-python's RRF example). Its lexical half ranks by ts_rank, so it inherits section 4's weakness; it scored 0.823 on Quora at 15.4 ms median measured:
WITH lex AS ( SELECT id, row_number() OVER (ORDER BY ts_rank(tsv, query) DESC) AS r FROM q, websearch_to_tsquery('english', $1) query WHERE tsv @@ query ORDER BY ts_rank(tsv, query) DESC LIMIT 100), sem AS ( SELECT id, row_number() OVER (ORDER BY embedding <=> $2) AS r FROM (SELECT id, embedding FROM q ORDER BY embedding <=> $2 LIMIT 100) s) SELECT coalesce(lex.id, sem.id) AS id, coalesce(1.0 / (60 + lex.r), 0) + coalesce(1.0 / (60 + sem.r), 0) AS score FROM lex FULL JOIN sem USING (id) ORDER BY score DESC LIMIT 10;
The measured version OR-ed the query's lexemes instead of websearch_to_tsquery's AND, because AND left half the Quora questions with no lexical match. On Quora, where duplicates are paraphrases, the right weight for BM25 would be low; on SciFact, where claims share rare terms with their abstracts, BM25 earns its place. After fusion many systems re-order the top 20 to 100 with a cross-encoder reranker (Rerankers and late interaction); learned sparse vectors (SPLADE-style, stored in pgvector as sparsevec) are a third retriever some teams add (the same page's section 10).
On Quora, vectors beat BM25 (nDCG@10 0.839 against 0.733) and fusion landed between them (0.825). On SciFact, BM25 beat vectors (nDCG@10 0.686 against 0.645) and fusion beat both (0.714). Per question on Quora, BM25 was better on 150, vectors on 388, and they tied on 462: the two retrievers fail on different questions, which is what fusion exploits when both are comparably strong (SciFact) and why an equal-weight fusion costs a little when one is much stronger (Quora). Requiring every word (fts_and) or ranking without idf (fts_or) costs the most; the HNSW index (ef_search 100) gave up little against exact vector search.
A "vector database" is an ANN index plus storage, filtering and an API, run as its own system; pgvector adds the same index types to the Postgres you may already run. Most of them run HNSW, so the comparison is about where the data lives, how filters and tenants are handled, and what you pay for, not about the algorithm.
Where the data lives sets the cost: memory-resident designs pay for RAM per vector, object-storage designs pay with a slow first query
| System | Index and filtering | Multi-tenancy | Consistency | You pay mostly for |
|---|---|---|---|---|
| pgvector | HNSW, IVFFlat; iterative scans for filters; halfvec, bit, sparsevec | a tenant_id column with partial indexes or list partitions (section 10) | Postgres transactions: vector, text and metadata change together | RAM for the HNSW index on your Postgres server |
| Qdrant | HNSW per segment, filters checked during traversal; scalar, binary and product quantisation | one collection with a tenant payload field (is_tenant co-locates a tenant's vectors), or a shard per large tenant (guide) | no multi-point transactions; replicas favour availability by default | RAM to cache the memory-mapped vectors |
| Weaviate | HNSW, flat, dynamic; ACORN filtering; BM25 and hybrid built in | a shard per tenant; tenants can be ACTIVE, INACTIVE (on disk) or OFFLOADED to S3 (docs) | leaderless replication, tunable levels | RAM for each active tenant's HNSW |
| Milvus | HNSW, IVF variants, DISKANN, SCANN, GPU CAGRA | database (64 by default), collection (65,536), partition (1,024 per collection), or a partition key for millions of tenants (docs) | default "bounded staleness": a search can miss very recent writes | a cluster of components on Kubernetes, with object storage underneath |
| Turbopuffer (service) | SPFresh centroid index; BM25 inverted index; exact metadata filters | a namespace per tenant, each its own object-storage prefix | strong by default, eventual on request | object storage plus queries; the cost advantage is the vendor's claim |
Will the index fit? Using the measured HNSW size at 384 dimensions (2,045 bytes per vector, 1,544 of them the vector), the links cost about 501 bytes per vector, so 10 million 1,536-dimension vectors need about 67 GB of index (plus the same again in the table) and 100 million about 665 GB. Predict 10 million at halfvec, then set it. derived, an estimate
| System | Version (date) | What it is, licence | Notes |
|---|---|---|---|
| pgvector | 0.8.7 (2026-10-01) | Postgres extension, PostgreSQL licence | measured on this page |
| Qdrant | 1.19.1 (2026-09-04) | Rust server, Apache 2.0 | |
| Milvus | 3.0.2 (2026-09-20) | distributed, Apache 2.0, many components on Kubernetes | |
| Weaviate | 1.39.8 (2026-10-01) | Go server, BSD-3 core | |
| LanceDB | 0.39.0 (2026-09-17) | embedded library over the Lance columnar format, Apache 2.0 | IVF_PQ by default, IVF-HNSW variants; files on S3; each write is a new table version |
| Pinecone | service | serverless: immutable "slabs" on object storage plus a memtable | internals not published; namespaces per tenant; officially eventually consistent; pod-based indexes are legacy |
| Vespa | 8.x | search and ranking engine, Apache 2.0 | modified HNSW plus exact; text, vectors and ML ranking in one query; writes synced before ack |
| Elasticsearch / OpenSearch | 9.5.4 / 3.9.0 (late September 2026) | section 6 | Lucene HNSW; ES defaults to BBQ (binary) for 384+ dimensions since 9.1, int8 below; OpenSearch defaults to Faiss; near real-time |
| Apache Lucene | 10.5.2 (latest on 2026-10-04) | Java library, Apache 2.0 | Lucene news |
| Typesense | v30.2 (2026-04-19) | C++, GPL-3.0 | in-memory, one node |
| Meilisearch | v1.54.3 (2026-10-01) | Rust, MIT AND BUSL-1.1 | |
| ParadeDB pg_search | v0.26.0 (2026-10-03) | Postgres extension, AGPL-3.0 | still 0.x |
| pgvectorscale | v0.9.1 (2026-09-04) | Postgres extension (Tiger Data) | StreamingDiskANN |
Versions and consistency are from the parent page's Database atlas (open the atlas tab there for licences, Jepsen results, scaling and "reach for it / avoid when"); index facts from each vendor's docs: Qdrant, Milvus, Weaviate, LanceDB, Pinecone, Vespa, Elasticsearch, OpenSearch.
Both kinds of index get rebuilt: a search engine when a mapping or analyser changes, a vector index when the embedding model changes (vectors from two models are not comparable). The safe pattern is the same in both: build the new one beside the old, compare, switch, drop.
Never rebuild in place: run old and new side by side and switch in one step
COPY loaded the 522,931 rows in 3.3 s measured.maintenance_work_mem". A 200,000-row copy built in 22 s with 2 GB and 87 s with 64 MB, where Postgres printed "hnsw graph no longer fits into maintenance_work_mem after 28373 tuples" measured. Not so high that a build exhausts the server.max_parallel_maintenance_workers (here 3, plus the leader).CREATE INDEX CONCURRENTLY builds without locking out inserts (slower, and a failure leaves an invalid index to drop); watch pg_stat_progress_create_index.REINDEX 22 s measured; the README advises REINDEX INDEX CONCURRENTLY before VACUUM when vacuuming is slow. Lucene has the same problem as dead documents waiting for a merge (section 6).SET enable_indexscan = off in a transaction, or on a replica) and compare with the index's answer; keep a labelled set of 100 to 1,000 real queries and rescore it after every model, index or parameter change (the evaluation page shows how). Set ef_search per query with SET LOCAL, so a high-recall feature does not slow every other query. Check pg_relation_size of each vector index against shared_buffers and RAM: an HNSW index that falls out of memory turns page reads into SSD reads at every hop.What teams do in production (2026). Postgres first: pgvector beside the data, HNSW at defaults with the operator class matching the model, iterative scans on for filtered queries, and the labelled set before any tuning. Hybrid (BM25 from a search engine or pg_search, plus vectors, fused with RRF, then a reranker when quality matters more than a few tens of milliseconds) is the usual start for user-facing search, kept only if it beats the better single retriever. The search engine is fed from the primary database, never written to directly, and can be rebuilt at any time. halfvec for storage, binary or int8 for the index and full vectors for re-ranking once memory is the cost. Tenants isolated by design: partitions or partial indexes in Postgres, namespaces in Pinecone and Turbopuffer, a shard per tenant in Weaviate, a tenant payload field in Qdrant.
LIKE '%word%' as search: it scans every row, matches substrings, ignores stemming and ranks nothing (258 ms against 0.25 ms with GIN).to_tsvector('english', body) is not used by a query on to_tsvector(body) under another default, and stems differ.LIMIT 100 with the default ef_search of 40 returns at most 40 rows (pgvector README, Troubleshooting); raise ef_search to at least the LIMIT.vector_l2_ops is not used by ORDER BY embedding <=> $1, which silently falls back to a sequential scan; and the ORDER BY must be the bare operator ascending (not 1 - (a <=> b) DESC).| Quantity | Value | Source |
|---|---|---|
Bytes per pgvector vector(n) | 4n + 8 (384: 1,544; 1,536: 6,152) | README; measured |
| HNSW dimension limit in pgvector | 2,000 (vector), 4,000 (halfvec), 64,000 (bit) | README |
| pgvector HNSW defaults | m 16, ef_construction 64, ef_search 40 | README |
| Exact kNN, 523k × 384, in memory | 91 ms median | measured |
| HNSW at defaults, same data | 0.76 ms median, recall@10 0.989 | measured |
| HNSW build, 523k × 384, 4 processes | 61 s, 1,069 MB | measured |
| Elasticsearch refresh interval | 1 s | Elastic docs |
| BM25 defaults | k1 1.2, b 0.75 | Lucene |
| RRF constant | k = 60 | Cormack et al. 2009 |
| Compression | halfvec 2×, int8 4×, binary 32×, PQ 64× (96 codes for 1,536-d) | derived |
| 100M × 1,536-d float32 | 615 GB before any index | derived |
Real test questions from BEIR Quora (522,931 stored questions) and BEIR SciFact (5,183 abstracts), each answered by five retrievers in PostgreSQL 18.6 with pgvector 0.8.7; results that human annotators labelled relevant are in green measured. Questions were picked at random among those where BM25 clearly beat vectors, where vectors clearly beat BM25, where fusion beat both, and where all failed, so this is a gallery of differences, not an average: the averages are in the table at the bottom. Two randomly drawn Quora questions on adult topics were left out of the gallery; they remain in the averages.
fts_and: plainto_tsquery (every word required), ranked by ts_rank. fts_or: the query's lexemes OR-ed, ranked by ts_rank (no idf). BM25: k1 0.9, b 0.4 (the values Anserini uses for BEIR) over the same Postgres lexemes, computed outside the database. Vector: exact cosine on all-MiniLM-L6-v2. Hybrid: RRF (k 60) of BM25 and vector, top 100 of each. Retrieval metrics are defined on the RAG and retrieval evaluation page.
Real labelled questions answered by full-text, BM25, vector and hybrid retrieval, with the averages. About 5 minutes.
The from-zero overview this page deepens. Its Database atlas tab compares about 50 systems including every search engine and vector store named here (licences, consistency, Jepsen results, "reach for it / avoid when"); its Query plans tab teaches reading EXPLAIN ANALYZE. Root page, plus the tabs.
Pages, B-trees, LSM-trees, the WAL; GIN's pending list, GiST, BRIN internals; the LSM write pattern that Lucene segments follow. Child page, about 42 minutes.
Queries, joins, schema design, migrations (adding a column and backfilling it, as a re-embedding needs). Child page, about 48 minutes.
Why the planner picks a plan, statistics, reading EXPLAIN; useful when a vector or full-text index is not used. Child page, about 45 minutes.
VACUUM, memory settings, replicas, upgrades: the operations an HNSW index depends on. Child page, about 43 minutes.
Semantic caching reuses this page's nearest-neighbour search to answer repeated LLM questions. Child page, about 43 minutes.
Read replicas and sharding (Citus), the ways to scale pgvector past one machine. Child page, about 45 minutes.
Columnar formats, including Lance under LanceDB. Child page, about 46 minutes.
Document and key-value stores, several of which now ship vector search. Child page, about 46 minutes.
ACID, MVCC, the isolation anomalies measured, locks, deadlocks and retries. Child page, about 43 minutes.
Owns retrieval metrics (recall@k, nDCG, MRR), reproduces BM25, dense and hybrid runs on three BEIR sets against Anserini and MTEB, and RAG faithfulness. About 22 minutes.
Chunking, embedding model choice, reranking and the rest of retrieval-augmented generation. Topic page, about 21 minutes.
Owns the ANN internals this page uses as products: IVF (section 3), quantisation and IVF-PQ (sections 4 and 5), HNSW read in hnswlib's code (section 6), DiskANN, ScaNN, filtered ANN (section 9) and the memory formulas, each with its visual inline, plus a Frontier tab. Child of Topic: rag-and-retrieval, about 34 minutes.
Where the vectors stored here come from: contrastive training, hard negatives, Matryoshka dimensions, and choosing a model on your own data. Child of Topic: rag-and-retrieval, about 27 minutes.
Owns fusion (section 4: RRF against score fusion, tuned on held-out queries) and BM25's knobs swept on SciFact (section 2); this page's hybrid section measures fusion in Postgres. Child of Topic: rag-and-retrieval, about 44 minutes.
Cross-encoders after fusion, ColBERT, and learned sparse retrieval with SPLADE (section 10), the third retriever section 11 mentions. Child of Topic: rag-and-retrieval, about 32 minutes.
Where retrieval sits in an LLM service. Child page, about 28 minutes.
The outbox and change data capture, the ways to keep a search index in step with Postgres. Child page, about 40 minutes.
Working sets and memory under load, for sizing an index that must stay in RAM. Child page, about 39 minutes.
Lewis et al. 2020, the paper that named RAG; dense retrieval feeding a generator. Paper page.
The reference for everything pgvector on this page: types, operators, HNSW and IVFFlat options, filtering, iterative scans, quantisation. About 30 minutes.
The paper behind nearly every vector index in production. About 45 minutes.
Billion-scale graph search from SSD (NeurIPS 2019). About 40 minutes.
The compression behind IVF-PQ (TPAMI 2011). About 45 minutes.
The theory of BM25 from its authors (2009). About 2 hours.
Four pages, the fusion formula with k = 60 (SIGIR 2009). About 10 minutes.
tsvector, tsquery, configurations, ranking and GIN, chapter 12. About 60 minutes.
Segments, refresh and why a write is searchable a second later. About 10 minutes.
The standing recall against queries-per-second comparison across ANN libraries; read the Pareto curves. About 20 minutes.
Binary and int8 quantisation measured, with re-scoring (2024-03-22). About 25 minutes.
The textbook: chapters 1 to 7 cover inverted indexes, tokenisation, scoring. Free online. Several hours; chapter 1 about 40 minutes.
How a graph index keeps filtered regions connected (2019). About 15 minutes.