liveBook · Manning

Cosine similarity

As explained in Generative AI in Action

Cosine similarity measures the cosine of the angle between two vectors and indicates their directional similarity.

Cosine similarity helps a semantic search system find documents related to a query. It measures the cosine of the angle between two vectors, comparing their direction regardless of magnitude. This makes it useful for text embeddings when direction matters more than vector length. section 8.3 section 7.4

Similarity ranges from −1 for opposite directions to 1 for the same direction. Cosine similarity is commonly used with normalized embeddings; for normalized vectors, the dot product is equivalent. Cosine is less suitable when vector magnitude is important. Choose a metric that fits the data and query needs, and use the metric associated with the embedding model. section 7.5.2

In a retrieval-augmented generation workflow, documents can be split into chunks, embedded, and stored with metadata. A retriever compares a query embedding with stored embeddings to find relevant content. A vector index supports fast nearest-neighbor lookup; its design balances speed, accuracy, and memory consumption. section 7.4 section 7.5.1

Find related posts

A Redis search application converts “Tell me about Longhorn” into a vector, then uses a K-nearest-neighbors query to retrieve the three most similar posts. The results include fields such as the URL, title, content, and vector score. section 8.5

Listing 8.2 Redis index schema
SCHEMA = [
    TagField("url"),
    TextField("title"), 
    TextField("description"),
    TextField("publish_date"),
    TextField("content"),
    VectorField("embedding", "HNSW",
                {"TYPE": "FLOAT32",
                 "DIM": 1536,
                 "DISTANCE_METRIC": "COSINE"}),
   ]

The Redis schema configures an HNSW embedding field with FLOAT32 values, 1,536 dimensions, and the COSINE distance metric. The dimensions must match the embedding model. section 8.3

How Generative AI in Action covers it

How deep it goes
Defines directional similarity and its range, compares alternative metrics, and configures cosine distance in a Redis index without a mathematical derivation.
Examples
Uses a Longhorn query to retrieve three similar posts and a Redis HNSW schema configured with COSINE.
What you can do after
Apply it via Redis to configure an embedding index and retrieve similar posts.
How it connects
Connects embeddings, vector search, nearest-neighbor indexes, dot product, and retrieval-augmented generation.

Also explained in

Compare how 16 books explain cosine similarity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Generative AI in Action. The section links point to the parts of the book it draws on.