Data for AI & Analytics

PostgreSQL Vector Database with pgvector (2026)

Turn PostgreSQL into a production vector database — pgvector setup, HNSW indexing, RAG architecture, and comparisons to Pinecone and Weaviate.
April 23, 2026
PostgreSQL Vector Database with pgvector (2026)
ByRajnikant Rakesh
8 min read
TL;DR
  • pgvector is a PostgreSQL extension that adds a native vector data type, similarity search operators, and HNSW or IVFFlat index support for AI workloads.
  • HNSW indexing enables approximate nearest neighbor search across millions of vectors using cosine distance, L2 distance, or inner product operators.
  • pgvector inherits PostgreSQL's ACID compliance, access control, and backup capabilities, eliminating the need for a separate vector database system.
  • Common use cases include RAG applications, semantic search, recommendation systems, image similarity search, and anomaly detection.
  • Choose pgvector over dedicated vector databases for workloads under 50 million vectors where operational simplicity and SQL compatibility are priorities.

PostgreSQL becomes a vector database by installing the pgvector extension, which adds a native vector data type, similarity search operators, and index support directly within PostgreSQL tables. This allows developers to store vector embeddings alongside relational data, run nearest neighbor queries using SQL, and build AI applications without introducing a separate database system.


This guide covers how pgvector works, how to set it up for production use, how to build a RAG (Retrieval Augmented Generation) application, and how pgvector compares to dedicated vector databases like Pinecone and Weaviate. All code examples use Python with OpenAI embeddings and PostgreSQL with pgvector.

What Is a PostgreSQL Vector Database?

A PostgreSQL vector database is a standard PostgreSQL instance with the pgvector extension installed, enabling it to store, index, and query high-dimensional vector embeddings using familiar SQL syntax. pgvector adds a vector column type that stores numerical arrays representing the semantic meaning of text, images, or other data. Developers can then perform similarity searches to find the closest matching vectors using cosine distance, L2 (Euclidean) distance, or inner product operators.


The primary advantage of using PostgreSQL as a vector database is operational simplicity. Teams already running PostgreSQL do not need to provision, learn, or maintain a separate vector database. pgvector inherits PostgreSQL's ACID compliance, backup and recovery capabilities, access control, and ecosystem integrations. For most enterprise RAG workloads with fewer than 50 million vectors, pgvector with HNSW indexing delivers production-grade performance.

How pgvector Works

Understanding how pgvector works under the hood helps you make better decisions about distance metrics, indexing strategies, and query performance. This section covers the two foundational concepts: how vector embeddings enable similarity search, and how pgvector's index types (HNSW and IVFFlat) make that search fast at scale.

Vector embeddings are numerical representations of semantic meaning. An embedding model (such as OpenAI's text-embedding-3-small) converts text, images, or other data into fixed-length arrays of floating-point numbers. Semantically similar content produces vectors that are close together in high-dimensional space. Similarity search finds the nearest neighbors to a query vector, retrieving the most semantically relevant results.


pgvector supports three distance metrics for similarity search:

MetricOperatorBest ForNotes
Cosine<=>Text embeddings (most common)Normalized; measures angle between vectors
L2 (Euclidean)<->Image embeddings, spatial dataMeasures absolute distance
Inner Product<#>Pre-normalized vectorsFastest; requires unit vectors

HNSW vs IVFFlat Index Types

pgvector supports two approximate nearest neighbor (ANN) index types. Without an index, pgvector performs exact (brute-force) search, which provides perfect recall but becomes impractical beyond a few hundred thousand vectors.

FeatureHNSWIVFFlat
Search SpeedFaster at query timeSlightly slower
RecallHigher (better accuracy)Lower (depends on nprobe)
Build TimeSlower (graph construction)Faster (centroid clustering)
MemoryHigherLower
Best ForProduction RAG, real-time searchBatch workloads, memory-constrained
RecommendationDefault for most workloadsUse when build speed is critical

HNSW is the recommended index for production LLM workloads. pgvector 0.8.x introduced iterative scan (hnsw.iterative_scan), which improves recall by rescanning the index graph when initial results are insufficient.

Architecture: Building a RAG App with PostgreSQL and pgvector

The Three Components of a pgvector RAG System

Retrieval Augmented Generation (RAG) is a pattern that enhances LLM responses by providing relevant context retrieved from a knowledge base. Instead of relying solely on the LLM's training data, RAG retrieves the most relevant documents from a vector database and includes them in the prompt, enabling the model to answer questions about private, domain-specific, or recent information.


A pgvector RAG system consists of three components:


  • Generate embeddings: Convert source documents (PDFs, web pages, internal docs) into vector embeddings using an embedding model (OpenAI text-embedding-3-small, Cohere, or open-source alternatives). Chunk documents into sections of 500-1000 tokens before embedding.

  • Store in pgvector: Insert the embeddings into a PostgreSQL table with a vector column, alongside the original text and any metadata (source, date, category). Create an HNSW index on the vector column.

  • Retrieve for RAG: When a user asks a question, embed the query, run a similarity search against the vector table to find the top-k most relevant chunks, and pass them as context to the LLM for answer generation.

LangChain and LlamaIndex are common orchestration libraries that automate this pipeline. Both support pgvector as a vector store backend. Tessell for PostgreSQL works with both libraries.

Setting Up pgvector on PostgreSQL

Before writing any code, you need a running PostgreSQL instance with pgvector enabled. There are two paths to get there: installing and managing everything yourself, or using a managed DBaaS that handles provisioning and extension setup automatically. The right choice depends on your team's operational capacity and production requirements.

Self-Managed vs Managed PostgreSQL for pgvector

There are two paths to running pgvector:


  • Self-managed: Install PostgreSQL, compile and install the pgvector extension manually, configure indexing parameters, and manage backups and scaling yourself. This works for development but adds operational overhead in production.

  • Managed DBaaS: Use a managed PostgreSQL service that provisions pgvector as a first-class integration. Tessell for PostgreSQL provisions pgvector-ready databases on AWS and Azure from a single control plane, with no manual extension installation. NVMe-backed storage delivers the low-latency I/O that vector search requires at scale.

Python Environment Setup

Install the required Python packages:


pip install openai psycopg2-binary pandas tiktoken


For LangChain users, install langchain-postgres (requires psycopg3):


pip install langchain langchain-postgres psycopg


Set your OpenAI API key as an environment variable and configure your PostgreSQL connection string pointing to your Tessell instance or self-managed database.

Storing Vector Embeddings in PostgreSQL with pgvector

Create a PostgreSQL Database and Install pgvector

Connect to your PostgreSQL instance and enable the pgvector extension:


CREATE EXTENSION IF NOT EXISTS vector;


On Tessell for PostgreSQL, pgvector is pre-installed. The CREATE EXTENSION command is a one-time activation step.

Create the Vector Table and Ingest Data

Create a table with a vector column sized to match your embedding model's dimensions. OpenAI text-embedding-3-small produces 1536-dimensional vectors:


CREATE TABLE documents (


id SERIAL PRIMARY KEY,


content TEXT NOT NULL,


metadata JSONB,


embedding vector(1536)


);


Generate embeddings using the OpenAI API and insert them into the table using psycopg2 or your preferred PostgreSQL client. For bulk inserts, use the COPY command or batch INSERT statements for best performance.

Add an HNSW Index for Production Performance

Without an index, similarity search performs a full table scan. For production workloads, create an HNSW index:


CREATE INDEX ON documents


USING hnsw (embedding vector_cosine_ops)


WITH (m = 16, ef_construction = 200);


Parameter guidance: m controls the number of connections per node (higher = better recall, more memory). ef_construction controls index build quality (higher = better recall, slower build). The defaults (m=16, ef_construction=64) work for most workloads under 10 million vectors. For larger datasets, increase ef_construction to 200. Set maintenance_work_mem to at least 1GB before building the index on large tables.

Similarity Search and RAG Retrieval with pgvector

Query the vector table to find the most similar documents to a user's question:


SELECT content, 1 - (embedding <=> query_embedding) AS similarity


FROM documents


ORDER BY embedding <=> query_embedding


LIMIT 5;


Pass the retrieved content as context to the LLM along with the user's question. The LLM generates an answer grounded in the retrieved documents rather than relying solely on its training data.

Pure vector search finds semantically similar content but may miss exact keyword matches. Hybrid search combines pgvector similarity search with PostgreSQL's native full-text search (tsvector) to capture both semantic and lexical relevance. This is a 2025-2026 production best practice for RAG applications.


SELECT content,


(1 - (embedding <=> query_embedding)) * 0.7 +


ts_rank(to_tsvector('english', content),


plainto_tsquery('english', 'search terms')) * 0.3


AS combined_score


FROM documents


ORDER BY combined_score DESC


LIMIT 5;


The weighting (0.7 vector / 0.3 keyword) can be tuned based on your use case. Tessell for PostgreSQL supports both query types with no additional configuration.

pgvector vs Dedicated Vector Databases

Choosing between pgvector and a dedicated vector database depends on your scale, operational requirements, and existing infrastructure.

CriteriapgvectorPineconeWeaviate
Best ForTeams already on PostgreSQL, <50M vectorsFully managed vector-only, any scaleMulti-modal search, GraphQL API
Scale LimitPractical to ~50M vectors per tableBillions (managed sharding)Hundreds of millions
Ops OverheadLow (if already on PostgreSQL)None (fully managed SaaS)Moderate (self-hosted or cloud)
ACID ComplianceFull PostgreSQL ACIDEventual consistencyEventual consistency
Cost ModelPostgreSQL instance costPer-vector pricingInfrastructure or SaaS

For most enterprise RAG workloads with fewer than 50 million vectors, pgvector with HNSW indexing delivers production-grade performance, especially when managed via Tessell with NVMe-backed storage and enterprise security (BYOA, zero RPO/RTO).

pgvector Use Cases Beyond RAG

  • Semantic search: Search knowledge bases, documentation, and support tickets by meaning rather than keywords. Users find relevant results even when their query uses different terminology than the source content.

  • Recommendation systems: Store user preference vectors and product/content embeddings in the same PostgreSQL database. Query for the nearest products to a user's preference vector to generate personalized recommendations.

  • Image and multi-modal similarity: Store CLIP or other multi-modal embeddings to enable image-to-image or text-to-image search. E-commerce platforms use this for visual product search.

  • Anomaly detection: Embed normal system behavior patterns as vectors. New observations that are distant from the normal cluster in vector space indicate potential anomalies or security threats.

  • Duplicate detection: Identify near-duplicate documents, support tickets, or records by finding vectors with high cosine similarity. Useful for data deduplication and content moderation.

Conclusion

PostgreSQL with pgvector is the most practical path to a production vector database for teams already invested in the PostgreSQL ecosystem. It eliminates the operational complexity of running a separate vector database while delivering ACID compliance, familiar SQL syntax, and production-grade similarity search with HNSW indexing.


For enterprise teams building RAG applications, semantic search, or recommendation systems, Tessell for PostgreSQL provisions pgvector-ready databases on AWS and Azure with NVMe-backed performance, enterprise security (BYOA), and zero RPO/RTO. No manual extension installation, no infrastructure management. Start a free trial at tessell.com or book a demo to evaluate pgvector on Tessell.

FAQs
A PostgreSQL vector database is a standard PostgreSQL instance with the pgvector extension enabled. pgvector adds a vector data type, similarity search operators (cosine, L2, inner product), and index support (HNSW, IVFFlat), allowing developers to store and query vector embeddings using SQL.
Install langchain-postgres (pip install langchain-postgres) and configure PGVector as your vector store with your PostgreSQL connection string. LangChain handles embedding generation, storage, and retrieval automatically. Tessell for PostgreSQL works with LangChain without additional setup.
HNSW builds a hierarchical navigable small world graph that provides faster queries and higher recall. IVFFlat clusters vectors into cells and searches nearby cells, offering faster index builds but lower recall. HNSW is recommended for production RAG workloads; IVFFlat suits batch workloads where build speed is the priority.
Yes, for most enterprise workloads with fewer than 50 million vectors. pgvector with HNSW indexing delivers sub-10ms query latency at this scale. For workloads exceeding 100 million vectors requiring ultra-low latency, a dedicated vector database may be more appropriate.
pgvector runs inside PostgreSQL, providing ACID compliance, SQL access, and no additional infrastructure. Pinecone is a fully managed vector-only SaaS with built-in sharding for billion-scale workloads. Choose pgvector if you are already on PostgreSQL and have fewer than 50M vectors; choose Pinecone for massive scale with no ops overhead.
Yes. Tessell for PostgreSQL provisions pgvector as a first-class integration on AWS and Azure. AWS RDS for PostgreSQL, Azure Database for PostgreSQL, and Google Cloud SQL for PostgreSQL also support pgvector. Tessell is the only managed service that provides pgvector on both AWS and Azure from a single control plane.
pgvector supports vectors with up to 2,000 dimensions by default. This covers all major embedding models including OpenAI text-embedding-3-small (1536 dimensions) and text-embedding-3-large (3072 dimensions, requires recompiling pgvector with a higher VECTOR_MAX_DIM). Most production workloads use 1536 or fewer dimensions.
Related Blogs