Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · AI / ML

Embeddings and Vector Databases

What embeddings are, how cosine similarity and ANN indexes like HNSW make vector search work, when you need a vector database, and the interview questions that follow.

Keyword search breaks the moment the user and the document use different words. Someone types "cheap flights to Goa"; the page says "low-cost airfare to Dabolim". A SQL LIKE or an inverted index finds nothing, because nothing matches. Embeddings fix this by turning text into numbers that are close together when the meaning is close together, and a vector database is what lets you search those numbers fast once you have millions of them.

If you are preparing for interviews in 2026, expect a question on this. RAG systems, "semantic search" features and many recommendation engines sit on top of it.

What an embedding is

An embedding is a list of floating-point numbers, usually a few hundred to a few thousand long, produced by a model from some input: a sentence, a paragraph, an image, a product. The model is trained so that inputs with similar meaning land near each other in that space.

So "cheap flights to Goa" might become [0.12, -0.33, 0.71, ...] and "low-cost airfare to Dabolim" becomes a different list of numbers that happens to point in nearly the same direction. "How to boil an egg" points somewhere else entirely.

The length of the list is the dimension. OpenAI's text-embedding-3-small produces 1,536 dimensions; many open models from the sentence-transformers family produce 384 or 768. Higher dimension is not automatically better; it is more storage and slower search for a gain that depends on the model.

Two properties matter in practice. Embeddings from different models are not comparable, so you cannot mix them in one index. And the embedding of a text is fixed at the time you compute it, so if you change models you re-embed everything.

How "close" is measured

The usual measure is cosine similarity: the cosine of the angle between two vectors. 1 means the same direction, 0 means unrelated, -1 means opposite. Most embedding models output normalised vectors, so cosine similarity is the same as a dot product, which is one multiply-add per dimension.

import numpy as np

def cosine(a, b):
    a, b = np.array(a, float), np.array(b, float)
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))

goa      = [0.9, 0.1, 0.0]   # toy 3-dimensional vectors
dabolim  = [0.8, 0.2, 0.1]
egg      = [0.0, 0.2, 0.9]

print(cosine(goa, dabolim))  # 0.984
print(cosine(goa, egg))      # 0.024

Real vectors have hundreds of dimensions, but the arithmetic is the same. Euclidean distance (L2) is the other common choice; for normalised vectors the two rankings agree.

Why you cannot just loop

With 10,000 documents you can compute the similarity to every one of them on each query and sort. With 50 million, that is 50 million dot products of 1,536 dimensions per query, and your p99 latency is gone.

Vector databases solve this with approximate nearest neighbour (ANN) indexes. The two you should be able to describe:

HNSW (Hierarchical Navigable Small World). A graph where each vector links to its nearest neighbours, built in layers like a skip list. A query starts at the top, sparse layer, greedily walks toward the closest node, drops a layer and repeats. Search is logarithmic in practice, recall is high, memory use is high because the whole graph lives in RAM. This is what pgvector, Qdrant, Weaviate and most managed services use by default.

IVF (Inverted File index). Cluster the vectors with k-means into, say, 4,096 cells. At query time find the few closest cell centroids and only scan vectors inside those cells. Cheaper to build and store than HNSW, lower recall unless you probe many cells. FAISS popularised it, often combined with product quantisation (IVF-PQ) to compress the vectors themselves.

"Approximate" is the word interviewers want you to notice. These indexes trade a little recall for a lot of speed, and the trade-off is tunable: ef_search in HNSW, nprobe in IVF.

Do you need a separate database?

Not always. A rough hierarchy by size:

  • Under about 100K vectors: a NumPy array or FAISS in memory on one machine.
  • Already on PostgreSQL: the pgvector extension adds a vector column type and HNSW/IVF indexes, so your embeddings live next to your relational data and you filter with normal WHERE clauses.
  • Tens of millions of vectors, metadata filtering, multi-tenancy, replication: a dedicated store such as Qdrant, Milvus, Weaviate, Pinecone or Chroma, or the vector features in Elasticsearch, OpenSearch, Redis or MongoDB Atlas.

In production, the feature you will care about most is filtered search: "nearest neighbours to this query, but only documents owned by tenant 42 and published after 2024". Doing the filter after the ANN search returns too few results; doing it before means a full scan. Real vector databases integrate the filter into the index walk, and how well they do it is the main thing to benchmark.

A worked example: RAG over your docs

  1. Split each document into chunks of roughly 200–500 tokens with some overlap, because an embedding of a 40-page PDF averages everything into mush.
  2. Embed each chunk and store (chunk_id, doc_id, vector, text, metadata).
  3. On a user question, embed the question with the same model.
  4. Query the index for the top k (usually 5–20) chunks, with any metadata filter.
  5. Optionally re-rank those with a cross-encoder, which reads query and chunk together and is more accurate but too slow to run over the whole corpus.
  6. Put the chunks in the prompt and let the LLM answer.

Step 1 and step 5 are where most quality problems come from, not the database.

Interview questions you should expect

  • What is an embedding and why does cosine similarity work on it?
  • Why can't you mix vectors from two models in one index?
  • Explain HNSW. What does it cost in memory, and what is ef_search?
  • When would you pick pgvector over Pinecone? (Answer with data size, existing stack, filtering needs and ops cost.)
  • How does metadata filtering interact with ANN search?
  • Your RAG system returns irrelevant chunks. List the places you would look. (Chunking, embedding model mismatch, no re-ranker, k too small, stale index.)
  • How do you handle updates and deletes in an HNSW index? (Most implementations mark deleted and rebuild periodically.)
  • How would you evaluate retrieval quality? (Recall@k against a labelled set; MRR.)

Go deeper

  • The pgvector README on GitHub, for the exact index options and their defaults.
  • The HNSW paper (Malkov and Yashunin, 2016 preprint) for the layered-graph idea.
  • The FAISS wiki, for IVF and product quantisation.
  • The Hugging Face MTEB leaderboard, for comparing embedding models on retrieval benchmarks.
  • My earlier article on RAG on this site, which assumes the retrieval layer this one explains.