Your RAG system works on two hundred chunks, then the corpus has twenty thousand and the search slows down, or you discover that the filter by product returns two results instead of five. These are the two moments in which a developer realises that the vector store is not a detail. This article explains what a vector database does beyond "saving numbers", what compromise it accepts when it uses an approximate index, and how to choose between managed services, servers you start yourself and a PostgreSQL extension.
I start from two experiments that I ran (measurements of metrics and of an index, with synthetic data and a fixed seed) and then move on to the products. I assume the embeddings seen in What is RAG and the code of RAG with TypeScript and LangChain.js.
Why a table is not enough
A relational database searches by equality or by range: "users named Marco", "products under 50 euros". A vector search asks something different: "the ten vectors closest to this one", where close is defined by a formula over hundreds of numbers. There is no column to sort in advance, and the exact comparison requires computing the distance between the query and all the vectors: with a million vectors of 1536 components that is about 1.5 billion multiplications for every question (1,000,000 × 1536, a calculation, not a measurement). The solution is an approximate index: it almost always returns the true neighbours while looking at only a small part of the data, and in exchange it does not guarantee to find them all.
The metrics, with numbers in hand
Before the index you need to decide what "close" means. The three common metrics are cosine similarity (the angle, it ignores length), the dot product (it also grows with length) and the Euclidean distance (the lower it is, the closer the points). The listing compares two candidates against a query: "near" points in the same direction but is twice as long, "far" points elsewhere.
const dot = (a: number[], b: number[]) => a.reduce((s, x, i) => s + x * b[i], 0);
const norm = (a: number[]) => Math.sqrt(dot(a, a));
const cosine = (a: number[], b: number[]) => dot(a, b) / (norm(a) * norm(b));
const euclid = (a: number[], b: number[]) => Math.sqrt(a.reduce((s, x, i) => s + (x - b[i]) ** 2, 0));
const unit = (a: number[]) => a.map(x => x / norm(a));
const q = [1, 2, 2];
const near = [2, 4, 4.4]; // same direction as q, but twice as long
const far = [3, 0, 0.5];
console.log("-- vectors as they are");
for (const [name, v] of [["near", near], ["far", far]] as const) {
console.log(`${name}: cos=${cosine(q, v).toFixed(4)} dot=${dot(q, v).toFixed(2)} L2=${euclid(q, v).toFixed(2)}`);
}
console.log("-- after normalisation to length 1");
for (const [name, v] of [["near", near], ["far", far]] as const) {
const a = unit(q), b = unit(v);
console.log(`${name}: cos=${cosine(a, b).toFixed(4)} dot=${dot(a, b).toFixed(4)} L2^2=${(euclid(a, b) ** 2).toFixed(4)} 2-2cos=${(2 - 2 * cosine(a, b)).toFixed(4)}`);
}
// Output:
// -- vectors as they are
// near: cos=0.9989 dot=18.80 L2=3.28
// far: cos=0.4384 dot=4.00 L2=3.20
// -- after normalisation to length 1
// near: cos=0.9989 dot=0.9989 L2^2=0.0023 2-2cos=0.0023
// far: cos=0.4384 dot=0.4384 L2^2=1.1232 2-2cos=1.1232
On the non-normalised vectors the Euclidean distance gets the order wrong: "far" has an L2 of 3.20 against the 3.28 of "near", so it would seem closer, when its cosine is 0.44 against 0.9989. The dot product rewards the long vector (18.80 against 4.00) for its length and not only for its direction. After normalisation the three metrics agree: cosine and dot product coincide, and the square of the Euclidean distance is exactly 2 − 2×cosine. The practical consequence is in the OpenAI manual: its embeddings are normalised to length 1, so with those models cosine and dot product give the same order and the Euclidean gives the same again. For another provider, or for vectors you shortened yourself, you must verify it or normalise.
Why an approximate index works: an experiment
The most widely used indexes split the work into two steps. IVF (inverted file) groups the vectors into lists around centroids found with k-means, and at each question looks only at the lists whose centroids are closest. HNSW builds a multi-layer graph (described by Malkov and Yashunin) and walks the graph from the top down. The listing implements the IVF version, which is short enough to read, on 20,000 synthetic vectors of 32 components in 40 clusters: for each question it measures how many distances it computes and how many of the true 10 neighbours it finds again (recall@10).
// Pseudo-random generator with a fixed seed: same output on every run.
let state = 12345;
const rnd = () => { state = (state * 1664525 + 1013904223) % 4294967296; return state / 4294967296; };
const gauss = () => Math.sqrt(-2 * Math.log(rnd() + 1e-12)) * Math.cos(2 * Math.PI * rnd());
const DIM = 32, N = 20000, TOPICS = 40, NLIST = 100, QUERIES = 100, K = 10;
let computations = 0; // how many distances get computed
const dist = (a: number[], b: number[]) => { computations++; let s = 0; for (let i = 0; i < DIM; i++) s += (a[i] - b[i]) ** 2; return s; };
// Data: 40 "topics" (random centers) with vectors scattered around each one.
const centers = Array.from({ length: TOPICS }, () => Array.from({ length: DIM }, () => gauss() * 3));
const sample = () => centers[Math.floor(rnd() * TOPICS)].map(x => x + gauss());
const data = Array.from({ length: N }, sample);
const query = Array.from({ length: QUERIES }, sample);
// Exact search: compares the query with all the vectors.
const topK = (q: number[], ids: number[]) =>
ids.map(i => [dist(q, data[i]), i] as const).sort((a, b) => a[0] - b[0] || a[1] - b[1]).slice(0, K).map(x => x[1]);
const all = data.map((_, i) => i);
computations = 0;
const exact = query.map(q => topK(q, all));
console.log(`exact: ${computations / QUERIES} distances per query`);
// IVF: k-means (10 iterations) and the membership list of each vector.
let centroids = Array.from({ length: NLIST }, (_, i) => data[i * (N / NLIST)].slice());
let assign = new Array(N).fill(0);
for (let it = 0; it < 10; it++) {
assign = data.map(v => { let b = 0, bd = Infinity; centroids.forEach((c, j) => { const d = dist(v, c); if (d < bd) { bd = d; b = j; } }); return b; });
centroids = centroids.map((c, j) => {
const m = all.filter(i => assign[i] === j);
return m.length ? c.map((_, d) => m.reduce((s, i) => s + data[i][d], 0) / m.length) : c;
});
}
const lists = centroids.map((_, j) => all.filter(i => assign[i] === j));
for (const nprobe of [1, 5, 10, 20]) {
computations = 0;
let found = 0;
query.forEach((q, qi) => {
const nearest = centroids.map((c, j) => [dist(q, c), j] as const).sort((a, b) => a[0] - b[0]).slice(0, nprobe).map(x => x[1]);
const candidates = nearest.flatMap(j => lists[j]);
const r = topK(q, candidates);
found += r.filter(i => exact[qi].includes(i)).length;
});
console.log(`nprobe=${String(nprobe).padStart(2)}: ${(computations / QUERIES).toFixed(0)} distances per query, recall@${K}=${(found / (QUERIES * K)).toFixed(2)}`);
}
// Output:
// exact: 20000 distances per query
// nprobe= 1: 386 distances per query, recall@10=0.70
// nprobe= 5: 1265 distances per query, recall@10=1.00
// nprobe=10: 2328 distances per query, recall@10=1.00
// nprobe=20: 4316 distances per query, recall@10=1.00
The exact search computes 20,000 distances per question. The index with nprobe=1 computes 386 (the
100 for the centroids plus those of the chosen list) but finds only 70% of the neighbours; with
nprobe=5 it is 1265 distances, about 6% of the work, and the recall reaches 1.00. The
nprobe parameter is the knob that trades speed for completeness, and it plays the same role as
ivfflat.probes in pgvector or ef_search in HNSW. Two honest caveats: I count
distances and not milliseconds, because times depend on the machine; and synthetic data in sharp clusters
is the easy case, so the recall on real embeddings will be lower at the same
nprobe. The value to use you measure on your corpus by comparing with the exact search.
The HNSW parameters, with the pgvector values
HNSW has three knobs. m is the maximum number of connections of each node: higher makes the
graph more precise and bigger in memory. ef_construction is the size of the candidate list
during construction: higher gives a better index and a slower build.
ef_search is the same list during search: higher, more recall and more slowness. The default
values depend on the product; for pgvector the documentation declares m 16,
ef_construction 64 and ef_search 40. If a tutorial talks about other
defaults (200 and 50 are the ones I had seen around), check the product and the version.
Four ways to keep vectors
The products differ less on the algorithm than on who manages what. The table compares only what I could verify in the documentation and in the client types; there are no latencies nor free-plan limits, because they change and are read on the provider's site.
| Solution | Who runs it | What it brings with it |
|---|---|---|
| Pinecone | Managed service, API key | No server to administer; the index is created with one call |
| Chroma | Open-source server you start | Simple startup for development, collections with metadata |
| Qdrant | Open-source server you start | Payload filters expressed as must and should conditions |
| pgvector | Your PostgreSQL | Vectors next to the relational data, filters in SQL, transactions |
| Weaviate | Open-source server or managed service | Hybrid search that merges vector and keyword (BM25F) results; not covered by the listings |
The question the table helps you ask is "who wakes up when it breaks". With a managed service you pay and someone else answers; with an open-source server you keep backups, updates and monitoring; with pgvector you already have all that, if you have PostgreSQL. The quality of the algorithm, at this level, matters less than your ability to run the service.
How they are used: Pinecone, Chroma and Qdrant
The listing creates the index or the collection, inserts a vector with metadata and queries with a filter, for the three products. The vectors are a placeholder of zeros: in an application you put the real embedding there. It is a schema to adapt, not run, because it requires a Pinecone key and two servers; I did, however, compile it with TypeScript against the installed packages, so names and signatures exist.
import { Pinecone } from "@pinecone-database/pinecone";
import { ChromaClient } from "chromadb";
import { QdrantClient } from "@qdrant/js-client-rest";
const DIM = 1536; // must match the embedding model
const makeVector = (): number[] => new Array(DIM).fill(0); // placeholder: the real embedding goes here
// --- Pinecone: managed service, key in PINECONE_API_KEY
const pinecone = new Pinecone();
await pinecone.createIndex({
name: "rag-demo",
dimension: DIM,
metric: "cosine",
spec: { serverless: { cloud: "aws", region: "us-east-1" } },
});
const index = pinecone.index("rag-demo");
await index.upsert({ records: [{ id: "doc-1", values: makeVector(), metadata: { source: "manual.pdf", page: 1 } }] });
const response = await index.query({ vector: makeVector(), topK: 5, includeMetadata: true, filter: { source: { $eq: "manual.pdf" } } });
// --- Chroma: server you start yourself
const chroma = new ChromaClient({ host: "localhost", port: 8000 });
const collection = await chroma.getOrCreateCollection({ name: "rag-demo", configuration: { hnsw: { space: "cosine" } } });
await collection.add({ ids: ["doc-1"], embeddings: [makeVector()], metadatas: [{ source: "manual.pdf", page: 1 }], documents: ["chunk text"] });
const found = await collection.query({ queryEmbeddings: [makeVector()], nResults: 5, where: { source: "manual.pdf" } });
// --- Qdrant: server you start yourself
const qdrant = new QdrantClient({ url: "http://localhost:6333" });
await qdrant.createCollection("rag-demo", { vectors: { size: DIM, distance: "Cosine" } });
await qdrant.upsert("rag-demo", { wait: true, points: [{ id: 1, vector: makeVector(), payload: { source: "manual.pdf", page: 1 } }] });
const hits = await qdrant.query("rag-demo", { query: makeVector(), limit: 5, with_payload: true, filter: { must: [{ key: "source", match: { value: "manual.pdf" } }] } });
console.log(response.matches.length, found.ids.length, hits.points.length);
Three things to read carefully. The dimension (DIM) must match that of the embedding
model, and it cannot be changed after creation: an index at 1536 does not accept vectors at 3072.
The metric is chosen at creation (metric: "cosine" in Pinecone, distance: "Cosine"
in Qdrant, space: "cosine" in Chroma) and must be kept consistent with what you decided in
listing 1. And the signatures change between versions: with @pinecone-database/pinecone 9.2.0
upsert receives { records: [...] }, while with 5.1.2 it received an
array directly and the compiler rejected the new form. Before copying a tutorial, check that the method
exists in the version you installed.
pgvector: vectors inside PostgreSQL
With pgvector the vector column is a type like the others and the search is an ORDER BY with
the distance operator (<=> for cosine, according to the README). The schema uses the
declared default values. I did not run it: the project forbids writes to local databases, so the
syntax is compared with the project's README and not with an execution.
-- 1. Extension and table (the dimension must be that of your model)
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
id bigserial PRIMARY KEY,
content text NOT NULL,
source text NOT NULL,
embedding vector(1536)
);
-- 2. HNSW index for cosine distance (m and ef_construction are the default values)
CREATE INDEX ON documents
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- 3. At search time: higher = more recall, slower (default 40)
SET hnsw.ef_search = 100;
-- 4. Search: <=> is the cosine distance, 1 - distance = similarity
SELECT id, content, 1 - (embedding <=> $1) AS similarity
FROM documents
WHERE source = 'manual.pdf'
ORDER BY embedding <=> $1
LIMIT 5;
Two limits written in the README explain choices that seem arbitrary. An index on a
vector column accepts up to 2,000 dimensions: the 3072 of text-embedding-3-large cannot
be indexed that way, and you need half-precision vectors (halfvec, up to 4,000), or
the shortening that OpenAI documents for that family. And 1 - (embedding <=> $1) is
the similarity only because the operator returns the cosine distance; with another metric the formula changes.
Filters and hybrid search: where an approximate index bites
Filtering by metadata ("only product B") seems free and it is not. The pgvector README says so
plainly: with an approximate index the filter is applied after the scan of
the index. If the condition selects 10% of the rows and hnsw.ef_search is 40, on average four
will be left. It is the typical cause of "I ask for five results and get two": the index
looked at 40 candidates, and most of them did not satisfy the filter.
- Raise
ef_search: more candidates, more rows survive the filter, slower search - Iterative scans: pgvector can keep scanning the index until it finds enough rows (
hnsw.iterative_scan) - Partial or partitioned index: if the values to filter on are few, one index per value avoids the problem at the root
- Filter first, exact search after: when the condition selects few rows, a normal index on the column and the exact distance on the subset are enough
The criterion that chooses among these exits is the selectivity of the filter: the narrower the condition, the more it pays to reduce the set first and compute exactly; the wider, the better the approximate index works with a few more candidates. Other products may treat the filter differently, and I did not verify how: the question to ask the documentation is always whether the filter is applied before or after the scan.
Hybrid search combines semantic similarity with keyword search. It is needed for texts that embeddings represent badly: error codes, acronyms, endpoint names. With pgvector it is combined with PostgreSQL's full-text search and the two lists are merged, for example with the Reciprocal Rank Fusion cited in the README. There is no "semantic versus keyword versus hybrid" table valid in general; the ones with qualitative grades and no measurement that you find online should be taken as opinions.
How to choose
Start from where your data already lives. If you use PostgreSQL and the corpus is of a reasonable size for that server, pgvector eliminates a system to manage and gives you SQL and transactions on the metadata. If you want to manage nothing and accept a paid service, a managed service such as Pinecone moves the operational work elsewhere. If you want a dedicated open-source server, Chroma is handy to start with, Qdrant and Weaviate offer more filtering and hybrid search tools. I have no comparable performance numbers to give: the honest comparison is to measure recall and latency on your corpus, with your queries, on two candidates.
A badly made choice is not final, but it has a cost: vectors are regenerated from the same texts, but changing embedding model requires redoing the index, and changing store requires rewriting the code that calls it. A layer of abstraction such as LangChain's reduces the second cost and does not touch the first.
What you can do now
You can say why an exact search does not scale and what you give up with an approximate index, read a recall@10 against a number of distances, choose a metric and normalise when needed, and recognise the filter applied after the index as the cause of missing results. You also know which pieces of the code of the three products depend on the version and on the dimension of the model. The next step is connecting a model: Integrating the OpenAI and Anthropic APIs; if you want to keep everything on your own machine, Local LLMs with Ollama.
Frequently asked questions
Do I need a dedicated vector database?
Not necessarily. With a few thousand chunks the in-memory index of the previous article or pgvector in the PostgreSQL you already have are enough. A dedicated product becomes interesting when the volume grows, when the filtering and hybrid search requirements exceed what the extension offers, or when you do not want to load the application database with the searches.
HNSW or IVF?
According to the pgvector README HNSW has a better speed-recall compromise, but slower build and more memory; IVFFlat builds faster and takes less memory, and must be created after the table contains data because it has a training phase. I have no measurement on your data: try both and compare with the exact search.
Why does a filtered search return fewer results than requested?
Because the approximate index retrieves a fixed number of candidates and the filter discards those that do not satisfy it. Raise the number of candidates, enable iterative scans where they exist, or narrow the set before the search.
The choice of index ties into the next one between fine-tuning and RAG, while AI agents and AI in CI/CD show where a model and its retrieval fit into a wider system.
Sources
- pgvector, official README - distance operators, default values of m, ef_construction, ef_search and probes, 2,000-dimension limit, filter applied after the approximate index, hybrid search, consulted on 2026-11-12
- Weaviate, hybrid search documentation - hybrid search as a fusion of vector and BM25F keyword search, consulted on 2026-11-12
- Malkov and Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (arXiv:1603.09320) - the multi-layer graph of HNSW, consulted on 2026-11-12
- OpenAI, embeddings guide - embeddings normalised to length 1 and cosine computable with the dot product, consulted on 2026-11-12
Listings 1 and 2 were run with Node 24.11 (listing 2 with identical output in two runs, synthetic data with a fixed seed, the count is of distances and not of times). Listing 3 was compiled with TypeScript 7.0.2 against @pinecone-database/pinecone 9.2.0, chromadb 3.5.0 and @qdrant/js-client-rest 1.20.0, without running it. Listing 4 is an SQL schema that was not run. No model was called.
Commenti
Caricamento commenti...
Sign in to comment