liveBook · Manning

Distance

As explained in Build an Advanced RAG Application (From Scratch)

A distance metric is a function that quantifies proximity or dissimilarity between points or vectors in a mathematical space.

A distance function quantifies proximity or dissimilarity between vectors. In semantic search, it compares a query embedding with document embeddings so results can be ranked by relevance. section 4.3

Choose the metric according to the relationship the search should emphasize:

  • Cosine distance measures the angle between vectors, emphasizing orientation rather than magnitude. section 4.3
  • Euclidean distance measures the straight-line distance between points in a multidimensional space. section 4.3
  • The selected metric can change both the quality and interpretability of search results. section 4.3

Cosine ranking for hotel search

Encode the query "Hotel near the Louvre with great food nearby," compute dot products against review embeddings, normalize by the query and review vector norms, sort similarities in descending order, and return the top five hotels with their scores.

How Build an Advanced RAG Application (From Scratch) covers it

How deep it goes
Defines cosine and Euclidean distance, then implements cosine ranking with normalization and top-k selection.
Examples
Uses a Paris hotel query, review embeddings, ranked hotel reviews, and printed similarity scores.
What it assumes
Assumes dense embeddings and Sentence Transformers, while establishing how vector comparisons support semantic retrieval.
What you can do after
Apply it via NumPy to rank embedded documents and inspect the highest-scoring semantic matches.
How it connects
Connects embeddings, semantic search, cosine distance, Euclidean distance, cross-encoders, and bi-encoders.

Also explained in

Compare how 12 books explain distance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build an Advanced RAG Application (From Scratch). The section links point to the parts of the book it draws on.