liveBook · Manning

Cosine distance

As explained in Just Use Postgres!

Cosine distance is a dissimilarity measure derived from the angle between two vectors, commonly defined as one minus cosine similarity.

Cosine distance measures how related two embedding vectors are by comparing the angle between them. Smaller angles produce smaller distances and indicate stronger relationships; larger angles indicate less similarity. The pgvector cosine-distance operator is <=>, and it is especially suitable for L2-normalized text embeddings. section 8.4

Use cosine distance to rank semantic search results in Postgres. This query orders movie embeddings by their distance from a stored phrase embedding and returns the three nearest neighbors: section 8.4.1

Search movies by meaning

SELECT id, name, description FROM omdb.movies ORDER BY movie_embedding <=> omdb.get_embedding('May the force be with you') LIMIT 3; The query places the smallest distances first. It returns Star Wars titles even when the search phrase does not literally appear in their names or descriptions. Displaying the distance makes relevance easier to inspect: a result near 0 is more related than one near 1. Replacing the phrase with “A movie about a Jedi who fights against the dark side of the force” improves the top result from about 0.39 to 0.27. section 8.4.1 section 8.4.2

Figure 8.7 Angle difference between more- and less-related vector embeddings.
A drawing of a triangle with lines and arrows

AI-generated content may be incorrect.

Compare the angles between more-related and less-related embeddings visually. section 8.4.1

Listing 8.12 Creating the HNSW index
CREATE INDEX movie_embeddings_hnsw_idx
ON omdb.movies
USING hnsw (movie_embedding vector_cosine_ops)
WITH (m = 8, ef_construction = 16);

Inspect how a cosine-distance HNSW index is created for faster vector search. section 8.5.2

How Just Use Postgres! covers it

How deep it goes
Explains angle-based ranking, SQL execution, distance values, phrase refinement, and HNSW indexing without developing the underlying mathematics.
Examples
Uses Star Wars movie searches, explicit distance output, refined phrases, SQL queries, and HNSW execution plans.
What it assumes
Assumes stored text embeddings and teaches distance-based retrieval, normalized vectors, phrase lookup, and result ordering.
What you can do after
Apply cosine distance via pgvector SQL to rank embeddings, inspect relevance, refine queries, and configure HNSW search.
How it connects
Connects embeddings, vector similarity search, L2 normalization, pgvector, nearest neighbors, and HNSW indexes.

Also explained in

Compare how 6 books explain cosine distance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.