Velamuvi AIAcademy

Lesson 6 of 9 · Tools

pgvector With PostgreSQL

Add vector search to PostgreSQL with pgvector: a vector column, embeddings, nearest neighbours with <=> and <->, SQL filters, HNSW indexes and Python queries.

  • 8 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Enable pgvector and store embeddings in a vector column
  • Find nearest neighbours with the cosine, Euclidean and inner product operators
  • Combine vector search with ordinary SQL filters and joins
  • Build an HNSW or IVFFlat index and query it from Python

Vector search in the database you already have

If your app already uses PostgreSQL, pgvector is often the simplest choice: one database to back up, secure and run, and you can filter and join vectors with normal SQL. Many hosted PostgreSQL services include it; on your own server, it is installed as a package and then enabled per database.

The SQL below runs on PostgreSQL with pgvector, not in this page, so it is shown without a Run button. The outputs come from a real run.

Create a table with a vector column

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE articles (
    id        bigserial PRIMARY KEY,
    title     text NOT NULL,
    category  text,
    embedding vector(3)          -- the number is the embedding size, e.g. vector(1536)
);

INSERT INTO articles (title, category, embedding) VALUES
    ('Booking cheap flights',  'travel', '[0.9, 0.1, 0.0]'),
    ('Easy pasta recipes',     'food',   '[0.1, 0.9, 0.1]'),
    ('Fixing a slow laptop',   'tech',   '[0.0, 0.1, 0.9]'),
    ('Street food in Bangkok', 'travel', '[0.7, 0.6, 0.0]');

Vectors are written as text in square brackets. The column size is enforced: inserting a vector with the wrong number of values fails.

Find nearest neighbours

pgvector adds distance operators. Sort by one of them and take the first rows:

SELECT title, embedding <=> '[0.6, 0.8, 0.0]' AS distance
FROM articles
ORDER BY embedding <=> '[0.6, 0.8, 0.0]'
LIMIT 3;

With the distances rounded to three decimal places, the result is:

Output
         title          | distance
------------------------+----------
 Street food in Bangkok |    0.024
 Easy pasta recipes     |    0.144
 Booking cheap flights  |    0.315
OperatorMeaningIndex operator class
<=>Cosine distance (1 − cosine similarity)vector_cosine_ops
<->Euclidean (L2) distancevector_l2_ops
<#>Negative inner product (so that smaller = more similar)vector_ip_ops

All three return a distance, so you always sort ascending. Here is exactly what they compute, in Python, for the same data:

Try it yourselfPython
import math

# What pgvector's three main operators compute, written out in Python.
def l2_distance(a, b):            # a <-> b
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

def negative_inner_product(a, b): # a <#> b  (negative, so that smaller = more similar)
    return -sum(x * y for x, y in zip(a, b))

def cosine_distance(a, b):        # a <=> b  (1 - cosine similarity)
    dot = sum(x * y for x, y in zip(a, b))
    return 1 - dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

articles = {
    "Booking cheap flights":  [0.9, 0.1, 0.0],
    "Easy pasta recipes":     [0.1, 0.9, 0.1],
    "Fixing a slow laptop":   [0.0, 0.1, 0.9],
    "Street food in Bangkok": [0.7, 0.6, 0.0],
}
query = [0.6, 0.8, 0.0]

# ORDER BY embedding <=> query LIMIT 3
ranked = sorted(articles, key=lambda title: cosine_distance(articles[title], query))
for title in ranked[:3]:
    v = articles[title]
    print(f"{title:<23} <=> {cosine_distance(v, query):.3f}   <-> {l2_distance(v, query):.3f}   <#> {negative_inner_product(v, query):.2f}")

The cosine distances match PostgreSQL's output.

Filters are just SQL

Because the vectors live in a normal table, filtering is an ordinary WHERE clause, and you can join to other tables (users, permissions, products) in the same query:

SELECT title, 1 - (embedding <=> '[0.6, 0.8, 0.0]') AS similarity
FROM articles
WHERE category = 'travel'
ORDER BY embedding <=> '[0.6, 0.8, 0.0]'
LIMIT 3;

Only two travel articles exist, so only two rows come back (rounded):

Output
         title          | similarity
------------------------+------------
 Street food in Bangkok |      0.976
 Booking cheap flights  |      0.685

Add an index

Without an index, PostgreSQL compares the query with every row: exact, and fine for tens of thousands of rows. For more, add an approximate index:

-- HNSW: the usual choice. Can be created on an empty table.
CREATE INDEX ON articles USING hnsw (embedding vector_cosine_ops);
SET hnsw.ef_search = 100;        -- more candidates = higher recall (default 40)

-- IVFFlat: smaller and faster to build. Create it AFTER loading data.
CREATE INDEX ON articles USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
SET ivfflat.probes = 10;         -- lists searched per query (default 1)

The operator class must match the operator you sort by: a vector_cosine_ops index is only used for ORDER BY embedding <=> ....

From Python

With the psycopg driver and the pgvector helper package (pip install "psycopg[binary]" pgvector numpy), vectors are passed as query parameters, never pasted into the SQL string:

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

conn = psycopg.connect("dbname=app user=app", autocommit=True)
register_vector(conn)                       # teach psycopg about the vector type

query_vector = np.array([0.6, 0.8, 0.0])    # in a real app: from your embedding model
rows = conn.execute(
    """
    SELECT title, 1 - (embedding <=> %s) AS similarity
    FROM articles
    WHERE category = %s
    ORDER BY embedding <=> %s
    LIMIT 3
    """,
    (query_vector, "travel", query_vector),
).fetchall()

for title, similarity in rows:
    print(f"{similarity:.2f}  {title}")
Output
0.98  Street food in Bangkok
0.68  Booking cheap flights

Common mistakes

Practice exercise

Without the pgvector Python package, vectors travel to and from PostgreSQL as text. Write both conversions.

Your solutionPython
vector = [0.6, 0.8, 0.0]
from_database = "[0.25,0.5,1]"

# 1. Turn the Python list into pgvector's text format: [0.6,0.8,0.0]
# 2. Turn the text from the database back into a list of floats
Knowledge check

Which pgvector operator gives cosine distance?

Summary

  • pgvector adds a vector(n) column type, distance operators and vector indexes to PostgreSQL.
  • <=> is cosine distance, <-> is Euclidean, <#> is negative inner product; sort ascending.
  • Filters and joins are ordinary SQL, so vectors sit next to the rest of your data.
  • Use an HNSW index (tune hnsw.ef_search) or IVFFlat (build after loading, tune ivfflat.probes), with the operator class matching your operator.

Next: two popular dedicated vector databases, Pinecone and Qdrant.

Finished reading? Tick it off to track your progress.