Sub topic 1
Vector Similarity Search in PostgreSQL with pgvector
Prerequisites
This chapter assumes you know basic SQL (CREATE TABLE, INSERT, UPDATE, SELECT, WHERE, ORDER BY, LIMIT), that you have a PostgreSQL server and a client such as psql, and that you can run commands in a shell. You do not need machine learning experience.
What embeddings are and why similarity search needs a database
An embedding is a list of numbers that represents the meaning of a piece of data, such as a sentence or an image. Embedding models produce these lists so that similar items get similar numbers. Finding the stored items closest to a query embedding is called nearest-neighbor search. A database suits this work because the vectors sit next to your other data, so you can filter, join, and update them with ordinary SQL.
Choosing a distance metric: L2, cosine, and inner product
Three common ways to measure closeness are:
- L2 (Euclidean) distance: the straight-line distance between two points. Smaller means closer.
- Cosine distance: the angle between two vectors, ignoring their length. Smaller means closer.
- Inner product: the dot product of two vectors. Larger means closer. pgvector's
<#>operator returns the negative inner product so that smaller still means closer.
Match the metric to the one the embedding model was trained for. If the model documentation says its vectors are normalized to length 1, cosine and inner product produce the same ranking.
Enabling pgvector in a database
pgvector is an extension, which is an add-on package that adds new types and functions to PostgreSQL. Install the package on the server, then enable it in each database that needs it:
CREATE EXTENSION IF NOT EXISTS vector;Installing the package alone does not make the vector type available. You must run this statement in every database that uses it.
The vector type and fixed dimensions
The vector(n) type stores a vector with exactly n values, where n is the dimension of your embedding model. The dimension is part of the column definition:
CREATE TABLE items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3)
);The 3 keeps this example small. Real models often produce hundreds or thousands of dimensions.
> Not allowed: block quotes. Use this instead.
Inserting and updating vectors
Write a vector as a text value in square brackets, with values separated by commas:
INSERT INTO items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4,5,6]'),
('c', '[1,1,1]');
UPDATE items
SET embedding = '[2,2,2]'
WHERE content = 'c';An update replaces the whole vector. When the source text changes, recompute its embedding in your application and write the new value.
Exercise
Why does this statement fail on the items table defined with vector(3)? INSERT INTO items (content, embedding) VALUES ('d', '[1,2]');
Show answer
The vector has two values, but the column requires exactly three dimensions, so PostgreSQL rejects the row with a dimension mismatch error.