A pgvector similarity query orders stored vectors by a distance operator and returns the nearest rows. In this first lab, you will store three-dimensional teaching vectors, query them with cosine and Euclidean distance, inspect numeric scores, and change the query direction. No embedding model is needed yet, so every result remains visible and explainable.
Use three axes—“billing,” “technical,” and “account”—only as a learning analogy. Real embedding dimensions do not have simple human labels. These manual vectors let you see that a query near one axis should retrieve candidates pointing in a similar direction.
Lab: 20 minutes · Cost: free locally · Cleanup: DROP TABLE lab_items;
Search with cosine distance:
Smaller distance is nearer, so the ascending order is intentional. Cosine similarity is 1 - cosine_distance for non-zero vectors. The refund-related vector should rank first. Do not assume every similarity score must be positive; geometry and metric determine its range.
Now compare L2 distance:
<-> measures Euclidean distance, including magnitude. <=> focuses on the angle between non-zero vectors. Later chapters connect metric choice to model training.
LIMIT 3 asks for the three nearest stored rows under the selected ordering. It does not apply a semantic quality threshold. The third result may be irrelevant if the database contains only poor candidates. Your application needs evaluation, optional distance rules, metadata constraints, and a safe “no useful evidence” outcome.
This finds items similar to an existing item. In a recommendation feature, filters would also enforce availability, tenant, policy, and diversity.
Run each query twice, save the order and distances, then change the query to [0,1,0]. debug API should move to the first position. Verify dimensions:
Try inserting [1,2]; PostgreSQL should reject the two-dimensional value for a vector(3) column.
Given these labeled three-dimensional vectors [paste rows], predict the top three results for query [vector] under cosine and L2 distance. Show calculations for one candidate, then generate SQL. State where the analogy stops matching real embeddings.
Verification contract: Compare the predicted order and numeric values with PostgreSQL output. Investigate differences rather than changing the expected answer after the fact.