Similarity Search
Learn how similarity search finds the most relevant vectors for a query and powers semantic search, retrieval systems, and RAG applications.
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.
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.
“How long can I return an item?” can retrieve a chunk saying “Products may be returned within 30 days.”
“Ways to reset my password” can retrieve a help article titled “Recover access to your account.”
Where Similarity Search Fits
Similarity search usually sits between embedding generation and the final retrieval or generation step.
In a RAG system, the selected chunks can become context for the language model.
Query Vector vs Stored Vectors
The query is represented as a vector in the same embedding space as the stored document chunks.
What the user asks
Generated from the user's search question.
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.
Similarity Score
A similarity function produces a score that helps rank candidates. The exact meaning of the score depends on the metric.
Direction
Measures the angle between vectors and is commonly used for normalized semantic embeddings.
Alignment
Uses the vector dot product; magnitude can affect the score.
Distance
Measures geometric distance; smaller distance means closer vectors.
Task dependent
The best metric depends on the embedding model and retrieval system.
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.
The word “nearest” does not necessarily mean physically close. It means close under the chosen vector similarity or distance function.
Similarity Search vs Keyword Search
- Looks for matching terms or text signals
- Excellent for exact names and identifiers
- Can struggle with different wording
- 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.
Top-K Similarity Search
Similarity search can return the strongest K matches instead of returning every candidate.
For example, Top-K = 5 returns the five highest-ranked candidates after similarity search.
Simple Python Similarity Search
Here is a small example using normalized vectors and cosine similarity.
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.
Applying Top-K in Python
Once candidates are ranked, slicing the sorted results gives a simple Top-K operation.
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.
Metadata Filtering
Similarity is not always the only requirement. A user may need results from a particular product, language, customer, or date range.
All vectors
Potentially contains unrelated products, regions, versions, or document types.
Relevant candidates
Apply supported metadata constraints and then retrieve the best matching vectors.
product = shoes and region = US. The filter narrows the candidate set before or during retrieval, depending on the database.Similarity Search in RAG
Similarity search is one of the core retrieval operations in a RAG pipeline.
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.
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.
Exhaustive
Checks all candidates and can provide exact nearest neighbors, but may become expensive as the dataset grows.
ANN
Uses an index designed for fast nearest-neighbor retrieval with a controlled accuracy/speed trade-off.
Lower latency
Indexes reduce the amount of work required to find strong candidates.
Recall vs speed
Approximate search requires evaluation to make sure useful neighbors are still being found.
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.
Reranking After Similarity Search
Some systems retrieve a broader candidate set first and then use a stronger reranker to order the candidates again.
Retrieve a candidate pool using vector similarity.
Apply a more precise relevance model to the candidates.
Pass only the best evidence to the generation step.
Generate a grounded response using selected context.
Common Similarity Search Mistakes
The metric should be compatible with the embedding model and retrieval design.
Good similarity cannot rescue poorly formed or incomplete chunks.
Too few results can miss evidence; too many can add noise.
Semantic similarity alone may return the wrong product, region, or version.
A score measures vector relationship, not factual correctness.
Test retrieval using real questions and expected evidence.
How to Evaluate Similarity Search
Build a representative query set and measure whether the expected evidence appears in the retrieved results.
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.
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
Represent the query as a vector.
Measure similarity or distance to stored vectors.
Order the nearest candidates.
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.