AI Hints
Home›PostgreSQL Tutorial›Vector Search in Postgres
PostgreSQL · Lesson 100 of 120

Vector Search

Books by meaning.

⏱ 2 min read▶ Video at 1:30:16🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A shopper asks for something cosy to read on a rainy evening. No blurb has those words. Embed every blurb, embed the question, and find the closest books by meaning.

  • 'cosy rainy evening'
  • No matching words
  • Closest by meaning

We embed every blurb, and store each vector in the embedding column. Then we embed the question, and order books by cosine distance to it. Run it. A love story, a calm cookbook, and an overnight train, all about cosy moods.

vector_search.pypython
import psycopg
from sentence_transformers import SentenceTransformer

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
model = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
conn = psycopg.connect(URL)

books = conn.execute("SELECT book_id, blurb FROM books").fetchall()
for (book_id, blurb), vec in zip(books, model.encode([b for _, b in books])):
    conn.execute("UPDATE books SET embedding = %s WHERE book_id = %s", (str(vec.tolist()), book_id))

q = str(model.encode("something cosy to read on a rainy evening").tolist())
for (title,) in conn.execute(
        "SELECT title FROM books ORDER BY embedding <=> %s LIMIT 3", (q,)):
    print(title)
Output
Letters to Lisbon
The Quiet Kitchen
Night Train to Oslo
Also uses _setup.sql
CREATE EXTENSION vector;
ALTER TABLE books ADD COLUMN embedding vector(384);

How it fits

The embedding model runs in your app, or a service. Vectors are stored in Postgres, beside the rows. Search is just order by distance, with a limit. And you can join, filter and paginate like any query.

keyvalue
Modelin your app
Vectorsin Postgres
SearchORDER BY <=>
SQLjoins, filters

Summary

Store embeddings in a vector column, and order by distance to search by meaning. Next, vector indexes for speed.

Key takeaways
  • Embed
  • Store
  • ORDER BY <=>
Next up: Vector Indexes — fast nearest neighbours