pgvector

0.8.2 · active · verified Sat Feb 28

Open-source PostgreSQL extension for vector similarity search. Two components: (1) the server-side Postgres extension (C, compiled and installed into Postgres), and (2) the Python client package 'pgvector' on PyPI which provides ORM/adapter integrations for psycopg2, psycopg3, asyncpg, SQLAlchemy, Django, SQLModel, and Peewee. The extension name in SQL is 'vector' (CREATE EXTENSION vector), not 'pgvector'. Maintained by Andrew Kane. Current extension version: 0.8.2 (CVE security fix). Python client: 0.4.2.

Warnings

Install

Imports

Quickstart

register_vector(conn) must be called after connecting — it registers the custom 'vector' type with psycopg2. Without it, vectors are returned as strings. Extension must be enabled server-side first with CREATE EXTENSION vector.

# Step 1: Enable extension in Postgres (run once per database)
# CREATE EXTENSION IF NOT EXISTS vector;

import psycopg2
from pgvector.psycopg2 import register_vector
import numpy as np

conn = psycopg2.connect("dbname=mydb user=postgres")
register_vector(conn)  # REQUIRED: registers the vector type

cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS items (id bigserial PRIMARY KEY, embedding vector(3))")

# Insert vectors
cur.execute("INSERT INTO items (embedding) VALUES (%s)", (np.array([1.0, 2.0, 3.0], dtype='float32'),))
conn.commit()

# L2 distance search (<->)
cur.execute("SELECT id FROM items ORDER BY embedding <-> %s LIMIT 5", (np.array([1.0, 1.0, 1.0], dtype='float32'),))
print(cur.fetchall())

cur.close()
conn.close()

view raw JSON →