← All posts

Building with LLMs › RAG and vector search

What is a vector database? How AI apps find similar things

What a vector database is, how ANN and HNSW find the closest embeddings fast, how it differs from a regular database, and when plain numpy is enough.

If you’ve followed a tutorial on building a chatbot that answers from your own documents, you were probably told at some point to put your data into a vector database. The term also turns up in diagrams of how LLM apps are built, often next to names like Pinecone, Milvus, and Chroma. Perhaps you nodded and kept going, though, without being sure how it differs from the databases you already know.

A vector database is a database that stores embedding vectors and quickly finds the ones closest to a vector you give it. An embedding is a list of hundreds or thousands of numbers that a model makes from a piece of text or an image, arranged so that things with similar meanings land close together. So finding the closest vectors amounts to finding the sentences that mean something similar. Much of the reason you hear the term so often now is probably RAG. In RAG, an app looks up relevant documents and hands them to a language model before it answers, and keeping those documents and finding them again is often the vector database’s job.

Looking for an exact match and looking for something similar

A regular database is good at finding what matches. Ask for the books by Mary Shelley and it returns exactly the rows that meet the condition, and keyword search, too, still looks for the same words. So a note that reads “Clean the fan if your laptop gets too hot” won’t turn up for “My computer is overheating,” because the two share no words. A vector database asks instead which stored vectors are closest to the query’s vector. That’s why, if the embedding model has placed the two sentences near each other, the note comes back with no word in common.

Aspect Regular database Vector database
What it mostly stores Rows or documents with values Vectors, with the original text and metadata
What a query asks Which rows meet this condition? Which vectors are closest to this one?
What comes back Every row that matches The k closest items and their distances
Index B-tree and similar, exact An ANN index such as HNSW, approximate

I’ll get to ANN and HNSW after the example. There’s one more difference, too. A vector search returns the k closest items even when none of them is really related.

Six notes in Chroma

I put six short notes, each with a category as metadata, into Chroma, an open-source database that runs right inside Python. For the embeddings I chose all-MiniLM-L6-v2, a small public model that turns a sentence into 384 numbers, and I made the vectors myself so you can see what gets stored. normalize_embeddings=True scales every vector to length 1.

import chromadb
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

notes = [
    ("Store bread in the freezer so it doesn't go stale.", "kitchen"),
    ("Let the pan heat up before you add the oil.", "kitchen"),
    ("Pack a plug adapter when you go abroad.", "travel"),
    ("Get to the airport two hours before an international flight.", "travel"),
    ("Restart the router when the Wi-Fi keeps dropping.", "computer"),
    ("Clean the fan if your laptop gets too hot.", "computer"),
]
texts = [text for text, _ in notes]
vectors = model.encode(texts, normalize_embeddings=True)  # one vector per note

client = chromadb.Client()  # in-memory; the data is gone when the program ends
collection = client.create_collection(
    "notes", configuration={"hnsw": {"space": "cosine"}}
)
collection.add(
    ids=[f"note-{i}" for i in range(len(notes))],
    documents=texts,
    metadatas=[{"category": category} for _, category in notes],
    embeddings=vectors,
)
print(collection.count(), vectors.shape)
6 (6, 384)

Six vectors of 384 numbers went in, and I’ll come back to the distance measure set by "space": "cosine". The question has to go through the same model, because vectors from different models can’t be compared.

def search(text, n=3, where=None):
    query = model.encode([text], normalize_embeddings=True)
    result = collection.query(query_embeddings=query, n_results=n, where=where)
    for doc, dist in zip(result["documents"][0], result["distances"][0]):
        print(f"{dist:.3f}  {doc}")

search("My computer is overheating")
0.429  Clean the fan if your laptop gets too hot.
0.786  Let the pan heat up before you add the oil.
0.867  Pack a plug adapter when you go abroad.

The laptop fan note comes first, with no words in common. The number on the left is the cosine distance, one minus the cosine similarity, so closer to 0 means more alike. The pan and the plug adapter, on the other hand, jump to 0.786 and 0.867. They were only the least distant of what was left, not good answers, so real apps often drop results beyond a distance limit chosen by looking at their own data.

How it finds the closest ones fast

With six notes, comparing the question against all of them is fine, but with ten million, doing that for every question gets slow. That’s why most vector databases use approximate nearest neighbor search, or ANN. It gives up the promise of always finding the true closest items in exchange for answering much faster, and the share of the true top k that a search actually finds is called recall.

HNSW, one of the best-known ANN methods, comes from a paper on Hierarchical Navigable Small World graphs that Malkov and Yashunin first posted to arXiv in March 2016. It stacks graphs of linked nearby vectors in layers, with every vector in the bottom layer and fewer the higher you go. That’s because each vector is given a random top layer, and the chance of reaching each higher one drops quickly. A search starts at the top, keeps stepping to whichever neighbor is closer to the query, and when no neighbor is closer, it drops a layer and carries on. Chroma’s configuration docs compare the upper layers to highways, so it’s like taking the highway to the right city and then switching to smaller streets. The paper says this structure allows “a logarithmic complexity scaling,” meaning the work grows far more slowly than the data.

Still, always stepping to the nearest neighbor can stop at a spot that only looks best locally and miss a true neighbor elsewhere. So HNSW carries a list of candidates as it searches. In Chroma, that list’s size is ef_search (100 by default) and each vector’s link limit is max_neighbors (16 by default), and raising them improves recall but costs time and memory. The pgvector README puts the trade plainly. It searches exactly by default, and an approximate index “trades some recall for speed.”

Cosine, dot product, and Euclidean distance

What counts as closest depends on how you measure. Cosine looks only at the angle between two vectors, the dot product (inner product) multiplies matching numbers and adds them up so length counts too, and Euclidean distance is the straight line between two points. Chroma calls them cosine, ip, and l2, and since its default is l2, the squared Euclidean distance, I set cosine in the example. When every vector has length 1, the three rank things the same way. To see this, and to check Chroma’s answer, I compared the question against all six vectors with numpy.

import numpy as np

q = model.encode(["My computer is overheating"], normalize_embeddings=True)[0]
cos = vectors @ q  # dot product equals cosine similarity for length-1 vectors
l2 = ((vectors - q) ** 2).sum(axis=1)  # squared Euclidean distance
for i in np.argsort(-cos)[:3]:
    print(f"{1 - cos[i]:.3f}  {l2[i]:.3f}  {texts[i]}")
0.429  0.858  Clean the fan if your laptop gets too hot.
0.786  1.572  Let the pan heat up before you add the oil.
0.867  1.734  Pack a plug adapter when you go abroad.

The cosine distances in the first column match Chroma’s, and the squared Euclidean distances in the second are exactly twice as large, so the order is the same. For length-1 vectors the dot product is the cosine similarity itself, which is why vectors @ q works. With vectors that aren’t normalized the measures can disagree, so the safer choice is usually the one the model was trained with. The model card says all-MiniLM-L6-v2 was trained on cosine similarity between sentence pairs.

Narrowing the search with metadata filters

In practice, you often want only the current user’s documents, only this year’s posts, or only one category. Metadata is the extra information stored next to each vector for times like these, and Chroma takes the condition through a where argument (metadata filtering). I asked one question without a filter and then only among the kitchen notes.

search("Something is getting too hot", n=2)
print("---")
search("Something is getting too hot", n=2, where={"category": "kitchen"})
0.503  Clean the fan if your laptop gets too hot.
0.637  Let the pan heat up before you add the oil.
---
0.637  Let the pan heat up before you add the oil.
0.919  Store bread in the freezer so it doesn't go stale.

With the filter, the laptop note dropped out and only the two kitchen notes came back. The bread note is far away at 0.919, but it was the second closest among the kitchen notes, so it filled the slot.

With an ANN index, though, the order of filtering matters. If a database takes the top candidates first and filters afterward, you can get fewer results than you asked for. According to the pgvector README, if a condition matches 10% of rows, then with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average. That’s why, since 0.8.0, pgvector has offered iterative index scans you can turn on to keep scanning until enough results are found. So when you choose a product, how it handles filters deserves a look too.

Dedicated vector databases and vector features in existing ones

Products fall into two rough groups. One is dedicated databases built around vectors. Besides Chroma, the open-source Milvus and Qdrant, and Pinecone, a fully managed service, all describe themselves as vector databases. The other is vector features added to databases you may already use, such as pgvector for PostgreSQL, MongoDB Vector Search, and Elasticsearch’s kNN search. Their appeal is one less system to run. The pgvector README, too, notes that you store vectors with the rest of your data and keep Postgres features like ACID compliance and JOINs. If you already run PostgreSQL or MongoDB, perhaps the easiest first step is the vector feature you already have.

When you don’t need a vector database

With a few thousand vectors, or even tens of thousands, comparing them all with numpy as above is fast enough. On my Apple M4 Mac, comparing one question against 10,000 vectors of 384 numbers took 0.1 to 0.25 milliseconds across several runs, and the vectors used about 15 MB of memory. A million vectors took 30 to 40 milliseconds per search, but filled 1.5 GB of memory. The Elasticsearch docs also say brute-force search is the best fit for small datasets.

A vector database earns its place when the data outgrows memory, when vectors change all the time, when many people search at once, or when you want filtering and persistence handled for you. Of course, for product codes or error messages, where the exact characters matter, keyword search often does better, and many systems use both.

Where to start

If you’re new to this, install chromadb and sentence-transformers with pip and run the four blocks above in order. Then swap the notes for a few dozen of your own sentences and watch the distances, which will show you where close enough ends in your data. To keep data across restarts, use the persistent client that the getting started guide points to. I ran these examples on October 27, 2026, on an Apple M4 Mac with Python 3.13.12, Chroma 1.5.9, sentence-transformers 6.2.0, and numpy 2.5.4.

AI tools helped with the research for this post.