Vector Databases: How AI Systems Store and Search Embeddings

Server racks in a data center, representing where vector databases store AI embeddings

A vector database stores embeddings, which are lists of numbers that represent the meaning of text, images or other data, and finds the stored items whose embeddings are closest to a query embedding. That “find what is nearby” operation is what powers semantic search, recommendations and the retrieval step in retrieval-augmented generation (RAG). To stay fast at scale, vector databases use approximate nearest neighbor (ANN) indexes that trade a small amount of accuracy for large speed gains.

This guide explains how that works, walks through a complete example in PostgreSQL with the pgvector extension, and ends with a decision table for when a dedicated vector database is worth adding to your stack.

The problem a vector database solves

Traditional databases are built to match exact values or ranges: WHERE sku = 'A-113' or WHERE price < 50. Meaning does not work that way. A customer searching for “affordable laptop” should find a product described as a “budget-friendly notebook,” even though the two strings share no words.

Embedding models solve the representation half of the problem. They turn each piece of content into a vector, often with hundreds or thousands of dimensions, placed so that similar meanings end up near each other. OpenAI’s current embedding models, for example, return 1,536 dimensions for text-embedding-3-small and 3,072 for text-embedding-3-large, and accept a dimensions parameter to return shorter vectors (OpenAI embeddings guide). For the background on how embeddings are produced, see how AI turns text into numbers.

A vector database solves the other half: storing millions of those vectors alongside their source data and metadata, and answering “which stored vectors are closest to this one?” in milliseconds.

How similarity is measured

Similarity between two vectors is measured with a distance function, and the right one depends on how your embedding model was trained. The three you will meet most often:

  • Cosine distance compares the angle between two vectors and ignores their length. It is the usual default for text embeddings.
  • Inner (dot) product multiplies the vectors element by element and sums the result. When vectors are normalized to length 1, ranking by inner product gives the same order as ranking by cosine, and it is slightly cheaper to compute.
  • Euclidean (L2) distance is the straight-line distance between two points. It is common for image and some recommendation embeddings.

Use whatever the embedding model’s documentation recommends, and use the same metric in your index and your queries. A mismatch does not throw an error; it just quietly returns worse results. If you shorten vectors yourself rather than through the API parameter, OpenAI’s guide notes that you need to re-normalize them.

How vector search stays fast: ANN indexes

The exact way to find nearest neighbors is to compare the query with every stored vector, which is called a brute-force or flat search. That is fine for thousands of vectors and becomes slow for millions, because each comparison touches every dimension. ANN indexes avoid most of those comparisons by organizing vectors so the search can skip regions that cannot contain good matches.

HNSW (graph-based)

Hierarchical Navigable Small World (HNSW) builds a stack of proximity graphs. The top layers are sparse with long-range links; the bottom layer contains every vector with short-range links. A search enters at the top, greedily moves toward the query, and drops down a layer each time it cannot get closer, a design the original HNSW paper by Malkov and Yashunin compares to a skip list and credits with logarithmic search scaling. pgvector’s documentation describes it as having a better speed-to-recall trade-off than IVFFlat. Its costs are memory, since the graph lives alongside the vectors, and slower index builds.

IVF (cluster-based)

Inverted file (IVF) indexes split the vectors into clusters, called lists, around centroids. A query is compared with the centroids first and then searched only inside the closest few lists. IVF builds faster and uses less memory than HNSW, but usually gives a worse speed-to-recall trade-off, and it needs existing data to train the centroids.

Recall: the number to watch

Recall is the share of the true nearest neighbors that the approximate search actually returns. Every ANN index has a query-time knob that trades speed for recall: more candidates examined means better recall and slower queries. When someone says a vector search is “fast,” ask at what recall.

Worked example: semantic search in PostgreSQL with pgvector

The quickest way to understand a vector database is to build one small table. The example below uses pgvector, an open-source PostgreSQL extension, because many teams already run Postgres. The product data is illustrative and the vectors are shortened to three dimensions so the SQL stays readable; in a real system the column would match your embedding model’s output size.

Step 1: Enable the extension and create the table

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE products (
  id          bigserial PRIMARY KEY,
  name        text NOT NULL,
  description text NOT NULL,
  category    text NOT NULL,
  in_stock    boolean NOT NULL DEFAULT true,
  embedding   vector(3)   -- use your model's dimension, e.g. vector(1536)
);

The vector sits in the same row as the metadata you will filter on. That is the main practical advantage of a database over a bare vector index: you get IDs, categories, dates and permissions next to the embedding, inside one transaction.

Step 2: Insert rows with embeddings

-- In production your application calls the embedding API and
-- inserts the returned array. Toy values for illustration:
INSERT INTO products (name, description, category, in_stock, embedding) VALUES
 ('Aero 13',  'Budget-friendly notebook for students', 'laptops', true,  '[0.91,0.10,0.05]'),
 ('Titan X',  'High-end gaming laptop with RTX GPU',   'laptops', true,  '[0.55,0.80,0.10]'),
 ('Lumen 14', 'Low-cost ultrabook, long battery',      'laptops', false, '[0.88,0.15,0.12]'),
 ('Desk Pro', 'Standing desk with memory presets',     'office',  true,  '[0.05,0.10,0.95]');

Embed the same text you want to match against. For products that is usually name plus description; for documents it is each chunk, not the whole file. How you split documents has a large effect on retrieval quality, which our comparison of fixed-size, recursive, semantic and contextual chunking covers in detail.

Step 3: Add an ANN index

-- Cosine distance index; operator class must match the query operator
CREATE INDEX ON products USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

The values shown are pgvector’s documented defaults: m is the maximum number of connections per node per layer and ef_construction is the candidate list size used while building. Raising them improves recall at the cost of build time and memory. pgvector also supports IVFFlat; its README suggests starting with roughly rows/1000 lists up to a million rows and creating the index only after the table has data.

Step 4: Query by meaning, with a filter

-- The app embeds "affordable laptop" and passes the vector as $1
SELECT id, name, 1 - (embedding <=> $1) AS cosine_similarity
FROM products
WHERE category = 'laptops' AND in_stock
ORDER BY embedding <=> $1
LIMIT 5;

In pgvector, <=> is cosine distance, <-> is L2 distance and <#> is negative inner product. With the toy vectors above, a query vector close to [0.9, 0.1, 0.1] would rank “Aero 13” first, skip “Lumen 14” because it is out of stock, and never consider the desk because of the category filter.

Step 5: Tune recall at query time

SET hnsw.ef_search = 100;                 -- default 40; higher = better recall, slower
SET hnsw.iterative_scan = relaxed_order;  -- keep scanning when filters remove rows

Errors and surprises you are likely to hit

Most first-time vector search problems come from a few predictable mismatches rather than from the database itself.

  1. “expected N dimensions, not M.” The vector you inserted or queried does not match the column size. Usually the embedding model changed or a dimensions parameter was set in one code path and not another. Pin the model and dimension in one config value.
  2. The index is not used. The operator in ORDER BY must match the index operator class: a vector_cosine_ops index serves <=>, not <->. Also, the query needs ORDER BY ... LIMIT for the planner to choose the ANN index. Check with EXPLAIN.
  3. Filtered queries return fewer rows than LIMIT. With approximate indexes, filtering happens after the index scan, so a restrictive WHERE can discard most candidates. pgvector added iterative index scans in version 0.8.0 to keep scanning until enough rows pass; otherwise raise ef_search or add a partial index for common filters.
  4. Index too large to index at all. pgvector can index the vector type up to 2,000 dimensions. For larger embeddings, store or index as halfvec (half precision, up to 4,000 dimensions) or request shorter vectors from the embedding API.
  5. Mixed embedding models in one column. Vectors from different models live in different spaces, and their distances are meaningless to compare. When you switch models, re-embed everything into a new column and cut over.
  6. Good similarity, wrong answer. Nearest neighbors are “similar,” not “correct.” Exact identifiers such as error codes, SKUs or names often match better with keyword search. Many systems run hybrid search, combining a keyword score such as BM25 with vector similarity, and merge the results.

Where vector databases fit in RAG

In a RAG system the vector database is the retrieval layer. Documents are split into chunks, each chunk is embedded and stored with metadata such as source URL, section and access permissions. At question time the question is embedded, the top matching chunks are retrieved (filtered by what that user may see), and those chunks are inserted into the model’s prompt as context. Our plain-English guide to RAG covers the full pipeline.

Two points are easy to miss. First, permission filtering must happen in the retrieval query, not after generation, or the model will see text the user should not. Second, retrieving more chunks is not automatically better: irrelevant chunks dilute the context and can lead to confident but wrong answers, a problem discussed in our article on reducing AI hallucinations with better prompts.

Dedicated vector database, extension, or library?

You have three broad options, and the right one depends far more on your existing infrastructure and data size than on benchmark charts.

OptionExamplesChoose it whenWatch out for
In-process libraryFAISS, hnswlib, NumPy brute forcePrototypes, offline jobs, small static datasets that fit in memoryNo persistence, metadata, access control or concurrent writes unless you build them
Vector extension on your current databasepgvector for PostgreSQL; vector search features in several document and search databasesYou already run that database, data is up to a few million vectors, you need joins, transactions and filtersIndex memory competes with your normal workload; tuning ANN is your job
Dedicated vector databaseManaged or self-hosted services built specifically for vector searchVery large collections, high query volume, multi-tenant isolation, built-in hybrid searchAnother system to secure, back up and keep in sync with your source of truth

A reasonable default for most teams: start with the extension on the database you already operate, measure recall and latency on your real queries, and move to a dedicated service only when a specific limit appears, such as index memory, write throughput or tenant isolation. Treat the vector store as derived data that can be rebuilt from the source documents and the embedding model, because at some point you will change one of them.

Questions the sections above leave open

Is a vector database the same as an AI model?

No. The embedding model creates the vectors; the vector database stores and searches them. You can swap either one independently, though swapping the embedding model means re-embedding all stored content.

Can it replace my relational database?

Generally no. Vector databases store metadata and support filters, but they are not designed as the system of record for orders, users or invoices. Keep the authoritative data where it is and store IDs that point back to it.

Does the embedding dimension affect cost?

Yes. Storage and index memory grow roughly linearly with dimension, and so does the cost of each distance calculation. Shorter vectors from an API that supports a dimensions parameter, or half-precision storage, can cut memory substantially; measure recall on your own queries before and after to confirm the quality trade-off is acceptable.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top