N
NexusDigitalLabs
← Back to Academy

Phase 3 — Core AI Engineering · Lesson 28 · 20 XP

Vector search with pgvector

pgvector adds a vector column type to Postgres, so embeddings live right alongside your other data — no separate database to run and keep in sync. Searching means embedding the query the same way you embedded your documents, then ordering by vector distance.

CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE docs (id serial PRIMARY KEY, content text, embedding vector(1536));

SELECT content FROM docs ORDER BY embedding <=> $1 LIMIT 5;  -- $1 = the query's embedding

The <=> operator computes cosine distance between the stored vector and your query vector — smaller means more similar. An approximate index (ivfflat or hnsw) makes this fast on large tables by trading a small amount of accuracy for a large speedup; for search, that tradeoff is almost always worth it, since the difference between the true 5th-best and 6th-best result rarely matters.

Exercise

Store embeddings for a handful of documents in a pgvector column, then run a nearest-neighbor query for a new query embedding and confirm the top results are the ones you'd expect.

Check yourself

1. What does the <=> operator represent in a pgvector query?

2. Why does an approximate nearest-neighbor index trade some accuracy for speed, and why is that usually fine for search?

← Previous lesson

Embeddings

Answer the check-yourself questions to unlock this