AI Hints
Home›PostgreSQL Tutorial›NOTIFY, Extensions and pgvector
PostgreSQL · Lesson 99 of 120

pgvector

Vectors in Postgres.

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

AI search works with embeddings, lists of numbers that capture meaning. The pgvector extension adds a vector column type, so embeddings live right next to your data.

  • Embeddings
  • vector type
  • Next to your data

A tiny vector table

Create extension vector turns it on. The embedding column holds three numbers, so we can read them. The arrow operator, less than equals greater than, gives cosine distance. Run it. The closest item to our search vector comes first.

query.sqlsql
CREATE EXTENSION vector;
CREATE TABLE items (name text, embedding vector(3));
INSERT INTO items VALUES ('rain jacket', '[0.9, 0.1, 0.2]'),
                         ('camp stove',  '[0.1, 0.8, 0.5]'),
                         ('umbrella',    '[0.8, 0.2, 0.1]');

SELECT name, round((embedding <=> '[1, 0, 0.1]')::numeric, 3) AS distance
FROM items ORDER BY distance;
Output
CREATE EXTENSION
CREATE TABLE
INSERT 0 3
    name     | distance
-------------+----------
 rain jacket |    0.013
 umbrella    |    0.030
 camp stove  |    0.843
(3 rows)
Also uses _empty
1

Distance operators

Arrow with equals is cosine distance, the usual choice for text. Arrow with minus is Euclidean distance. And arrow with hash is negative inner product. Smaller distance means more similar.

OperatorDistance
<=>cosine (text)
<->Euclidean (L2)
<#>negative inner product
Smaller= more similar

Summary

Pgvector adds a vector type and distance operators to Postgres. Next, real vector search over our books.

Key takeaways
  • vector(n)
  • <=>
  • Closest first
Next up: Vector Search — books by meaning