What is a vector database, and how does approximate nearest-neighbour search work?

Learning path, stage 3 of 5: RAG and fine-tuning · question 3 of 10

A vector database stores embeddings with metadata and answers "which vectors are closest to this one?" fast, using approximate nearest-neighbour (ANN) indexes such as HNSW or IVF instead of comparing against every vector. You give up a little recall for search that stays fast across millions or billions of vectors.

Common index types

  • Flat (brute force): exact results. Fine up to around 100k vectors.
  • HNSW: a layered graph that you walk greedily from coarse to fine. High recall and fast, but uses a lot of memory. The usual default.
  • IVF: clusters the vectors with k-means and searches only the closest clusters.
  • Product quantisation (PQ): compresses vectors to save memory, with some loss of precision.

What a production vector store also gives you

  • Metadata filtering (tenant, permissions, date) alongside the similarity search.
  • Hybrid search (vector + keyword), upserts and deletes, replication.

Choosing one

  • Already on Postgres? pgvector is often enough.
  • Want a library rather than a service? FAISS.
  • Very large scale or fully managed: a dedicated vector DB.
  • Settings to tune include HNSW's ef_search and M, which trade recall against latency.

Sources

Code example

tsx
1// pgvector with node-postgres: schema, HNSW index and a filtered k-NN query.
2import { Pool } from "pg";
3
4const db = new Pool();
5
6export async function setup() {
7 await db.query(`CREATE EXTENSION IF NOT EXISTS vector`);
8 await db.query(`
9 CREATE TABLE IF NOT EXISTS chunks (
10 id bigserial PRIMARY KEY,
11 tenant_id text NOT NULL,
12 content text NOT NULL,
13 embedding vector(1024) NOT NULL
14 )`);
15 // HNSW index using cosine distance
16 await db.query(`CREATE INDEX IF NOT EXISTS chunks_hnsw ON chunks USING hnsw (embedding vector_cosine_ops)`);
17}
18
19export async function search(tenantId: string, queryVec: number[], k = 5) {
20 const { rows } = await db.query(
21 `SELECT id, content, 1 - (embedding <=> $2) AS similarity
22 FROM chunks
23 WHERE tenant_id = $1 -- permission filter
24 ORDER BY embedding <=> $2 -- <=> is cosine distance
25 LIMIT $3`,
26 [tenantId, JSON.stringify(queryVec), k],
27 );
28 return rows;
29}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app