
Databases · Search & indexing
Vector databases, explained and measured: how search by meaning works and how it differs from a normal database
Embeddings, similarity, the curse of dimensionality, HNSW, IVF and quantization, filtering and hybrid search, a working product search on PostgreSQL with pgvector, real benchmarks, and a clear comparison with normal databases.
26 min read
Type "cheap phone that lasts all day" into the search box of a typical online store and you will probably get nothing back. The store has a phone with a 6000 mAh battery for under 12,000 rupees, which is exactly what you asked for, but its title doesn't contain the words "cheap" or "lasts all day". A normal database matches characters. It has no idea what you meant.
Vector databases exist to close that gap. They store the meaning of things as lists of numbers and find what is closest in meaning, not in spelling. This guide explains how that works from the ground up: what an embedding is, how closeness is measured, why searching in a thousand dimensions breaks the tricks that make normal databases fast, and how algorithms like HNSW and IVF get around it. Then it builds a working semantic search with real numbers, puts vector and normal databases side by side, and covers where vector databases are used in practice.
Transcript
1. The problem: computers compare text, people compare meaning
A normal database is excellent at exact questions. Which order has id 1042? Which customers live in Kolkata? Which products cost less than 15,000 rupees? These questions have exact answers, and indexes such as B-trees find them in a handful of steps.
Many of the questions people actually ask are not exact. "Something to cook dinner quickly." "A gift for someone who loves music." "Find support tickets like this one." "Which contract clauses are about termination?" The right answer shares meaning with the question but often no words at all. Here is what our dummy store's database does with the first query:
-- A normal database matches characters, not meaningSELECT title FROM products WHERE title ILIKE '%cheap phone that lasts all day%';-- (0 rows)-- Full-text search is smarter (stemming, ranking) but still needs the wordsSELECT title FROM productsWHERE to_tsvector('english', title) @@ plainto_tsquery('english', 'cheap phone that lasts all day');-- (0 rows)Full-text search improves on LIKE: it handles plurals, ignores filler words and ranks results. But it still needs the words to overlap. To match by meaning, we first need a way to write meaning down as something a computer can compare. That something is a vector.
2. Embeddings: meaning as coordinates
Think of a map. Kolkata and Howrah have coordinates close to each other; Kolkata and London are far apart. Two numbers, latitude and longitude, are enough to answer "what's near here?" for any place on Earth.
An embedding does the same for meaning. An embedding model, a neural network trained on huge amounts of text (or images, or audio), turns an input into a list of numbers, a vector, so that inputs with similar meaning land close together. "Budget smartphone with long battery life" and "cheap phone that lasts all day" get nearby coordinates; "stainless steel pressure cooker" lands far away. With the pretrained model used for this post's examples, the first pair scored a cosine similarity of 0.71 and the second pair 0.50.
The difference from a map is the number of coordinates. Two dimensions can't hold everything that distinguishes one sentence from another, so embedding models use hundreds or thousands. No single dimension means "price" or "electronics"; meaning is spread across all of them together.
Embedding model (examples) | Dimensions | Notes |
|---|---|---|
OpenAI text-embedding-3-smallSource [2] | 1,536 (can be shortened) | Low price, the common default for English retrieval |
OpenAI text-embedding-3-large | 3,072 (can be shortened to 1,024 or 256) | Higher accuracy; Matryoshka-style truncation |
Voyage 4 familySource [3] | Selectable | Released January 2026; all sizes share one vector space |
Google Gemini Embedding 2Source [4] | Selectable | One model for text, images, video, audio and PDF |
Open-weight models (Qwen3-Embedding and others) | Varies | Run on your own hardware; high on public leaderboards |
spaCy en_core_web_md word vectors | 300 | Small, old-style word vectors; used in this post because it runs offline |
Benchmarks like MTEB rank embedding models, and the top spots change every few months. Leaderboard position matters less than performance on your own data: build a small test set of real queries with known good answers and measure.
3. Measuring closeness: distance and similarity
Once everything is a vector, "similar" becomes "close", and there are several ways to measure close. Picture two arrows from the origin:
Measure | What it compares | Range | pgvector operator | Typical use |
|---|---|---|---|---|
Cosine similarity / distance | The angle between the arrows, ignoring their length | Similarity -1 to 1; distance = 1 - similarity |
| Text embeddings (the usual default) |
Dot (inner) product | Angle and length together | Any number |
| Same as cosine when vectors are normalised; some recommendation models |
Euclidean (L2) distance | Straight-line distance between the arrow tips | 0 and up |
| Image features, clustering, geometry-like data |
Manhattan (L1) distance | Sum of differences along each axis | 0 and up |
| Some sparse or tabular features |
Hamming distance | How many bits differ | 0 to number of bits |
| Binary vectors and binary-quantized embeddings |
Jaccard distance | Overlap of two sets of bits | 0 to 1 |
| Sets, fingerprints |
4. Why searching gets hard: the curse of dimensionality
Here's a puzzle. I give you the numbers 1 to 13, sorted, and ask you to find one. You check the middle, see whether your number is bigger or smaller, and throw away half the list. Repeat, and you're done in about four steps. That's binary search: log n steps instead of n, and the idea behind the B-tree indexes in every normal database.
Now make it a 2D grid and ask for a point near (x, y). Splitting on x halves the data, but the closest point might sit just across the dividing line, close in x and on the other side. You have to check neighbouring regions too. Structures like the k-d tree handle this by splitting on x, then y, then x again, and they work beautifully in 2 or 3 dimensions.
Keep adding dimensions and two things go wrong. Each split rules out less and less: in 300 dimensions, a query is close to the dividing wall in some dimension almost everywhere, so you end up visiting most regions anyway. And distances themselves stop being informative: in high dimensions, the nearest point and the farthest point are almost the same distance away. This is the curse of dimensionality, and it's easy to measure:
# Same 100,000 random points, more and more dimensions:# how fast is a k-d tree (the "binary search" of space) compared with checking every point?import time, numpy as npfrom scipy.spatial import cKDTreerng = np.random.default_rng(42)for d in [2, 10, 50, 300, 1536]: X = rng.random((100_000, d), dtype=np.float32) # the "database" q = rng.random((200, d), dtype=np.float32) # 200 queries t = time.perf_counter() # brute force: every distance dist = (q**2).sum(1)[:, None] + (X**2).sum(1)[None, :] - 2 * q @ X.T np.argpartition(dist, 10, axis=1) brute = (time.perf_counter() - t) / 200 * 1000 tree = cKDTree(X) # space partitioning t = time.perf_counter(); tree.query(q, k=10) kd = (time.perf_counter() - t) / 200 * 1000 print(f"{d:>5}d brute {brute:7.3f} ms kd-tree {kd:8.3f} ms")# 2d brute 0.748 ms kd-tree 0.004 ms <- tree wins 187x# 10d brute 0.755 ms kd-tree 0.203 ms# 50d brute 0.849 ms kd-tree 7.488 ms <- tree now LOSES# 300d brute 1.539 ms kd-tree 58.332 ms# 1536d brute 4.205 ms kd-tree 185.544 ms <- 44x slower than brute forceDimensions | Nearest ÷ farthest distance (random data) | k-d tree vs checking every point |
|---|---|---|
2 | 0.001 (nearest is 1000× closer) | 187× faster |
10 | 0.149 | 3.7× faster |
50 | 0.490 | 8.8× slower |
300 | 0.756 | 38× slower |
1,536 | 0.884 (nearest is barely closer) | 44× slower |

At 1,536 dimensions, the size of a common text embedding, the classic space-splitting index is 44 times slower than simply comparing the query with every vector. So how do vector databases answer in milliseconds across millions of vectors? They stop insisting on the exact answer.
Real embeddings are kinder than random data: they cluster and lie close to a lower-dimensional surface, which is why the approximate methods in the next section work at all. But exact search still has to look at every vector, and that doesn't scale to millions of queries a second.
5. Exact vs approximate nearest neighbours
Exact k-nearest-neighbour search (kNN) compares the query with every stored vector and keeps the k closest. It's always right, it needs no index, and it's perfectly fine for a few thousand vectors. Its cost grows linearly: on our test set of 200,000 vectors with 384 dimensions, an exact scan in PostgreSQL took about 102 ms per query on one core.
Approximate nearest-neighbour search (ANN) uses an index to look at only a small, promising part of the data. It's usually right, much faster, and you can tune how often it's right. That "how often" has a name:
You will see different results for queries after adding an approximate index.
pgvector documentation
6. How vector indexes work
IVF: cluster first, search a few clusters
An inverted file index (IVF) runs k-means clustering on your vectors to find a set of centres, called lists, and files each vector under its nearest centre. At query time it compares the query with the centres, picks the closest few (the probes), and searches only the vectors in those lists. With 200 lists and 14 probes, it looks at roughly 7% of the data.Source [5]
The weakness is the boundary problem from the 2D grid: a true neighbour can sit just across the edge in a list you didn't probe. More probes fix that at the cost of speed. IVF builds fast and uses little memory, but it needs representative data before you build it, because the centres are learned from it.
HNSW: a navigable graph with express lanes
Hierarchical Navigable Small World (HNSW), introduced by Malkov and Yashunin in 2016, is the index most vector databases default to. It links each vector to a handful of close neighbours, forming a graph, and stacks several layers of such graphs. The top layer has few vectors and long links; each layer down has more vectors and shorter links.Source [6]

A search starts at the top, greedily hops to whichever neighbour is closest to the query, drops down a layer when it can't get closer, and repeats until it reaches the dense bottom layer. It's like getting to a friend's house in another city: motorway, then main road, then lane. Each step only looks at a few neighbours, so search cost grows roughly with the logarithm of the data size, not linearly.
HNSW setting | pgvector default | What raising it does |
|---|---|---|
| 16 | Better recall, more memory, slower builds |
| 64 | Better graph quality, slower builds and inserts |
| 40 | Better recall, slower queries (set per query) |
Quantization: store less of each vector
A 1,536-dimension vector of 32-bit floats takes 6 KB. Ten million of them take 61 GB before any index, and fast search wants them in memory. Quantization stores a compressed version and uses it to find candidates, then re-checks the top candidates with the full vectors (re-ranking).
Scalar / half precision: 16-bit or 8-bit numbers instead of 32-bit. Simple, and usually almost no recall loss.
Binary quantization: one bit per dimension (positive or negative), compared with fast Hamming distance. 32× smaller; always re-rank.
Product quantization (PQ): split each vector into chunks and replace each chunk with the id of its closest entry in a learned codebook. Tens of times smaller; the classic way to fit billions of vectors in memory.
Newer schemes keep appearing: Qdrant 1.18 (May 2026) introduced TurboQuant, which it reports reaches similar recall and speed to scalar quantization at twice the compression.Source [7]
Other approaches
Disk-based graphs (DiskANN and similar): keep the graph and compressed vectors on SSD, with only a small part in memory, for billion-scale data on one machine.
Locality-sensitive hashing (LSH): hash functions that put close vectors in the same bucket. Historically important and simple, but usually beaten by graphs and IVF on modern embeddings.
GPU indexes: build and search graphs or IVF on GPUs for very high throughput.
Sparse vectors: mostly-zero vectors (for example from learned sparse models such as SPLADE, or BM25-style weights) with their own index types, often combined with dense vectors.
Measured: the trade-offs in numbers
To make the trade-offs concrete, I loaded 200,000 vectors of 384 dimensions into PostgreSQL 19 with pgvector 0.8.7 and ran 200 queries against each index, measuring recall@10 against the exact answer and latency per query on one core. The vectors were generated to lie near a 16-dimensional surface, which makes them behave like real embeddings rather than random noise:
Index and setting (pgvector) | Recall@10 | Median latency | Index size | Build time |
|---|---|---|---|---|
None (exact scan) | 1.000 | 102 ms | - | - |
HNSW, ef_search 10 | 0.833 | 1.1 ms | 391 MB | 77 s |
HNSW, ef_search 40 (default) | 0.988 | 2.6 ms | 391 MB | 77 s |
HNSW, ef_search 100 | 1.000 | 5.0 ms | 391 MB | 77 s |
IVFFlat, 200 lists, 1 probe (default) | 0.280 | 1.1 ms | 313 MB | 3.8 s |
IVFFlat, 200 lists, 14 probes | 0.892 | 7.9 ms | 313 MB | 3.8 s |
IVFFlat, 200 lists, 30 probes | 0.982 | 17.4 ms | 313 MB | 3.8 s |
HNSW on half precision, ef_search 100 | 1.000 | 6.0 ms | 223 MB | 75 s |
HNSW on binary (1 bit), top 100 re-ranked | 0.971 | 1.7 ms | 67 MB | 34 s |
And product quantization, measured with FAISS on the same data:
FAISS index | Recall@10 | Latency | Bytes per vector |
|---|---|---|---|
Flat (exact) | 1.000 | 25.6 ms | 1,536 |
IVF, 448 lists, 32 probes | 0.950 | 1.6 ms | 1,547 |
IVF + PQ (48 chunks × 8 bits), 32 probes | 0.566 | 0.3 ms | 61 |
IVF + PQ, top 100 re-ranked exactly | 0.939 | 0.4 ms | 61 + originals on disk |
What the numbers say: HNSW gives the best recall for the time spent, at the cost of memory and slow builds. IVF builds 20 times faster and is smaller, but needs many probes for high recall, and pgvector's default of one probe is far too low for real use. Half precision cost nothing here. Binary quantization with re-ranking and PQ with re-ranking keep most of the recall at a fraction of the memory. Your numbers will differ with your data, so measure.Source [8]
-- HNSW: build-time optionsCREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64); -- the defaults-- HNSW: query-time recall/speed knob (default 40)SET hnsw.ef_search = 100;-- IVFFlat: create AFTER loading data (it learns cluster centres from it)CREATE INDEX ON docs USING ivfflat (embedding vector_cosine_ops) WITH (lists = 200); -- ~rows/1000 up to 1M rowsSET ivfflat.probes = 14; -- ~sqrt(lists) is a good start-- Filters remove rows AFTER the index scan; keep scanning until enough matchSET hnsw.iterative_scan = relaxed_order;-- Half precision: same recall in our test, ~43% smaller indexCREATE INDEX ON docs USING hnsw ((embedding::halfvec(384)) halfvec_cosine_ops);-- Binary quantization (1 bit per dimension) + re-rank with the full vectorsCREATE INDEX ON docs USING hnsw ((binary_quantize(embedding)::bit(384)) bit_hamming_ops);SELECT id FROM ( SELECT id, embedding FROM docs ORDER BY binary_quantize(embedding)::bit(384) <~> binary_quantize($1) LIMIT 100) candidatesORDER BY embedding <=> $1LIMIT 10;7. What's inside a vector database
The index is the famous part, but a production vector database does much more than run HNSW:
Component | What it does |
|---|---|
Storage | Keeps vectors with an id and a payload (metadata such as category, price, tenant, permissions), durably, with a write-ahead log |
Indexes | One or more ANN indexes per vector field, plus normal indexes on metadata for filtering |
Filtering | Combines "near this vector" with "category = phones AND price <= 15000"; doing this well is one of the hardest parts |
Hybrid search | Runs keyword (BM25-style) search and vector search together and merges the rankings |
Updates and deletes | Inserts go into the graph; deletes are usually marked and cleaned up later, so indexes need maintenance |
Scaling | Sharding across machines, replication for availability, tiered storage (memory, SSD, object storage) |
Multi-tenancy | Keeps customers' data and results separate; per-tenant partitions or collections |
Re-ranking | Optionally re-scores the top candidates with full vectors or a slower, more accurate cross-encoder model |
Filtering: the part that surprises people
Filtering can happen before the vector search (pre-filtering), after it (post-filtering) or during it. Post-filtering is simple but leaky: if the index returns the 40 nearest products and only 4 of them are phones, you get 4 results, not 10. pgvector's documentation gives exactly this example and solves it with iterative index scans (since 0.8.0), which keep scanning until enough rows pass the filter. Dedicated vector databases build filters into the graph walk itself. For a few very common filter values, a partial index per value works well; for strict tenant separation, use partitions or separate collections.Source [9]
Hybrid search: meaning plus exact words
Vector search understands "cheap phone that lasts all day". It's weaker at exact tokens like product codes, model numbers, error codes and names, which keyword search handles perfectly. Hybrid search runs both and merges the results, most often with Reciprocal Rank Fusion (RRF): each result scores 1/(60 + rank) in each list, and the scores are added. A result that ranks well in both lists rises to the top. In our store, a vector-only search for "headphones" put a party speaker first; the hybrid search put the actual headphones first and kept the speaker and earbuds as related results.

8. Normal database vs vector database
They aren't rivals so much as tools for different questions. Here is the comparison point by point:
Normal (relational / document) database | Vector database | |
|---|---|---|
Main question | "Which rows match these conditions?" | "Which items are most similar to this one?" |
Data | Rows, columns, documents: numbers, text, dates | Vectors (hundreds to thousands of numbers) plus metadata |
Matching | Exact: equals, ranges, text patterns | By distance: cosine, dot product, Euclidean |
Results | A set that does or doesn't match | A ranked list with similarity scores; there's always a "nearest" |
Index | B-tree, hash, GIN, GiST | HNSW, IVF, PQ, DiskANN |
Correctness | Exact; the same query returns the same rows | Usually approximate; tuned for recall |
Typical query |
|
|
Writes | Cheap, transactional, frequent updates | Inserts cost more (graph links); deletes need cleanup; embedding costs money and time |
Scaling pressure | Rows and transactions | Memory: vectors and graphs are large |
Good at | Orders, payments, users, inventory, reporting | Semantic search, RAG, recommendations, deduplication, similarity |
Bad at | "Find things like this" | Exact lookups, joins, transactions, aggregations |
In practice the line is blurring. PostgreSQL has pgvector, and most major databases and search engines (MongoDB, Elasticsearch, OpenSearch, Redis and others) now offer vector search alongside their normal features. Specialised vector databases still win at very large scale, at advanced filtering and quantization, and when vector search is the main workload. A useful rule: if your vectors fit comfortably next to data you already keep in PostgreSQL, start with pgvector; move to a dedicated engine when scale, latency or features demand it.
9. Hands-on: semantic product search
Let's build the search from the start of this post. The embeddings here come from a small pretrained word-vector model (spaCy's en_core_web_md, 300 dimensions, averaged over the words in each title after dropping filler words) because it runs offline. It's a deliberately simple, older model. A modern embedding model drops into the same code and ranks noticeably better; the database part doesn't change at all.Source [10]
CREATE EXTENSION IF NOT EXISTS vector;CREATE EXTENSION IF NOT EXISTS vector; -- pgvector 0.8.7CREATE TABLE products ( id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, category text NOT NULL, price_inr int NOT NULL, embedding vector(300) NOT NULL -- one 300-number vector per product);-- Approximate nearest-neighbour index for cosine distanceCREATE INDEX ON products USING hnsw (embedding vector_cosine_ops);-- Ordinary full-text index for keyword search (used later for hybrid search)CREATE INDEX ON products USING gin (to_tsvector('english', title));Each product's title is embedded once when it's added, and each search embeds the user's query with the same model. The search itself is one SQL query:
-- $1 = embedding of the user's query, made with the same model as the productsSELECT title, price_inr, round((1 - (embedding <=> $1))::numeric, 3) AS similarityFROM productsORDER BY embedding <=> $1 -- <=> is cosine distanceLIMIT 5;-- "something to cook dinner quickly"-- Non-stick frying pan with glass lid | 0.765-- Cold-pressed mustard oil, 1 litre | 0.615-- Cookbook of quick Indian vegetarian recipes | 0.596-- "gift for someone who loves music"-- Over-ear studio headphones for music production | 0.484-- Meaning plus ordinary filters: phones under 15,000 rupeesSELECT title, price_inrFROM productsWHERE category = 'phones' AND price_inr <= 15000ORDER BY embedding <=> $1LIMIT 3;-- Rugged feature phone with torch and two SIM slots | 1599-- Galaxy M16 phone with 6000 mAh battery and fast charging | 11999-- Redmi A5 smartphone, 5200 mAh battery, 6.9-inch screen | 7499None of these results share the query's words. "Cook dinner quickly" found a frying pan, cooking oil and a book of quick recipes; "loves music" found studio headphones. The filtered query shows the real strength of keeping vectors in a normal database: meaning and exact conditions in one statement. The simple model also shows its limits: for "cheap phone that lasts all day" without a filter, it ranked a fitness band first ("battery", "day") ahead of the right phone. That's the embedding model's fault, not the database's, and exactly what a better model fixes.
Exact terms are where hybrid search earns its place:
-- Hybrid search: run keyword and vector search, then merge with Reciprocal Rank FusionWITH semantic AS ( SELECT id, row_number() OVER (ORDER BY embedding <=> $2) AS rank FROM products ORDER BY embedding <=> $2 LIMIT 20), keyword AS ( SELECT id, row_number() OVER (ORDER BY ts_rank_cd(to_tsvector('english', title), q) DESC) AS rank FROM products, plainto_tsquery('english', $1) AS q WHERE to_tsvector('english', title) @@ q ORDER BY ts_rank_cd(to_tsvector('english', title), q) DESC LIMIT 20)SELECT p.title, coalesce(1.0 / (60 + s.rank), 0) + coalesce(1.0 / (60 + k.rank), 0) AS rrf_scoreFROM semantic sFULL OUTER JOIN keyword k USING (id)JOIN products p USING (id)ORDER BY rrf_score DESCLIMIT 3;-- query "headphones"-- vector only : Bluetooth party speaker..., Over-ear studio headphones..., Wireless earbuds...-- hybrid : Over-ear studio headphones... (0.0325), party speaker (0.0164), earbuds (0.0159)Finally, the same search from a Node.js application, with an OpenAI embedding model, the official pgvector package for node-postgres, filters, and per-query recall settings:
// src/search.ts - semantic product search with PostgreSQL + pgvector from Node.jsimport pg from 'pg';import pgvector from 'pgvector/pg';import OpenAI from 'openai';const openai = new OpenAI(); // reads OPENAI_API_KEYconst pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, // teach node-postgres the vector type on every new connection onConnect: async (client) => await pgvector.registerTypes(client),});const MODEL = 'text-embedding-3-small'; // 1536 dimensions by defaultconst DIMS = 1536;/** Turn text into a vector. Use the SAME model for documents and queries. */async function embed(texts: string[]): Promise<number[][]> { const res = await openai.embeddings.create({ model: MODEL, input: texts, dimensions: DIMS }); return res.data.map((d) => d.embedding);}export async function setup() { await pool.query('CREATE EXTENSION IF NOT EXISTS vector'); await pool.query(`CREATE TABLE IF NOT EXISTS products ( id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, category text NOT NULL, price_inr int NOT NULL, embedding vector(${DIMS}) NOT NULL)`); await pool.query('CREATE INDEX IF NOT EXISTS products_embedding_idx ON products USING hnsw (embedding vector_cosine_ops)');}export async function addProducts(items: { title: string; category: string; priceInr: number }[]) { const vectors = await embed(items.map((i) => i.title)); // one API call per batch for (const [i, item] of items.entries()) { await pool.query('INSERT INTO products (title, category, price_inr, embedding) VALUES ($1, $2, $3, $4)', [ item.title, item.category, item.priceInr, pgvector.toSql(vectors[i]), ]); }}/** Nearest products by meaning, with ordinary SQL filters alongside. */export async function search(query: string, opts: { category?: string; maxPrice?: number; limit?: number } = {}) { const [q] = await embed([query]); const client = await pool.connect(); try { await client.query('BEGIN'); await client.query('SET LOCAL hnsw.ef_search = 100'); // recall vs speed, per query await client.query("SET LOCAL hnsw.iterative_scan = 'relaxed_order'"); // keep scanning if filters drop rows const { rows } = await client.query<{ title: string; price_inr: number; similarity: number }>( `SELECT title, price_inr, 1 - (embedding <=> $1) AS similarity FROM products WHERE ($2::text IS NULL OR category = $2) AND ($3::int IS NULL OR price_inr <= $3) ORDER BY embedding <=> $1 LIMIT $4`, [pgvector.toSql(q), opts.category ?? null, opts.maxPrice ?? null, opts.limit ?? 5], ); await client.query('COMMIT'); return rows; } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); }}// Example: await search('cheap phone that lasts all day', { category: 'phones', maxPrice: 15000 });10. Where vector databases are used
Application | What gets embedded | How the search is used |
|---|---|---|
Retrieval-augmented generation (RAG) | Chunks of documents, help articles, code | Find the passages most relevant to a question and give them to an LLM to answer from |
Semantic search | Products, documents, tickets | Search by meaning, usually combined with keyword search |
Recommendations | Users and items (behaviour or content) | "More like this", "customers like you also bought" |
Deduplication | Records, images, listings | Find near-identical items, such as the same product listed twice |
Image, audio and video search | Images, frames, audio clips | Search by example or by text describing the image |
Anomaly and fraud detection | Transactions, log lines, sessions | Flag items far from everything normal |
AI agent memory | Past conversations, tool results, notes | Recall relevant memories for the current task |
Classification and routing | Support tickets, emails | Label by the nearest labelled examples |
RAG, step by step
RAG is the application that made vector databases mainstream, so it's worth spelling out:
Split documents into chunks of a few hundred words, with a little overlap so ideas aren't cut in half.
Embed each chunk and store it with metadata: source, section, date and who may see it.
When a question arrives, embed it with the same model and retrieve the top chunks, filtered by what that user is allowed to see.
Optionally re-rank the candidates with a cross-encoder for precision.
Give the question and the chunks to an LLM and ask it to answer only from them, citing the sources.
11. Choosing a vector database
Option | Type | Current version (Nov 2026) | Good fit |
|---|---|---|---|
pgvector | PostgreSQL extension | 0.8.7 (2 Oct 2026, security fix)Source [11] | You already use PostgreSQL; up to tens of millions of vectors; SQL filters and joins |
Qdrant | Dedicated, open source (Rust) | 1.20 (22 Oct 2026)Source [12] | Rich filtering, quantization, hybrid search, self-hosted or cloud |
Milvus | Dedicated, open source, distributed | 3.0 (July 2026) | Very large scale; 3.0 can index data in lake formats (Parquet, Iceberg, Lance, Vortex) in placeSource [13] |
FAISS | Library, not a database | 1.16 | Building your own search, research, offline batch jobs, GPUs |
Pinecone, Zilliz Cloud and similar | Managed services | Managed | No infrastructure to run; pay per usage |
Weaviate, Chroma, LanceDB | Dedicated, open source | Check current releases | Built-in vectorizer modules, simple local development, embedded use |
Elasticsearch / OpenSearch, MongoDB, Redis | Existing databases with vector search | Check your version | Adding vector search to a stack you already run |
12. Checklist and common mistakes
Pick the embedding model by testing on your own queries, record its name and dimensions with the data, and plan for re-embedding when you change it.
Use the metric the model was trained for, and build the index for that metric.
Start exact (no index) while the data is small; add HNSW when queries get slow.
Measure recall@k against exact search before going live, then tune ef_search or probes, not just speed.
Handle filters deliberately: iterative scans, partial indexes or partitions; never let a filter silently return 2 results instead of 10.
Add hybrid search wherever names, codes or numbers matter.
Watch memory: halfvec, binary quantization or PQ with re-ranking before buying bigger machines.
Batch embedding calls, cache embeddings, and never re-embed unchanged text.
Apply permissions in the query (metadata filters), especially for RAG.
Rebuild IVF indexes after the data changes a lot; vacuum and monitor HNSW indexes after heavy deletes.
Transcript
Go further
pgvector's documentation is one of the clearest practical references on vector indexes, filtering and tuning, even if you end up using a different database:
Binary search halves a sorted list because one dimension has a clear left and right. Meaning has hundreds of dimensions and no left or right, which is why vector databases trade a little accuracy for a lot of speed, using graphs, clusters and compression. Once you see an embedding as coordinates and an index as a clever shortcut through them, the rest is engineering: pick a good model, measure recall, filter carefully, and keep vectors close to the data they describe.
Sources
- pgvector: open-source vector similarity search for Postgres, pgvector (GitHub). Accessed 2026-11-28. Back to the text for source 1
- New embedding models and API updates, OpenAI. Accessed 2026-11-28. Back to the text for source 2
- The Voyage 4 model family, Voyage AI by MongoDB. Accessed 2026-11-28. Back to the text for source 3
- Gemini Embedding 2 model, Google AI for Developers. Accessed 2026-11-28. Back to the text for source 4
- pgvector README: IVFFlat, pgvector (GitHub). Accessed 2026-11-28. Back to the text for source 5
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs, Yu. A. Malkov, D. A. Yashunin. Accessed 2026-11-28. Back to the text for source 6
- Qdrant 1.18 - TurboQuant, Qdrant. Accessed 2026-11-28. Back to the text for source 7
- Faiss: a library for efficient similarity search, Meta (facebookresearch). Accessed 2026-11-28. Back to the text for source 8
- pgvector README: iterative index scans, pgvector (GitHub). Accessed 2026-11-28. Back to the text for source 9
- English pipelines (en_core_web_md), spaCy / Explosion. Accessed 2026-11-28. Back to the text for source 10
- pgvector changelog, pgvector (GitHub). Accessed 2026-11-28. Back to the text for source 11
- Qdrant 1.20 - Full-Text Search Improvements, Qdrant. Accessed 2026-11-28. Back to the text for source 12
- Announcing Milvus 3.0: Lake-Native Vector Search and a More Powerful Retrieval Engine, Milvus. Accessed 2026-11-28. Back to the text for source 13
- pgvector 0.8.2 Released, PostgreSQL.org news. Accessed 2026-11-28. Back to the text for source 14
- pgvector 0.8.7 Released, PostgreSQL Announce mailing list. Accessed 2026-11-28. Back to the text for source 15
- Vector databases
- RAG
- Embeddings
- Vector search
- pgvector