Vectors

Draft

Vector search stores meaning as numbers and ranks rows by distance. Real apps often use pgvector; this lesson uses arrays to show the core idea.

Nearest vector

This uses arrays to show the same idea: nearest embeddings sort first.

Loaded Database:vectors.database-init
SELECT title
FROM documents
ORDER BY
  power(embedding[1] - 0.85, 2) +
  power(embedding[2] - 0.15, 2) +
  power(embedding[3] - 0.20, 2)
LIMIT 2;
Loading plan...

Show distance

The smaller the distance score, the more similar the document is to the query vector.

Loaded Database:vectors.database-init
SELECT
  title,
  power(embedding[1] - 0.10, 2) +
  power(embedding[2] - 0.20, 2) +
  power(embedding[3] - 0.90, 2) AS distance
FROM documents
ORDER BY distance;
Loading plan...

Try Yourself

Loaded Database:vectors.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Find the closest document to ARRAY[0.95, 0.10, 0.20].
2.Return the two closest documents to ARRAY[0.70, 0.25, 0.25].

What We Learned

  • Embeddingis a numeric representation of meaning.
  • Distancescores how far two vectors are from each other.
  • Similarity searchorders rows by nearest vector distance.
  • pgvectoris the common PostgreSQL extension for vector columns.