4 Hours

12. pgvector: AI Embeddings & Semantic Search

AI

Turn Your Postgres Database into a Vector Store

The pgvector extension adds a native vector data type to Postgres, enabling you to store high-dimensional AI embeddings and perform semantic similarity search — finding content that is conceptually similar, not just keyword-matching. This powers Retrieval-Augmented Generation (RAG), semantic search, recommendation engines, and duplicate detection.

Vector embeddings are the foundation of modern AI applications. An embedding is a list of numbers that represents the meaning of a piece of text, image, or other content. Content with similar meaning has embeddings that are close together in vector space. pgvector adds vector data types, distance operators, and indexes to Postgres. This means you can store embeddings alongside your relational data and query them with SQL. You can join vectors with your users, products, and orders in the same query. This is incredibly powerful for building AI applications. The vector indexes support efficient approximate nearest neighbor search, making it fast to find similar items even with millions of vectors.

What Are Vector Embeddings?

Embeddings are produced by AI models like OpenAI's text-embedding-3-small or Google's text-embedding-004. The model takes text as input and outputs a list of numbers. The numbers capture the semantic meaning of the text. Similar texts have similar embeddings. For example, the embedding for king is close to the embedding for queen but far from the embedding for laptop. The dimensionality of the embedding depends on the model — 1536 for text-embedding-3-small, 768 for other models. You store the embedding as a vector in Postgres. To find similar items, you calculate the distance between your query embedding and the stored embeddings. The distance operators in pgvector support cosine distance, L2 distance, and inner product. Cosine distance is most common for text embeddings.

SQL
-- Enable pgvector
CREATE EXTENSION IF NOT EXISTS vector;

-- Create a table to store documents with their embeddings
CREATE TABLE documents (
  id BIGSERIAL PRIMARY KEY,
  content TEXT NOT NULL,
  metadata JSONB DEFAULT '{}',
  embedding VECTOR(1536),  -- OpenAI text-embedding-3-small dimension
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- HNSW index for fast approximate nearest neighbor search
CREATE INDEX idx_documents_embedding_hnsw
ON documents
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

Semantic Search in Practice

Semantic search is the most common use case for pgvector. The flow is: 1) User enters a search query. 2) You generate an embedding for the query using an AI model. 3) You call a Postgres function that finds the most similar documents using vector similarity. 4) You return the results to the user. The match_documents function uses the <=> operator for cosine distance. It filters by a threshold to remove low-similarity matches and limits the results. The query is efficient even with millions of documents because of the HNSW index. You can also use semantic search for recommendation systems — find products similar to what a user viewed, or find related articles. The possibilities are endless. Semantic search often outperforms keyword search because it understands meaning, not just word matching.

TypeScript
// Edge Function: embed a query and find similar documents
import OpenAI from 'npm:openai';

const openai = new OpenAI({ apiKey: Deno.env.get('OPENAI_API_KEY') });

Deno.serve(async (req) => {
  const { query } = await req.json();
  const { data: [{ embedding }] } = await openai.embeddings.create({
    model: 'text-embedding-3-small',
    input: query,
  });
  const { data } = await supabase.rpc('match_documents', {
    query_embedding: embedding,
    match_threshold: 0.75,
    match_count: 5
  });
  return new Response(JSON.stringify(data));
});

Building a RAG Pipeline

RAG (Retrieval-Augmented Generation) is the pattern of combining semantic search with LLM generation. The flow: 1) Ingest — chunk your documents, generate embeddings, store them. 2) Retrieve — embed the user's question, find relevant chunks. 3) Augment — inject the retrieved chunks as context into your LLM prompt. 4) Generate — the LLM generates a grounded answer. This is the standard pattern for building question-answering systems over private data. The quality of the answer depends on the quality of the retrieval. pgvector provides the best-in-class retrieval for RAG. You can combine it with any LLM — OpenAI, Anthropic, Llama, or others. The result is a system that can answer questions about your data without hallucinating.

  1. Ingest: Chunk your documents, generate embeddings via OpenAI/Gemini, store in the documents table.
  2. Retrieve: Embed the user's question, run match_documents() to find relevant chunks.
  3. Augment: Inject retrieved chunks as context into your LLM prompt.
  4. Generate: LLM generates an answer grounded in your private data.

Distance Operators

<=> Cosine distance (best for normalized text embeddings). <-> L2/Euclidean distance. <#> Negative inner product (used for dot-product similarity). Always use the same distance type that your HNSW index was built with.

Knowledge Check

Ready to test your understanding of 12. pgvector: AI Embeddings & Semantic Search?

Back