Lesson 1 of 4 Vector Search and RAG with PostgreSQL

Understanding pgvector

This lesson explains how to enable pgvector on flexible server, its vector types and distance operators, and how an exact similarity query works.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the steps to enable pgvector.
  • Compare vector, halfvec, sparsevec and bit types.
  • Distinguish the distance operators.
  • Explain why an operator must match the index operator class.

Enabling pgvector

pgvector is an open-source PostgreSQL extension that adds a vector data type, distance functions and approximate nearest neighbour indexes. On Azure Database for PostgreSQL flexible server it is supported but must be enabled in two steps: allow-list it by adding vector to the azure.extensions server parameter, then run CREATE EXTENSION vector; in each database that uses it. The extension's version can be checked with SELECT extversion FROM pg_extension WHERE extname = 'vector';, which matters because some features, such as iterative index scans, need recent versions.

Once enabled, embeddings are stored in ordinary tables next to the relational data they describe, and every capability of PostgreSQL, such as joins, transactions, constraints, row-level security and full-text search, works alongside vector search.

Put in order

Enabling pgvector

Exam skills 2.2.5

Put the steps for using pgvector on a new flexible server in order.

Log in to try this activity Interactive activities are free with an account.

Vector types

pgvector provides several types for different precisions and densities. The dimension is declared in the column type, such as vector(1536), and every value must have exactly that many elements.

TypeElementIndexable dimensions (HNSW, IVFFlat)Typical use
vector(n)32-bit floatUp to 2,000Most embedding models, such as 1,536-dimension text embeddings
halfvec(n)16-bit floatUp to 4,000Halving storage and index size, or indexing 3,072-dimension embeddings
sparsevec(n)Non-zero elements onlyUp to 1,000 non-zero elementsSparse embeddings from keyword-style models
bit(n)Single bitsUp to 64,000Binary quantization for fast pre-filtering

A column can store vectors with more dimensions than an index supports, but it then cannot be indexed with HNSW or IVFFlat. A 3,072-dimension embedding from text-embedding-3-large therefore needs halfvec, a shorter output from the model's dimensions parameter, or another index method.

Scenario questions

Which vector type?

Exam skills 2.2.5 · 2.2.2

Choose the pgvector type for each requirement.

Log in to try this activity Interactive activities are free with an account.

Distance operators

pgvector compares vectors with operators, each corresponding to a distance metric. All of them return a distance, so smaller means more similar, and similarity queries sort in ascending order.

  • <-> returns Euclidean (L2) distance.
  • <=> returns cosine distance, which is 1 minus cosine similarity.
  • <#> returns the negative inner product; it is negated so that ascending order still puts the most similar first.
  • <+> returns L1 (taxicab) distance; <~> and <%> return Hamming and Jaccard distance for bit vectors.

For normalized embeddings such as Azure OpenAI's, cosine distance and negative inner product give the same ordering, and inner product is slightly cheaper to compute. To display a similarity score, compute 1 - (embedding <=> query). Functions such as cosine_distance(), l2_distance(), vector_dims() and l2_normalize() provide the same calculations by name.

The following diagram compares mismatched and matched definitions of an HNSW index and a vector query.

Why the HNSW index was ignored. The index was built with vector_l2_ops for L2 distance, but the query orders by the cosine operator <=>, so PostgreSQL can only scan the table. Building the index with vector_cosine_ops makes the operator and the operator class match, and the plan becomes an index scan.
An index serves a query only when the query's operator matches the index's operator class.
Match the pairs

pgvector operators

Exam skills 2.2.5

Match each pgvector operator with the distance it returns.

Log in to try this activity Interactive activities are free with an account.

Storing and searching

Embeddings are inserted like any other value; the pgvector Python package adapts lists and NumPy arrays for psycopg. A similarity search orders rows by distance to the query embedding and limits the number returned. Without an index, PostgreSQL computes the distance for every row, which is an exact search with perfect recall; the planner can parallelize it across workers.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE faq (
    id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    question  text NOT NULL,
    answer    text NOT NULL,
    embedding vector(1536) NOT NULL
);

SELECT id, question, 1 - (embedding <=> %(q)s) AS similarity
FROM faq
ORDER BY embedding <=> %(q)s
LIMIT 5;

The query passes the question's embedding as a parameter, %(q)s in psycopg's named style, so the same vector is used in the projection and the sort. Exact search is acceptable up to tens of thousands of rows or when a selective filter narrows the candidates; beyond that, an approximate index, covered in the next topic, keeps latency low.

True or false

Searching without an index

Exam skills 2.2.5

Decide whether each statement about pgvector similarity search is true.

Log in to try this activity Interactive activities are free with an account.
Worked example

An operator that ignores the index

A developer builds an HNSW index with vector_l2_ops on a 2-million-row table, then runs ORDER BY embedding <=> %s LIMIT 10. EXPLAIN shows a parallel sequential scan, and each query takes several seconds.

An index is built for one distance metric through its operator class, and the query uses the cosine operator <=> while the index was built for L2 distance. PostgreSQL can use the index only when the query's operator matches. The developer should create the index with vector_cosine_ops (or change the query to <-> if L2 is intended). With matching operator and operator class, EXPLAIN shows an index scan and latency drops to milliseconds.

Running ANALYZE would refresh statistics but not make a mismatched index usable. Raising hnsw.ef_search changes recall, not whether the index is chosen. Adding more vCores would only make the sequential scan somewhat faster.

Check yourself

Why does pgvector's inner product operator <#> return a negative value?

Show answer

So that, like the other operators, smaller means more similar, and similarity queries can always sort in ascending order.

Exam Tips

Remember for the exam

  • Allow-list vector in azure.extensions, then CREATE EXTENSION vector in each database.
  • vector indexes support up to 2,000 dimensions; halfvec up to 4,000.
  • <-> is L2, <=> is cosine distance, <#> is negative inner product; smaller means more similar.
  • Without an index, a vector query is an exact sequential scan.