Vector Databases

Difficulty: Intermediate

Question

What is a vector database, how does it work, and when would you use one (for example Pinecone or pgvector)?

Answer

A vector database stores embeddings, which are arrays of numbers produced by a machine learning model to represent the meaning of text, images or other data, and finds the stored vectors most similar to a query vector. Instead of exact matches, it answers "what is closest to this?" using a distance metric such as cosine similarity, with approximate nearest neighbor (ANN) indexes like HNSW so search stays fast across millions of vectors. It is the retrieval layer behind semantic search, recommendations and Retrieval-Augmented Generation (RAG).

What embeddings are

An embedding model turns input into a fixed-length vector, often 384 to 3,072 dimensions depending on the model. Inputs with similar meaning land close together. "How do I reset my UPI PIN" and "forgot UPI PIN, what to do" produce nearby vectors even though they share few words, which keyword search would miss.

How similarity search works

  1. Ingest: split documents into chunks, embed each chunk, and store the vector with its text and metadata (source, date, tenant).
  2. Query: embed the user's question with the same model.
  3. Search: find the top-k closest vectors by a distance metric:
  • Cosine distance: compares direction; the usual choice for text embeddings.
  • Dot (inner) product: equivalent to cosine for normalized vectors, cheaper to compute.
  • Euclidean (L2) distance: straight-line distance.
  1. Use the results: show them, or pass them to an LLM as context (RAG).

Why ANN indexes matter

Exact search compares the query with every vector, which is too slow at scale. ANN indexes trade a little recall for big speed gains:

  • HNSW (Hierarchical Navigable Small World): a layered graph you navigate greedily toward close neighbors. Fast and accurate, memory-hungry; tune with m, ef_construction and ef_search.
  • IVF (inverted file): clusters vectors and searches only the nearest clusters; tuned with list and probe counts.
  • Quantization (product or scalar quantization) compresses vectors to save memory.

Dedicated vector DB vs pgvector

OptionStrengthsConsider when
pgvector (PostgreSQL extension)Vectors next to relational data, SQL joins and filters, transactionsYou already use PostgreSQL and have up to tens of millions of vectors
Pinecone (managed)Fully managed, serverless scalingYou want no infrastructure work
Qdrant, Weaviate, MilvusOpen source, rich filtering, hybrid searchLarge scale or self-hosting
Elasticsearch or OpenSearchCombines BM25 keyword and vector searchYou already run a search cluster

Gotchas

  • Use the same embedding model for indexing and querying. Changing models means re-embedding everything.
  • Metadata filtering (for example only documents for this college or tenant) can reduce recall with ANN indexes if the filter is applied after the search. Check how your database handles filtered search.
  • Chunking quality often matters more than the database choice for RAG accuracy.
  • Hybrid search (keyword plus vector) usually beats pure vector search for names, codes and IDs like an IFSC or order number.
Retrieval-Augmented Generation with a vector store. The vector database finds relevant chunks that the LLM then uses to answer.
  1. User question: Natural language query arrives.
  2. Embedding model: Question converted into a vector.
  3. Vector DB top-k search: ANN index finds the closest chunks.
  4. Prompt with retrieved chunks: Context added to the LLM prompt.
  5. LLM answer with sources: Grounded response returned to the user.

Code examples

Semantic search with pgvector

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE doc_chunks (
  id        BIGSERIAL PRIMARY KEY,
  course_id BIGINT NOT NULL,
  content   TEXT   NOT NULL,
  embedding vector(1536) NOT NULL      -- must match the model's dimensions
);

-- HNSW index using cosine distance
CREATE INDEX ON doc_chunks USING hnsw (embedding vector_cosine_ops);

-- $1 = query embedding from the same model
SELECT id, content, embedding <=> $1 AS cosine_distance
FROM doc_chunks
WHERE course_id = 12
ORDER BY embedding <=> $1
LIMIT 5;

The <=> operator is cosine distance in pgvector (<-> is L2, <#> is negative inner product); ORDER BY distance with LIMIT lets the HNSW index serve the query.

Key points

  • Embeddings are fixed-length vectors where similar meaning means nearby vectors.
  • Vector databases answer nearest-neighbor queries using cosine, dot product or L2 distance.
  • ANN indexes like HNSW and IVF trade a little recall for large speed gains.
  • pgvector keeps vectors inside PostgreSQL; Pinecone, Qdrant, Weaviate and Milvus are dedicated options.
  • Index and query with the same embedding model; hybrid keyword plus vector search often works best.

Common follow-up questions

  • How does HNSW work at a high level?
  • When would you choose pgvector over a dedicated vector database?
  • How do you handle metadata filters without hurting recall?
  • How would you chunk documents for a RAG system?

Interview tips

  • Explain embeddings and similarity first; the database is just the index around that idea.
  • Mention ANN and recall vs latency trade-offs; it shows you understand why special indexes are needed.
  • Bring up pgvector as a pragmatic default if the team already runs PostgreSQL.

Concepts covered

Vector Database, Embeddings, Approximate Nearest Neighbor, HNSW, pgvector, RAG

More Database Design questions