pgvector: PostgreSQL Vector Extension for AI Applications
pgvector brings vector similarity search directly into PostgreSQL. Store embeddings as a native column type, create HNSW or IVFFlat indexes for fast ANN search, and combine semantic search with SQL WHERE clauses, JOINs, and transactions — all in your existing database. No new infrastructure, no new operational burden.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →Installation & Schema Setup
Enable the extension, create a table with a vector column, and set up HNSW indexing.
-- Enable pgvector extension (requires superuser or rds_superuser on RDS)
CREATE EXTENSION IF NOT EXISTS vector;
-- Create a documents table with an embedding column
-- dimension must match your embedding model (OpenAI 3-small = 1536)
CREATE TABLE documents (
id BIGSERIAL PRIMARY KEY,
content TEXT NOT NULL,
category VARCHAR(64),
user_id BIGINT REFERENCES users(id),
created_at TIMESTAMPTZ DEFAULT NOW(),
embedding vector(1536) -- pgvector column type
);
-- Create HNSW index for fast approximate nearest neighbor search
-- HNSW is recommended over IVFFlat for most use cases (better recall, faster queries)
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- For L2 distance use: vector_l2_ops
-- For inner product use: vector_ip_ops
-- (Alternative) IVFFlat index — faster to build, lower memory, less accurate
-- lists = sqrt(row_count) is a good starting point
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100); Insert Embeddings & Run Similarity Search
Store OpenAI embeddings and query with cosine distance, combining with SQL filters.
import openai
import psycopg2
import json
oa = openai.OpenAI()
conn = psycopg2.connect("postgresql://user:pass@localhost/mydb")
cur = conn.cursor()
# Generate and store an embedding
def embed(text: str) -> list[float]:
return oa.embeddings.create(
model="text-embedding-3-small",
input=text
).data[0].embedding
docs = [
("RAG combines retrieval with LLM generation", "ai"),
("pgvector adds vector search to PostgreSQL", "database"),
("HNSW is the recommended ANN index type", "database"),
]
for content, category in docs:
emb = embed(content)
cur.execute(
"INSERT INTO documents (content, category, embedding) VALUES (%s, %s, %s)",
(content, category, json.dumps(emb)) # psycopg2 auto-converts list to vector
)
conn.commit()
# Similarity search with cosine distance (<=>)
query_emb = embed("how does retrieval augmented generation work")
cur.execute("""
SELECT content, category,
embedding <=> %s::vector AS distance
FROM documents
WHERE category = 'ai' -- SQL filter (pre-filter with HNSW iterative scan)
ORDER BY distance -- nearest first
LIMIT 5
""", (json.dumps(query_emb),))
for row in cur.fetchall():
print(f"dist={row[2]:.4f} | {row[0]}") Advanced: SQL JOINs, CTEs & Row-Level Security
pgvector's biggest advantage — combine vector similarity with full SQL capabilities.
-- JOIN vector search with user data (pgvector's killer feature)
SELECT
d.content,
u.name AS author,
d.created_at,
d.embedding <=> query.vec AS similarity_distance
FROM
documents d
JOIN users u ON d.user_id = u.id,
(SELECT %s::vector AS vec) query -- parameterized query vector
WHERE
d.created_at > NOW() - INTERVAL '30 days'
AND d.category IN ('ai', 'database')
ORDER BY
similarity_distance
LIMIT 10;
-- Row-Level Security for multi-tenant vector search
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON documents
USING (user_id = current_setting('app.user_id')::bigint);
-- Now every query automatically filters to current user's vectors
-- Perfect for SaaS applications with per-user document stores
-- Tune HNSW search precision vs. speed at query time
SET hnsw.ef_search = 100; -- default 40; higher = better recall, slower
-- Check index usage
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM documents
ORDER BY embedding <=> '[...]'::vector LIMIT 5; pgvector vs Dedicated Vector Databases
| Feature | pgvector | Pinecone | Qdrant | Weaviate |
|---|---|---|---|---|
| SQL JOINs | Yes (full SQL) | No | No | No |
| ACID transactions | Yes | No | No | No |
| Row-level security | Yes (Postgres RLS) | Namespaces | Payload filter | Multi-tenancy |
| Max practical scale | ~50M vectors | 100M+ | 100M+ | 100M+ |
| Hybrid search | Manual (FTS + vector) | Limited | Native sparse+dense | BM25 + vector |
| Ops overhead | Low (existing PG) | None (managed) | Low–medium | Low–medium |
| Best for | Existing PG users, SQL+vector | Managed prod | High perf self-host | Hybrid RAG, SaaS |
Frequently Asked Questions
What is pgvector and why use it?▼
pgvector is a PostgreSQL extension that adds a native vector column type and similarity search operators. It lets you store embeddings directly in your existing Postgres database alongside relational data, enabling vector search with full SQL — JOINs, WHERE filters, CTEs, transactions, and RLS (Row Level Security). If you already use PostgreSQL, pgvector is often the fastest path to production vector search.
What is the difference between IVFFlat and HNSW indexes in pgvector?▼
IVFFlat divides vectors into 'lists' (clusters) and searches only the nearest clusters. It has faster build time and lower memory use but requires lists to be set at creation. HNSW (added in pgvector 0.5.0) builds a navigable small world graph — it has better recall (higher accuracy), faster queries, but longer build time and higher memory usage. For most production use cases, HNSW is now the recommended choice.
What distance operators does pgvector support?▼
pgvector provides three operators: <-> for L2 (Euclidean) distance, <#> for negative inner product (use for cosine-normalized vectors or dot product similarity), and <=> for cosine distance. Cosine distance (<=> operator) is most commonly used for text embeddings from OpenAI, Cohere, etc. Your ORDER BY clause should use the same metric your embedding model was trained with.
How many vectors can pgvector handle?▼
pgvector handles millions of vectors well on adequate hardware. The main constraint is that HNSW indexes are loaded into shared_buffers memory during search. For 1M vectors at 1536 dims (float32), the raw data is ~6GB; the HNSW index adds ~2-3x on top. With proper Postgres tuning (work_mem, shared_buffers), 10-50M vectors are feasible on high-memory instances. For 100M+, dedicated vector databases (Qdrant, Milvus) become more cost-efficient.
Can I combine vector search with SQL filters in pgvector?▼
Yes — this is pgvector's primary advantage over dedicated vector databases. You can combine <-> / <=> with any SQL WHERE clause: filter by user_id, date range, status, and then rank by similarity. For best performance with HNSW, apply pre-filters using a WHERE clause rather than post-filtering results — pgvector's iterative index scan will traverse the HNSW graph while respecting your filter.
pgvector vs dedicated vector databases: when to choose each?▼
Choose pgvector when: you already use PostgreSQL, your vector count is under 10-50M, you need SQL JOINs between vectors and relational data, or you want a simpler stack. Choose a dedicated vector DB (Pinecone, Qdrant, Weaviate) when: you need billion-scale search, advanced hybrid search (sparse+dense), managed infrastructure with auto-scaling, or performance-critical low-latency at very high QPS.
Related Products
on GumroadAI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →AI Developer Prompts Pack
55 battle-tested prompt templates for the workflows developers actually use: code review, debugging, architecture, documentation, and testing. Stop writing prompts from scratch.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
CrewAI Agent Config Generator
Build CrewAI agent configurations visually. Define roles, goals, backstories, and tools. Generate YAML or Python code for multi-agent crews.
Open free tool →
Embedding Storage Calculator
Calculate storage requirements for vector embeddings at scale. Choose model, precision, and vector count to get RAM, disk, and Pinecone cost estimates.
Open free tool →
Test Coverage Calculator
Calculate line, branch, function, and statement code coverage percentages. Set thresholds, check pass/fail status, and generate Jest/Vitest coverage config snippets.
Open free tool →
More Free Tools
Related Articles
Vector Database Comparison 2026: Pinecone vs Weaviate vs Qdrant vs Chroma
In-depth comparison of the top vector databases in 2026. Evaluate Pinecone, Weaviate, Qdrant, and Chroma on performance, scalability, filtering, pricing, and self-hosting for production AI applications.
Vector Databases Explained: Pinecone vs Weaviate vs Qdrant vs Chroma (2026 Guide)
A complete comparison of the best vector databases in 2026: Pinecone, Weaviate, Qdrant, Chroma, and pgvector. Pricing, code examples, performance benchmarks, and a clear decision framework for AI and LLM applications.
Building a RAG Pipeline from Scratch: Embeddings, Vector Databases, and Retrieval
Step-by-step guide to building a production-ready RAG pipeline in Python. Covers embeddings, chunking strategies, Chroma and Pinecone setup, hybrid search, reranking, and evaluation with RAGAS.
Building Production RAG Systems with LlamaIndex and Vector Databases 2026
Complete guide to building production-ready RAG systems with LlamaIndex v0.10+. Covers chunking strategies, embedding models, Chroma, Pinecone, Weaviate integration, and advanced retrieval patterns.
Building a Production RAG Pipeline: Complete Implementation Guide 2026
A comprehensive guide to building production-ready RAG pipelines in 2026. Covers chunking strategies, embedding models, vector store selection, retrieval techniques, reranking, evaluation with RAGAS/TruLens, and LangChain vs LlamaIndex vs custom implementations.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →