4 Hours

16. AI Foundations: pgvector & Semantic Search

Next-Gen AI

Postgres as a Vector Engine

The AI revolution has introduced a new type of data: Embeddings. These are lists of numbers (vectors) that represent the meaning of text or images. pgvector allows you to store these vectors in Postgres and find similar data using advanced mathematics. This is the foundation of RAG (Retrieval-Augmented Generation).

Why Vector Search?

Traditional search looks for keywords. If you search Pupny, a keyword search might fail. A vector search understands that Pupny (typo for Puppy) is conceptually similar to Dog because their vectors are physically close in multi-dimensional space.

SQL
-- Enabling the vector extension
CREATE EXTENSION vector;

-- Storing OpenAI embeddings (1536 dimensions)
CREATE TABLE documents (
  id SERIAL PRIMARY KEY,
  content TEXT,
  embedding VECTOR(1536)
);

Distance Metrics

To find Similar data, we measure the distance between vectors. pgvector supports three main methods:

  • Cosine Distance (<=>): Most common for text. Measures the Angle between vectors. Ignores the magnitude of the text.
  • L2 Distance (<->): Euclidean distance. Standard Straight line distance.
  • Inner Product (<#>): Used for certain recommendation models.

Performance: HNSW Indexes

Comparing your search vector against 1 million rows one-by-one is slow. Senior engineers use the HNSW (Hierarchical Navigable Small World) index. It builds a graph of your data, allowing for lightning-fast Approximate Nearest Neighbor search.

Knowledge Check

Ready to test your understanding of 16. AI Foundations: pgvector & Semantic Search?

Back