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.
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.
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
What does <#> return, and why?
What must match for an index to be used by a query?
Why can a filter plus an approximate index return fewer rows than the LIMIT?
When is a plain pgvector table with no index the right choice?
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