LESSON 46 · RETRIEVAL

Similarity Search

Learn how similarity search finds the most relevant vectors for a query and powers semantic search, retrieval systems, and RAG applications.

30 min read•Intermediate•Generative AI

By the end of this lesson, you will be able to:

  • Explain what similarity search does.
  • Understand queries, vectors, scores, and nearest neighbors.
  • Compare cosine similarity, dot product, and Euclidean distance.
  • Understand Top-K retrieval and metadata filtering.
  • Build a simple similarity-search example in Python.
  • Explain how similarity search fits into semantic search and RAG.
  • Evaluate retrieval quality instead of relying only on similarity scores.
1

What Is Similarity Search?

Similarity search finds stored items whose vector representations are most similar to a query vector.

Instead of asking for an exact text match, the system compares the meaning represented by vectors. This makes it useful when a user's wording differs from the wording stored in the documents.

Simple idea:Turn the query into a vector, compare it with stored vectors, rank the results, and return the most relevant neighbors.
EXAMPLE 1User question

“How long can I return an item?” can retrieve a chunk saying “Products may be returned within 30 days.”

EXAMPLE 2Meaning-based search

“Ways to reset my password” can retrieve a help article titled “Recover access to your account.”

2

Where Similarity Search Fits

Similarity search usually sits between embedding generation and the final retrieval or generation step.

QueryUser's question
→
EmbeddingConvert query to a vector
→
Similarity searchCompare with stored vectors
→
Top-KKeep the strongest matches

In a RAG system, the selected chunks can become context for the language model.

3

Query Vector vs Stored Vectors

The query is represented as a vector in the same embedding space as the stored document chunks.

QUERY VECTOR

What the user asks

Generated from the user's search question.

↔
STORED VECTORS

What your data contains

Generated earlier from documents, products, tickets, or other content.

The search operation calculates a similarity or distance between the query vector and candidate vectors.

4

Similarity Score

A similarity function produces a score that helps rank candidates. The exact meaning of the score depends on the metric.

COSINE

Direction

Measures the angle between vectors and is commonly used for normalized semantic embeddings.

DOT PRODUCT

Alignment

Uses the vector dot product; magnitude can affect the score.

EUCLIDEAN

Distance

Measures geometric distance; smaller distance means closer vectors.

OTHER METRICS

Task dependent

The best metric depends on the embedding model and retrieval system.

Important: Do not compare raw scores from different metrics as if they had the same scale or interpretation.
5

Nearest Neighbors

Similarity search is often described as a nearest-neighbor search. The system looks for vectors that are closest according to the selected metric.

1NearestStrongest candidate
2Next nearestSecond candidate
3ThirdAnother useful candidate
KCutoffLast returned candidate

The word “nearest” does not necessarily mean physically close. It means close under the chosen vector similarity or distance function.

6

Similarity Search vs Keyword Search

Keyword search
  • Looks for matching terms or text signals
  • Excellent for exact names and identifiers
  • Can struggle with different wording
Similarity search
  • Looks for vector closeness
  • Can match related meaning
  • May miss exact identifiers if retrieval is not designed carefully

Modern search systems often combine lexical and semantic retrieval instead of treating them as mutually exclusive.

7

Top-K Similarity Search

Similarity search can return the strongest K matches instead of returning every candidate.

Query“Refund policy”
→
RankScore candidates
→
Top-KKeep best matches
→
ContextUse selected chunks

For example, Top-K = 5 returns the five highest-ranked candidates after similarity search.

8

Simple Python Similarity Search

Here is a small example using normalized vectors and cosine similarity.

</> Python
import numpy as np

query = np.array([1.0, 0.9, 0.1])

documents = {
    "refund policy": np.array([0.9, 0.8, 0.2]),
    "shipping policy": np.array([0.1, 0.2, 0.9]),
    "return window": np.array([0.8, 0.7, 0.2]),
}

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

ranked = sorted(
    (
        (name, cosine_similarity(query, vector))
        for name, vector in documents.items()
    ),
    key=lambda item: item[1],
    reverse=True,
)

for name, score in ranked:
    print(f"{score:.3f}  {name}")

The system calculates a score for each stored vector, sorts the candidates, and places the strongest matches first.

9

Applying Top-K in Python

Once candidates are ranked, slicing the sorted results gives a simple Top-K operation.

</> Python
k = 2

top_results = ranked[:k]

for name, score in top_results:
    print(f"{name}: {score:.3f}")

In a production vector database, the database index performs the search efficiently rather than comparing every vector in Python.

10

Metadata Filtering

Similarity is not always the only requirement. A user may need results from a particular product, language, customer, or date range.

SEARCH SPACE

All vectors

Potentially contains unrelated products, regions, versions, or document types.

→
FILTER + SEARCH

Relevant candidates

Apply supported metadata constraints and then retrieve the best matching vectors.

Example: Search for “return window” while restricting product = shoes and region = US. The filter narrows the candidate set before or during retrieval, depending on the database.
11

Similarity Search in RAG

Similarity search is one of the core retrieval operations in a RAG pipeline.

1. EmbedEmbed the question
→
2. SearchFind similar chunks
→
3. SelectChoose useful evidence
→
4. GenerateLLM answers with context

If the retriever returns poor evidence, a strong language model may still produce an unsupported answer. Retrieval quality is therefore a critical part of RAG quality.

12

Exact Search vs Approximate Search

For a small collection, an exact search can compare the query with every vector. At large scale, systems often use approximate nearest-neighbor indexes to reduce search work.

EXACT

Exhaustive

Checks all candidates and can provide exact nearest neighbors, but may become expensive as the dataset grows.

APPROXIMATE

ANN

Uses an index designed for fast nearest-neighbor retrieval with a controlled accuracy/speed trade-off.

SPEED

Lower latency

Indexes reduce the amount of work required to find strong candidates.

TRADE-OFF

Recall vs speed

Approximate search requires evaluation to make sure useful neighbors are still being found.

13

Why Similarity Scores Are Not Enough

A high similarity score does not guarantee that a chunk contains the correct answer. Embeddings capture relationships in vector space, not factual truth.

Example:A retrieved chunk can be semantically related to “refund period” but discuss a different product or an outdated policy. Metadata, freshness, reranking, and answer evaluation may still be required.
14

Reranking After Similarity Search

Some systems retrieve a broader candidate set first and then use a stronger reranker to order the candidates again.

STAGE 1Fast retrieval

Retrieve a candidate pool using vector similarity.

STAGE 2Reranking

Apply a more precise relevance model to the candidates.

STAGE 3Final context

Pass only the best evidence to the generation step.

STAGE 4Answer

Generate a grounded response using selected context.

15

Common Similarity Search Mistakes

01Using the wrong metric

The metric should be compatible with the embedding model and retrieval design.

02Ignoring chunk quality

Good similarity cannot rescue poorly formed or incomplete chunks.

03Using K blindly

Too few results can miss evidence; too many can add noise.

04Ignoring metadata

Semantic similarity alone may return the wrong product, region, or version.

05Treating scores as truth

A score measures vector relationship, not factual correctness.

06Skipping evaluation

Test retrieval using real questions and expected evidence.

16

How to Evaluate Similarity Search

Build a representative query set and measure whether the expected evidence appears in the retrieved results.

RECALL@KDoes the relevant evidence appear in the top K?
PRECISIONHow much of the retrieved set is useful?
RANKHow highly are useful chunks ranked?
ANSWER QUALITYDoes better retrieval produce better grounded answers?
Best practice: evaluate retrieval independently before changing the language model. If the right evidence never reaches the prompt, generation cannot reliably use it.
17

Practice: Build a Tiny Similarity Search

Create three or more vectors, define a query vector, calculate cosine similarity, sort the results, and return the top two. Then change the query and observe how the ranking changes.

TASK

Find the nearest documents

Use the Python example above as a starting point. Add one more document vector and explain why it appears where it does in the ranking.

Quick Quiz

1. What does similarity search return?

It returns stored vectors or their associated records ranked by similarity or distance to a query vector.

2. Why is Top-K used?

Top-K limits the retrieved set to the strongest K candidates instead of passing every candidate forward.

3. Is a higher similarity score always proof that a chunk is correct?

No. The score measures vector relationship; it does not guarantee factual correctness, freshness, or the right business context.

4. Why use metadata filters?

Filters can restrict retrieval to candidates that satisfy business or document constraints such as product, region, language, or date.

30-Second Recap

1. Embed

Represent the query as a vector.

2. Compare

Measure similarity or distance to stored vectors.

3. Rank

Order the nearest candidates.

4. Retrieve

Return useful Top-K evidence for the next stage.

Key Takeaways

  • Similarity search finds vectors that are closest to a query under a selected metric.
  • It enables semantic retrieval even when query wording differs from document wording.
  • Top-K controls how many ranked candidates move forward.
  • Metadata filtering can constrain retrieval to the right business context.
  • Exact and approximate nearest-neighbor search make different speed and recall trade-offs.
  • Similarity scores are useful ranking signals, not guarantees of factual correctness.
  • Evaluate retrieval with realistic questions, expected evidence, and answer quality.