PGVector教程:30分钟给PostgreSQL加AI搜索
你已经在用PostgreSQL——加向量搜索可以保持技术栈简单。
PGVector Tutorial 2026: Add AI Search to PostgreSQL in 30 Minutes
PGVector is the PostgreSQL extension that adds vector storage and similarity search to your existing database. At 22,400 GitHub stars, it is the most popular way to add semantic search without introducing a separate vector database. If you already run Postgres, this tutorial gets you a working RAG search in half an hour.
Why PGVector Instead of a New Database
| Factor | PGVector | Dedicated vector DB |
|---|---|---|
| Setup | 1 command | New service to run |
| Data consistency | Same DB as your data | Sync needed |
| Transactions | Full ACID | Varies |
| Scale | Great to ~1M vectors | Better at 100M+ |
| You already run Postgres | Free | Extra cost |
Step 1: Install the Extension
CREATE EXTENSION IF NOT EXISTS vector;
On Ubuntu: apt install postgresql-16-pgvector. On Mac: brew install pgvector.
Step 2: Create a Table
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
content TEXT,
embedding vector(768)
);
The 768 dimension must match your embedding model (bge-m3 uses 1024; nomic-embed-text uses 768).
Step 3: Insert Embeddings (Python)
import psycopg2
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
vec = client.embeddings.create(model="nomic-embed-text", input="your text").data[0].embedding
conn = psycopg2.connect("dbname=app")
conn.execute(
"INSERT INTO documents (content, embedding) VALUES (%s, %s)",
("your text", vec)
)
Step 4: Search
SELECT content, 1 - (embedding <=> query_embedding) AS similarity
FROM documents
ORDER BY embedding <=> query_embedding
LIMIT 5;
The <=> operator is cosine distance. Lower = more similar.
Step 5: Add an Index (required at scale)
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
HNSW indexes make search milliseconds instead of seconds once you pass ~10K rows.
FAQ
PGVector vs dedicated vector DBs? PGVector wins on simplicity and consistency for most apps under ~10M vectors. Chroma (28,900 stars), Qdrant (33,700), and Milvus (45,400) win at massive scale or when you want a purpose-built store.
Does it work with LangChain? Yes - langchain-postgres has a PGVector vectorstore class.
HNSW or IVFFlat index? HNSW - better accuracy and no tuning needed. IVFFlat is legacy.
