Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.2 — PostgreSQL with pgvector
RAG and Vector Search · Example 1 of 1

pgvector's operators on tiny vectors

These are the formulas pgvector evaluates, written by hand on 2-D vectors so you can check them. The operator names in the labels are pgvector's.

pgvector adds a vector column type, three distance operators and two index types to PostgreSQL, so embeddings live in a normal table next to your other data and a search is an ordinary SQL query.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write the cosine similarity of vectors [1, 2] and [2, 1] in Python and print it with 4 decimals, then the same value through the formula 1 - cosine distance.

02

Write a function to_pg(v) that turns a list of floats into the text form [0.1,0.2,0.3] (no spaces) that pgvector accepts. Print it for [0.5, -0.25, 1.0].

Explain it without notes

01

What does <#> return, and why?

02

What must match for an index to be used by a query?

03

Why can a filter plus an approximate index return fewer rows than the LIMIT?

04

When is a plain pgvector table with no index the right choice?

pgvector's operators on tiny vectors
Sign in to run this example in your browser.

Expected output

raw vectors (different lengths)
<->  L2 distance        B=1.0000  A=2.0000  D=2.0000  C=3.1623
<#>  negative inner     A=-3.0000  B=-1.0000  C=0.0000  D=1.0000
<=>  cosine distance    A=0.0000  B=0.2929  C=1.0000  D=2.0000
after scaling every vector to length 1
<->  L2 distance        A=0.0000  B=0.7654  C=1.4142  D=2.0000
<#>  negative inner     A=-1.0000  B=-0.7071  C=0.0000  D=1.0000
<=>  cosine distance    A=0.0000  B=0.2929  C=1.0000  D=2.0000
similarity of B = 1 - distance = 0.7071