LESSON 36 Β· VECTOR DATABASES

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.

35 min readβ€’Beginnerβ€’Generative AI

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.
1

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.

User query"How do I reset my password?"
β†’
EmbeddingQuery becomes a vector
β†’
Similarity searchCompare against stored vectors
β†’
Top resultsMost relevant records
Key idea:Similarity search does not search for identical text. It searches for vectors that are close according to a chosen similarity or distance metric.
2

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.

KEYWORD SEARCH

Text overlap

Looks for matching words or indexed terms. It can miss useful documents when the wording is different.

VS
SIMILARITY SEARCH

Meaning proximity

Compares embeddings so related ideas can be retrieved even when the exact words differ.

QUERY"cheap flights to Paris"

May retrieve a document saying "affordable airfare for Paris."

QUERY"reset account password"

May retrieve "steps to change your login credentials."

3

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.

QUERYqThe vector representing the user's search.
VECTORv₁, vβ‚‚, v₃...Stored embeddings in the index.
SCOREs(q, v)How similar or distant two vectors are.
TOP-Kk resultsThe highest-ranked matches returned.

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.

4

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.

COSINE SIMILARITY

Direction

Measures the angle between vectors. Common for normalized text embeddings and semantic search.

DOT PRODUCT

Interaction

Uses the dot product. For normalized vectors, it has the same ranking as cosine similarity.

EUCLIDEAN DISTANCE

Geometric distance

Measures straight-line distance. Smaller distance means vectors are closer.

Important: do not assume that a larger score is always better. Similarity metrics and distance metrics have different directions.
5

Top-k Search

Top-k means returning the k highest-ranked candidates after comparing the query with the searchable vectors.

QUERY"How can I return a product?"
#1Return policy β€” online purchases0.94
#2Refund and exchange rules0.89
#3Shipping a product back0.84
#4Payment cancellation policy0.61

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.

6

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.

</> Python
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))
What this teaches:the database is not creating the meaning. The embedding vectors already exist; similarity search ranks those vectors.
7

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.

10.93

Very strong match

20.87

Strong match

30.73

Useful candidate

40.41

Potentially weak match

Do not over-trust scores:a score is meaningful within the metric, model, and dataset that produced it. A universal threshold such as "0.8 always means relevant" is unsafe.
8

Similarity Search with Metadata Filters

Semantic similarity and metadata filtering solve different problems. Similarity finds semantically close records; filters enforce structured constraints.

QUERY"running shoes for rain"
+
FILTERcategory = "shoes"
+
RESULTTop matching shoe records

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.

9

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.

Embedding modelquery β†’ vector
β†’
Vector indexsearch candidates
β†’
Metadata filterapply constraints
β†’
Top-kreturn matches
Separation of responsibilities: the embedding model represents content; the vector index performs retrieval; your application decides how to use the retrieved records.
10

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.

EXACT SEARCH

Check all candidates

Useful for smaller datasets and evaluation because the true nearest neighbors can be calculated directly.

VS
APPROXIMATE SEARCH

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.

11

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.

1Chunk documents

Split source material into useful retrieval units.

2Embed chunks

Convert each chunk into a vector.

3Store vectors

Keep vectors, IDs, and metadata in an index.

4Embed query

Convert the user's question into a vector.

5Search

Retrieve the nearest top-k candidates.

12

Similarity Search in RAG

Retrieval-augmented generation (RAG) uses similarity search to select external context before an LLM generates an answer.

QuestionUser asks
β†’
Query embeddingCreate vector
β†’
Similarity searchFind context
β†’
LLMUse retrieved context
β†’
AnswerGenerate response

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.

13

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.

HIGH SCOREKeep

Likely useful context, subject to evaluation.

MIDDLE SCOREReview

May be relevant depending on the dataset and query.

LOW SCOREReject

Often weak, but only a measured threshold should decide.

Best practice:Choose thresholds from evaluation data. Test real queries and measure whether retrieved results are actually relevant.
14

Common Mistakes

Using the wrong metric

The index metric does not match the vector representation or application assumptions.

Ignoring dimensions

Stored vectors and query vectors must have compatible dimensions.

Returning too many results

Large top-k values can introduce noisy context into downstream systems.

Using a universal score threshold

Scores depend on the embedding model, metric, and data distribution.

Skipping metadata

Pure semantic similarity cannot enforce every business constraint.

Not evaluating retrieval

A search that looks plausible in one example may fail across real queries.

15

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.

RECALL@KDid relevant items appear?

Measures whether the expected relevant results were retrieved within the first k results.

PRECISION@KHow many results were relevant?

Measures the relevance of the returned top-k set.

LATENCYHow fast is retrieval?

Measures the time required to produce the search results.

PRACTICE

Build a Tiny Similarity Search

Use the Python example from this lesson and extend it into a small retrieval experiment.

  1. Create 5–10 short document vectors.
  2. Create one query vector.
  3. Calculate cosine similarity for every document.
  4. Sort the results from highest to lowest score.
  5. Return the top 3 results.
  6. Change the query and observe how the ranking changes.
Challenge: add a metadata field such as category and filter the candidates before ranking them.

Quick Quiz

1. What does similarity search compare?

A query vector with stored vectors using a chosen metric.

2. What does top-k mean?

The k highest-ranked results returned by the search.

3. Does a higher score always mean a better result?

No. It depends on whether the metric is a similarity score or a distance.

4. Why use metadata filters?

To enforce structured constraints that semantic similarity alone cannot guarantee.

5. Why is retrieval evaluation important?

Because plausible-looking search results do not guarantee that the system retrieves the context users actually need.

30-Second Recap

1. EmbedTurn content and queries into vectors.
2. CompareMeasure vector similarity or distance.
3. RankOrder candidates by the chosen metric.
4. FilterApply metadata and business constraints.
5. RetrieveReturn useful top-k context for the application.

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.