Inspecting Distances and Similarity Scores in pgvector
Introduction: Why Look at Distances and Similarity Scores?
Now that you have learned how to run nearest neighbor queries using different distance metrics in pgvector, it is important to go a step further and understand the actual numbers behind those results. In the previous lesson, you saw how to retrieve the most similar products to a given embedding, but the queries only showed you the product IDs and names, ordered by similarity. While this is useful, sometimes you need to see the raw distance or similarity scores themselves. These scores can help you understand how close or far apart items are in the embedding space, set thresholds for filtering results, or debug your search system.
In this lesson, you will learn how to modify your queries to display these distance and similarity values directly in your results. This will give you more insight into how your vector search is working and help you make better decisions about which products to show or recommend.
Viewing Raw L2 (Euclidean) Distance Values in SQL
Let’s start by looking at how to view the actual L2 (Euclidean) distance values in your search results. As a reminder, the <-> operator in pgvector is used to calculate the Euclidean distance between two vectors. In the previous lesson, you used this operator to order your results, but you did not display the distance values themselves.
To include the distance in your output, you can add an extra column to your SELECT statement. Here is an example query that shows the product_id, product_name, and the L2 distance from your query embedding:
In this query, ${QUERY_EMBEDDING} should be replaced with the embedding vector you want to compare against. The embedding <-> ${QUERY_EMBEDDING} part calculates the Euclidean distance between each product’s embedding and your query embedding, and the result is shown in a column called distance. The results are ordered so that the products with the smallest distance (i.e., most similar) appear first.
For example, your output might look like this:
| product_id | product_name | distance |
|---|---|---|
| 1 | Wireless Mouse | 0.231 |
| 7 | Bluetooth Mouse | 0.245 |
| 12 | Ergonomic Mouse | 0.260 |
| 23 | USB Mouse | 0.275 |
| 34 | Gaming Mouse | 0.290 |
Here, you can see not only which products are most similar to your query but also how close they are in the embedding space. A smaller distance means a higher similarity.
