Similarity Search
Similarity search finds the vectors that are closest to a query vector. It is the retrieval engine behind semantic search, recommendations, document retrieval, and many RAG systems.
By the end of this lesson, you will be able to:
- Explain what similarity search does and why embeddings make it possible.
- Understand query vectors, candidates, scores, distance, and top-k results.
- Compare cosine similarity, dot product, and Euclidean distance at a practical level.
- Write simple Python similarity-search logic.
- Combine similarity search with metadata filters and vector databases.
- Understand how retrieval quality affects semantic search and RAG.
What Is Similarity Search?
Similarity search retrieves items whose vector representations are most similar to a query vector. The query might come from a user's question, a document, an image, or another piece of content.
Why Embeddings Are Needed
A computer can compare strings directly, but semantic retrieval needs a representation that captures meaning. An embedding model converts content into numerical vectors that can be compared mathematically.
Text overlap
Looks for matching words or indexed terms. It can miss useful documents when the wording is different.
Meaning proximity
Compares embeddings so related ideas can be retrieved even when the exact words differ.
May retrieve a document saying "affordable airfare for Paris."
May retrieve "steps to change your login credentials."
Query Vector and Stored Vectors
Similarity search compares one query vector with many stored vectors. Each stored vector normally has an ID and may have metadata such as a category, language, product ID, or document source.
For example, a search may compare one query against 100,000 document vectors and return only the best 5 matches. A vector database or vector index is responsible for making that retrieval efficient.
How Similarity Is Measured
Different systems use different metrics. The important point is that the ranking rule must match how your vectors are represented and how the index is configured.
Direction
Measures the angle between vectors. Common for normalized text embeddings and semantic search.
Interaction
Uses the dot product. For normalized vectors, it has the same ranking as cosine similarity.
Geometric distance
Measures straight-line distance. Smaller distance means vectors are closer.
Top-k Search
Top-k means returning the k highest-ranked candidates after comparing the query with the searchable vectors.
If k=3, the application receives the first three results. Choosing k is a retrieval-quality decision: too few results can miss useful context, while too many can add irrelevant information.
Python: Simple Cosine Similarity
Before using a vector database, it helps to understand the basic operation with plain Python. This example ranks a few small vectors against a query vector.
import math
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot / (norm_a * norm_b)
query = [1.0, 0.8, 0.1]
documents = {
"doc-1": [0.9, 0.7, 0.2],
"doc-2": [0.1, 0.2, 0.9],
"doc-3": [0.8, 0.6, 0.1],
}
scores = [
(doc_id, cosine_similarity(query, vector))
for doc_id, vector in documents.items()
]
for doc_id, score in sorted(scores, key=lambda item: item[1], reverse=True):
print(doc_id, round(score, 4))Ranking Results
The search engine calculates a score or distance for each candidate and sorts the candidates according to the metric. Your application then takes the best results.
Very strong match
Strong match
Useful candidate
Potentially weak match
Similarity Search with Metadata Filters
Semantic similarity and metadata filtering solve different problems. Similarity finds semantically close records; filters enforce structured constraints.
For example, a support system could search semantically for "cancel my order" while filtering to language="en" and region="UK". This reduces irrelevant candidates before the application uses the results.
Similarity Search in a Vector Database
In production, the vector index is usually not a Python list. A vector database such as FAISS-based infrastructure, Qdrant, or Pinecone provides indexing and retrieval capabilities for larger collections.
Approximate vs Exact Search
Exact search compares the query with every relevant vector. This is simple and can be highly accurate, but scanning a very large collection can become expensive.
Check all candidates
Useful for smaller datasets and evaluation because the true nearest neighbors can be calculated directly.
Search an index
Uses specialized indexing structures to find very good candidates much faster at scale.
Approximate nearest-neighbor (ANN) methods trade some retrieval behavior for speed and scale. The right index depends on dataset size, latency targets, memory, and recall requirements.
Similarity Search for Semantic Search
A semantic search pipeline typically embeds both stored content and the incoming query. The query vector is then used to retrieve the nearest content vectors.
Split source material into useful retrieval units.
Convert each chunk into a vector.
Keep vectors, IDs, and metadata in an index.
Convert the user's question into a vector.
Retrieve the nearest top-k candidates.
Similarity Search in RAG
Retrieval-augmented generation (RAG) uses similarity search to select external context before an LLM generates an answer.
If retrieval returns poor chunks, the LLM may receive weak evidence. Improving RAG therefore often requires improving chunking, embeddings, metadata, search parameters, and evaluationβnot only changing the LLM prompt.
Similarity Thresholds
Top-k always returns candidates when candidates exist, but not every candidate is necessarily relevant. Some applications therefore combine ranking with a relevance threshold or a second-stage reranker.
Likely useful context, subject to evaluation.
May be relevant depending on the dataset and query.
Often weak, but only a measured threshold should decide.
Common Mistakes
The index metric does not match the vector representation or application assumptions.
Stored vectors and query vectors must have compatible dimensions.
Large top-k values can introduce noisy context into downstream systems.
Scores depend on the embedding model, metric, and data distribution.
Pure semantic similarity cannot enforce every business constraint.
A search that looks plausible in one example may fail across real queries.
How to Evaluate Similarity Search
Good retrieval should be measured using a representative test set. For each query, define which documents or chunks are relevant and check what the search system returns.
Measures whether the expected relevant results were retrieved within the first k results.
Measures the relevance of the returned top-k set.
Measures the time required to produce the search results.
Build a Tiny Similarity Search
Use the Python example from this lesson and extend it into a small retrieval experiment.
- Create 5β10 short document vectors.
- Create one query vector.
- Calculate cosine similarity for every document.
- Sort the results from highest to lowest score.
- Return the top 3 results.
- Change the query and observe how the ranking changes.
category and filter the candidates before ranking them.Quick Quiz
A query vector with stored vectors using a chosen metric.
The k highest-ranked results returned by the search.
No. It depends on whether the metric is a similarity score or a distance.
To enforce structured constraints that semantic similarity alone cannot guarantee.
Because plausible-looking search results do not guarantee that the system retrieves the context users actually need.
30-Second Recap
Key Takeaways
- Similarity search retrieves vectors that are close to a query vector according to a chosen metric.
- Embeddings make semantic retrieval possible by representing content numerically.
- Top-k controls how many ranked candidates are returned.
- Metadata filters complement semantic similarity with structured constraints.
- Similarity search is a core building block of semantic search and RAG.
- Retrieval quality should be evaluated with real queries instead of trusting one example or one score threshold.