What Is a Vector Database? How It Powers AI Search
November 30, 2026 · 12 min read

What is a vector database? It is a database built to store embeddings, long lists of numbers that capture the meaning of text, images or audio, and to find the stored items whose meaning is closest to a query in milliseconds. That ability, called similarity or semantic search, is what lets a help centre find "refund a duplicate payment" when a customer types "I was charged twice", even though the two share no keywords. Vector search sits behind most AI chatbots that answer from company documents, as well as recommendations, image search and duplicate detection.
The technology has moved from niche to mainstream remarkably quickly. Amazon made its S3 Vectors storage generally available in December 2025, claiming up to 90% lower costs than specialised vector databases, after preview users created more than 250,000 vector indexes and stored over 40 billion vectors, according to InfoQ. MongoDB made vector search generally available in its free Community Edition in June 2026, and PostgreSQL's pgvector extension is offered by almost every managed PostgreSQL service. This guide explains how vector databases work in plain language, shows tested code for both a from-scratch similarity search and pgvector, and helps you decide whether you need a dedicated vector database at all.
What Is a Vector Database Used For?
- Semantic search: finding documents, products or help articles by meaning rather than exact words.
- Retrieval-augmented generation: giving AI chatbots the right passages from your own content.
- Recommendations: suggesting items similar to what a user viewed or bought.
- Image, audio and video search: finding visually or acoustically similar media.
- Duplicate and anomaly detection: spotting near-identical records, fraud patterns or unusual events.
Embeddings: Turning Meaning Into Numbers
Vector search starts with an embedding model, a machine learning model that converts a piece of content into a vector, a fixed-length list of numbers. Text embedding models typically produce several hundred to a few thousand dimensions. The model is trained so that content with similar meaning produces vectors that point in similar directions: "reset my password" and "I can't log in" land close together, while "track my parcel" lands far away. Image and multimodal models do the same for pictures and mixed content.
To compare vectors, databases use distance measures. Cosine similarity compares the angle between two vectors and is the most common choice for text; the dot product and Euclidean distance are alternatives, and the right one depends on how your embedding model was trained. A vector database's job is to store millions or billions of these vectors and quickly return the ones nearest to a query vector, usually together with filters on ordinary metadata such as language, customer or date.
See Similarity Search in 30 Lines
Before adding any database, it helps to see the core idea in plain JavaScript. This example uses tiny four-dimensional vectors that are easy to read, where each dimension represents a topic. Real embeddings are much longer and their dimensions are not human-readable, but the maths is identical:
// similarity.mjs: the core idea of vector search, without a database
// Toy 4-dimensional "embeddings": [billing, account access, delivery, product quality]
// Real embedding models produce hundreds or thousands of dimensions, but the maths is the same.
const articles = [
{ title: "Refund a duplicate payment", vector: [0.9, 0.1, 0.0, 0.1] },
{ title: "Reset your password", vector: [0.0, 0.95, 0.0, 0.05] },
{ title: "Track a late parcel", vector: [0.05, 0.0, 0.9, 0.1] },
{ title: "Update your card details", vector: [0.7, 0.4, 0.0, 0.0] },
{ title: "Return a faulty item", vector: [0.3, 0.0, 0.3, 0.8] },
];
const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
const norm = (a) => Math.sqrt(dot(a, a));
const cosine = (a, b) => dot(a, b) / (norm(a) * norm(b)); // 1 = same direction, 0 = unrelated
function search(queryVector, k = 2) {
return articles
.map((a) => ({ title: a.title, score: cosine(queryVector, a.vector) }))
.sort((x, y) => y.score - x.score)
.slice(0, k);
}
// "I was charged twice for my order" embeds close to the billing dimension
for (const hit of search([0.85, 0.05, 0.1, 0.05])) console.log(`${hit.score.toFixed(3)} ${hit.title}`);
Running it prints:
0.991 Refund a duplicate payment
0.888 Update your card details
The billing article scores highest, followed by the card details article, which is partly about billing and partly about account access. This brute-force approach compares the query with every stored vector, which is perfectly fine for a few thousand items. For millions, comparing against everything becomes too slow, which is the problem vector databases exist to solve.
How Vector Databases Search Billions of Vectors
Instead of exact search, vector databases use approximate nearest-neighbour (ANN) indexes that return almost always the right results in a tiny fraction of the time. The most popular is HNSW, short for hierarchical navigable small world, which links vectors into a layered graph: a search starts in a sparse top layer, hops towards the query and descends into denser layers until it reaches the closest neighbours. IVF indexes instead group vectors into clusters and search only the clusters nearest the query. Quantisation techniques compress vectors so more fit in memory, at a small cost in accuracy.
Every index trades three things against each other: recall, meaning how often the true nearest neighbours are found, speed and memory. Parameters such as HNSW's search breadth let you tune that balance, and measuring recall on your own data is part of doing vector search properly.
Vector Search Inside PostgreSQL With pgvector
If your application already uses PostgreSQL, the pgvector extension adds a vector column type, distance operators and HNSW and IVFFlat indexes, so embeddings can sit next to the rows they describe. This script stores help articles with their embeddings, builds an HNSW index and runs a filtered similarity search:
-- pgvector: store embeddings next to your relational data and search them with SQL
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE help_articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
language text NOT NULL,
embedding vector(4) NOT NULL -- use your model's size, e.g. vector(1536)
);
INSERT INTO help_articles (title, language, embedding) VALUES
('Refund a duplicate payment', 'en', '[0.9, 0.1, 0.0, 0.1]'),
('Reset your password', 'en', '[0.0, 0.95, 0.0, 0.05]'),
('Track a late parcel', 'en', '[0.05, 0.0, 0.9, 0.1]'),
('Update your card details', 'en', '[0.7, 0.4, 0.0, 0.0]'),
('Rembourser un double paiement', 'fr', '[0.88, 0.12, 0.0, 0.1]');
-- Approximate nearest-neighbour index using cosine distance
CREATE INDEX ON help_articles USING hnsw (embedding vector_cosine_ops);
-- Keep searching the index until enough rows pass the filter (pgvector 0.8+)
SET hnsw.iterative_scan = relaxed_order;
-- Top 2 English articles closest to the question's embedding
SELECT title, round((1 - (embedding <=> '[0.85, 0.05, 0.1, 0.05]'))::numeric, 3) AS similarity
FROM help_articles
WHERE language = 'en'
ORDER BY embedding <=> '[0.85, 0.05, 0.1, 0.05]'
LIMIT 2;
Run against PostgreSQL 19 with pgvector through PGlite, the final query returns:
0.991 Refund a duplicate payment
0.888 Update your card details
The results match the plain JavaScript version, and the language filter correctly excludes the French article even though it is very similar. Filtering is where approximate indexes used to struggle: an index scan returns a limited number of candidates, and if most of them fail the filter, too few results come back. The pgvector 0.8 release added iterative index scans, enabled by the hnsw.iterative_scan setting above, which keep searching until enough rows pass the filter.
How Vector Databases Power AI Search and RAG
Retrieval-augmented generation, or RAG, is the most common reason teams adopt vector search today. The pattern has two phases:
- Indexing: split documents into chunks of a few hundred words, create an embedding for each chunk and store the vectors with metadata such as source, date and permissions.
- Answering: embed the user's question, retrieve the most similar chunks the user is allowed to see, and pass them to a large language model as context so it answers from your content rather than from memory alone.
Production systems usually add hybrid search, which combines vector similarity with traditional keyword search so exact terms such as product codes are not missed, plus a reranking step that reorders the top results with a more precise model. Our step-by-step guide on how to build a RAG app covers the full pipeline, our comparison of RAG vs fine-tuning explains when retrieval is the right approach, and good retrieval is one of the most effective ways to reduce AI hallucinations.
Your Vector Database Options in 2026
| Option | Examples | Best when |
|---|---|---|
| Vector search in your existing database | PostgreSQL with pgvector, MongoDB Vector Search, Redis, Elasticsearch and OpenSearch | You want one system, transactional consistency and simple operations |
| Dedicated vector databases | Pinecone, Weaviate, Qdrant, Milvus, Chroma | You need very large scale, low latency at high query rates or advanced vector features |
| Vector storage on object storage | Amazon S3 Vectors, LanceDB | You store huge volumes cheaply and can accept somewhat slower queries |
| Libraries in your own code | FAISS, hnswlib | You need full control or run search inside a specialised service |
Vector Search in a Next.js Application
In a typical Next.js project, the search box in the browser sends the user's question to a server-side route handler. That handler calls the embedding model, queries the vector index with the user's permissions applied as filters, and returns the matching results or passes them to a language model whose answer is streamed back to the page. Keep every API key and database connection on the server, never in browser code, and add rate limiting so nobody can run up your embedding bill. Embeddings for your own documents should be created in a background job whenever content changes, not on each search, so the user only waits for one embedding call and one fast index lookup.
Do You Need a Dedicated Vector Database?
For most applications starting out, no. If your data already lives in PostgreSQL or MongoDB and you have up to a few million vectors, keeping embeddings in the same database is simpler: one backup, one security model, and filters and joins on your existing data. Our guides to PostgreSQL vs MySQL and MongoDB vs PostgreSQL cover how each handles vectors. Consider a dedicated vector database when you reach tens or hundreds of millions of vectors, need consistently low latency under heavy query load, serve many isolated tenants, or need features such as built-in hybrid search and reranking at scale. Object-storage options suit very large archives that are queried occasionally, where cost matters more than milliseconds.
Costs and Performance Tips
- Mind the memory. A 1,536-dimension vector stored as 4-byte floats takes about 6 KB, so a million vectors need roughly 6 GB before index overhead. Half-precision types, such as pgvector's
halfvec, and quantisation cut this significantly. - Choose dimensions deliberately. Smaller embedding models are cheaper to store and search, and are often accurate enough for focused domains.
- Batch and cache embeddings. Embedding the same text twice wastes money; cache results, as explained in our guide to Redis caching.
- Plan for re-embedding. Vectors from different models are not comparable, so switching models means re-embedding everything.
- Measure retrieval quality, not just speed, with a set of real questions and expected answers; see our guide to LLM evaluation.
Common Mistakes
- Ignoring permissions: in multi-user systems, filter retrieved chunks by what each user may see, or a chatbot can leak confidential documents.
- Poor chunking: chunks that are too large dilute meaning, and chunks that are too small lose context.
- Vector search only: skipping keyword search misses exact matches such as names, codes and numbers.
- Mixing embedding models in one index, which makes similarity scores meaningless.
- Adding infrastructure too early: a separate vector service you do not yet need adds cost and operational work. Our SQL vs NoSQL guide covers the wider database landscape.
Frequently Asked Questions
What is a vector database in simple terms?
It is a database that stores numerical representations of meaning, called embeddings, and quickly finds the items most similar to a question or example, even when they share no exact words.
How is a vector database different from a regular database?
A regular database finds exact matches and ranges, such as customer ID 42 or orders over $100. A vector database finds the closest matches by meaning, using similarity between embeddings, and is optimised for that kind of search.
Is PostgreSQL a vector database?
Not on its own, but with the pgvector extension PostgreSQL can store embeddings, build approximate nearest-neighbour indexes and run similarity searches, which is enough for many applications.
Do I need a vector database for RAG?
You need vector search, but not necessarily a separate vector database. For small and medium document collections, pgvector, MongoDB Vector Search or a similar feature in your existing database works well.
What are embeddings?
Embeddings are lists of numbers produced by a machine learning model to represent the meaning of text, images or other data, arranged so that similar content has similar numbers.
Which vector database is best?
There is no single best option. Start with vector search in your existing database, and consider dedicated options such as Pinecone, Qdrant, Weaviate or Milvus when scale, latency or features demand them.
Add AI Search to Your Product
We build AI search, RAG chatbots and recommendation features on PostgreSQL, MongoDB and dedicated vector databases, with evaluation and access control built in. Contact our team to plan your AI search project.