Tutorial

Storing and Querying Embeddings with pgvector

Keep vectors in PostgreSQL beside the rows they describe, choose the right index and operator, and write similarity queries that filter correctly.

On this page

  1. Introduction
  2. Why Keep Vectors Next to Your Data
  3. Choosing a Vector Type and Dimension
  4. Building the Right Index for the Query
  5. Writing Similarity Queries Correctly
  6. Filtering by Metadata Without Losing Recall
  7. Maintaining and Monitoring the Index
  8. Sources

Introduction

A dedicated vector database is not required to ship semantic search. The pgvector extension adds a vector column type and index operators to PostgreSQL, so embeddings live in the same transaction, backup and access control boundary as the text they describe. For most applications below a few million rows this is the simplest correct choice: one database to operate, joins to metadata for free, and no synchronization job between a relational store and a separate index. This article covers the schema, the index, the operators and the traps that quietly destroy recall, because getting the schema and index right up front avoids a costly migration once millions of vectors are stored.

Why Keep Vectors Next to Your Data

Storing vectors in the same database as your rows lets you filter, join and update them atomically. Deleting a document deletes its vectors in the same transaction, so the index cannot drift out of sync with the source of truth. You reuse existing backups, replication and row level security instead of building a second operational surface. The connection your application already opens to read documents is the same one that runs the vector query, so there is no new client library or network hop to introduce. A separate vector store only wins when the index exceeds the memory a single Postgres instance can afford or when query volume must scale independently of transactional traffic.

-- Enable the extension and create the schema.
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id        bigserial PRIMARY KEY,
  doc_id    text        NOT NULL,
  tenant    text        NOT NULL,
  body      text        NOT NULL,
  embedding vector(1536) NOT NULL
);

-- HNSW index for cosine distance; build after a first load.
CREATE INDEX chunks_embedding_idx
  ON chunks USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

-- Partial index for one hot tenant, much smaller and faster.
CREATE INDEX chunks_tenant_idx
  ON chunks USING hnsw (embedding vector_cosine_ops)
  WHERE tenant = 'acme';

Choosing a Vector Type and Dimension

pgvector offers two storage types: vector for single precision floats and halfvec for half precision. Half precision halves storage and, for most text embeddings, the retrieval quality loss is negligible; because the index must fit in memory to stay fast, that saving can double how many vectors one instance holds. The dimension in the column definition must match the embedding model exactly, since a query vector of the wrong length is rejected at runtime. Fix the dimension before you load data, because changing the embedding model afterwards means re-computing and re-indexing every vector in the corpus.

-- Set the number of candidates explored per query (higher = better recall).
SET hnsw.ef_search = 100;

-- Approximate search, index-backed. Confirm with EXPLAIN.
SELECT id, doc_id, 1 - (embedding <=> $1) AS similarity
FROM chunks
WHERE tenant = $2
ORDER BY embedding <=> $1
LIMIT 10;

-- Verify recall: compare against exact search with the index disabled.
SET enable_indexscan = off;
SELECT count(*) FROM (
  SELECT id FROM chunks WHERE tenant = $2
  ORDER BY embedding <=> $1 LIMIT 10
) exact
WHERE id IN (
  SELECT id FROM chunks WHERE tenant = $2
  ORDER BY embedding <=> $1 LIMIT 10
);

Building the Right Index for the Query

Without an index every query scans every row, which is acceptable for thousands of vectors and fatal for millions. HNSW builds a navigable graph that answers approximate nearest neighbour queries in logarithmic time with high recall and fast builds, at the cost of memory. IVFFlat clusters vectors into lists and probes a subset, using less memory but requiring data to be present before the index is built. Smaller m keeps the graph shallow and builds quickly, while larger m improves recall at the cost of memory and build time. Create the index with the operator class that matches your distance metric and set its build parameters deliberately, building after the first load so the graph covers the real distribution.

Writing Similarity Queries Correctly

The operator you use must match the operator class of the index or the planner will ignore the index and fall back to a sequential scan. pgvector defines cosine distance with the <=> operator, negative inner product with <#>, and Euclidean distance with <->. Choose the metric your embedding model was trained for, which for normalised text embeddings is almost always cosine. Return the similarity rather than the raw distance, because reporting a distance where a caller expects a similarity inverts your ranking. Use ORDER BY embedding <=> query LIMIT k and confirm with EXPLAIN that the index is used.

Filtering by Metadata Without Losing Recall

Filtering by tenant, language or date is essential, but applying the filter after the index search can return fewer than k rows because the nearest neighbours were filtered out. PostgreSQL 0.8 and later support iterative index scans that keep probing until enough rows survive the filter, recovering recall at a small latency cost. When selectivity is very high, a partial index over the hot subset is faster still, because it is smaller and its graph only covers relevant rows. Always test recall on filtered queries, not only on unfiltered benchmarks, since a filtered query can collapse under a selective predicate in production.

Maintaining and Monitoring the Index

An approximate index degrades as rows are inserted, updated and deleted, because the graph no longer reflects the current distribution. Rebuild periodically or use the maintenance functions, and watch index size against available memory. Test with representative queries and compare returned rows against an exact search on the same data to measure actual recall. Track query latency at p95 and p99 and alert when it rises, because a slow vector query usually means the index fell out of memory and is being served from disk. Log the fraction of rows that survive each filter class so a sudden drop signals a shift in the data distribution.

Sources

Sources: pgvector, PostgreSQL indexes, PostgreSQL EXPLAIN.

FAQ

When should I move from pgvector to a dedicated vector database?
Move when the index no longer fits in RAM on your Postgres instance, when vector queries need to scale independently of transactional traffic, or when you need features such as multi-region replication that Postgres cannot provide cheaply.
Which distance operator should I use?
Use the metric your embedding model was trained with, which for most text embeddings is cosine, written with the <=> operator and backed by vector_cosine_ops.

Related Examples