New Tool Radar

AI Concepts

How to Store Document Embeddings in PostgreSQL With pgvector

Enable pgvector, store embeddings in a table with an HNSW index, and run a cosine similarity query.

Schematic with three steps: Enable the extension and create the table; Create the HNSW index; Run a cosine similarity query.

You do not need a separate vector database on day one. Store the vectors in PostgreSQL with the pgvector extension, and you can join search results to the rest of your application tables in a single SQL query. The table holds the chunk text and its embedding side by side, and an HNSW index makes approximate nearest-neighbour search fast.

What you need

  • PostgreSQL with the pgvector extension available
  • Embeddings for your chunks, 1536 dimensions for text-embedding-3-small
  • A table design with document_id, content and metadata columns

Step 1: Enable the extension and create the table

Run CREATE EXTENSION IF NOT EXISTS vector, then create a document_chunks table with an embedding column of type vector(1536) for text-embedding-3-small, plus document_id, content, source_url and section_heading.

Step 2: Create the HNSW index

Create an index using hnsw on the embedding column with vector_cosine_ops, so nearest-neighbour search uses the index instead of scanning every row.

Step 3: Run a cosine similarity query

Select the top 5 chunks ordered by the cosine distance operator, computing similarity as 1 minus the distance. Add tenant or workspace filters to the same query before relying on it in a product.

Worked example: synthetic pgvector query check

The table below is a synthetic example. It shows the expected result of a pgvector query; no database was created.

Check Value Result
Table document_chunks Created
Index HNSW, vector_cosine_ops Created
Query Top 5 by cosine similarity 5 returned
Tenant filter workspace_id applied Pass

Expected result (UNTESTED). the table and HNSW index exist, a query returns the 5 nearest chunks, and the tenant filter keeps results inside one workspace. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • The 0.70 similarity cutoff in the published example is only an example; pick a threshold from your own evaluation set, or skip the cutoff and take a top-k list into a re-ranker.
  • A similarity search with no tenant filter can return another customer documents; store workspace_id or tenant_id on every chunk.
  • Schedule maintenance with REINDEX INDEX CONCURRENTLY and VACUUM ANALYZE, since a stale index slows queries.
  • pgvector fits small scale and teams already on PostgreSQL; very large scale may need a dedicated vector store.

Sources

See all