Skip to main content
LearnMLAcademy
Intermediate10 min read

Semantic Search with Embeddings

Build semantic search engines using dense neural embeddings and cosine, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Why exact keyword matching can miss the right answer

A user writes “Why won't my computer turn on?” while the support document says “Laptop fails to power on.” The meaning is similar even though several words differ.

Semantic search represents queries and passages as vectors so the system can compare meaning-related numerical representations rather than requiring exact word overlap.

From text to searchable vectors

  1. Embed the corpus

    Use an embedding model to turn each passage into a vector and store it with its text and metadata.

  2. Embed the query

    Use a compatible embedding model to turn the user's question into a vector in the same representation space.

  3. Measure similarity

    Compare the query vector with passage vectors using a similarity or distance measure.

  4. Return top candidates

    Pass the best-ranked authorized passages to the next RAG stage.

Semantic search matches meaning, not only exact wording

Query

“Why won't my computer turn on?”

Close meaning

“Laptop fails to power on.”

Farther meaning

“Change screen brightness.”

The same embedding model should place both indexed passages and incoming queries into a compatible vector space.

Two differently worded sentences about a computer not powering on are represented near each other in an embedding space, while a sentence about screen brightness is farther away.

Cosine similarity — compare direction

Cosine similarity compares the angle between two vectors after accounting for their magnitudes. A value near 1 means they point in a similar direction; 0 means roughly perpendicular; negative values point in opposing directions.

cos(q,d) = (q · d) / (||q|| ||d||)
Dot product in the numerator measures alignment; the norms in the denominator remove the effect of overall vector length.

For q = [1,1] and d = [1,0]:

q · d = 1

||q|| = √2, ||d|| = 1

cos(q,d) = 1 / √2 ≈ 0.707

For dB = [2,2], the direction is exactly the same as q, so cosine similarity is 1.0 even though dB has a larger magnitude.

The arithmetic measures similarity between representations; it does not prove that a passage answers the question. Inspect the returned text and its conditions as well as its score before using it as evidence.

Semantic search is not always the only search you need

Exact identifiers such as INV-009381, legal clause numbers, product codes, or names can be better handled by lexical matching. Many production systems therefore use hybrid retrieval: combine lexical signals with dense semantic similarity.

Choose the signal that matches the query

Choose the signal that matches the query
Query typeUseful starting approach
Natural-language paraphraseDense semantic retrieval
Exact invoice/product/codeLexical or metadata lookup
Contains both exact code + descriptionHybrid lexical + dense retrieval

Why the next lesson matters

We can turn millions of passages into vectors. Where do we store those vectors, metadata, and permissions—and how do we search them efficiently?

Vector Databases →

Summary / Key Takeaways

  • Semantic search retrieves meaning-related passages even when the wording differs.
  • Queries and indexed passages must use compatible embedding representations.
  • Cosine similarity compares vector direction after normalizing for magnitude.
  • q=[1,1] and d=[1,0] have cosine similarity about 0.707; [2,2] points in the same direction as [1,1], so cosine is 1.
  • Dense semantic search is not automatically best for exact identifiers.
  • Hybrid retrieval combines lexical and semantic signals when a query needs both.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Semantic Search with Embeddings"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What problem does semantic search primarily address?
Question 2 of 5numerical/formula
For q=[1,1] and d=[1,0], what is their cosine similarity approximately?
Question 3 of 5interpretation
Why does dB=[2,2] have cosine similarity 1.0 with q=[1,1] even though its magnitude is larger?
Question 4 of 5debugging/diagnostic
A system indexes passages with embedding model A but embeds new queries with an unrelated model B. Why is this dangerous?
Question 5 of 5practical selection
A search system must find exact invoice numbers such as `INV-009381`. What should the team consider?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What problem does semantic search primarily address?▼

Correct Answer: Retrieving meaning-related text even when wording differs

Embeddings enable meaning-based similarity beyond exact lexical overlap.

2For q=[1,1] and d=[1,0], what is their cosine similarity approximately?▼

Correct Answer: 0.707

Dot product is 1, norms are √2 and 1, so cosine is `1/√2 ≈ 0.707`.

3Why does dB=[2,2] have cosine similarity 1.0 with q=[1,1] even though its magnitude is larger?▼

Correct Answer: Cosine compares direction after normalizing by vector magnitudes

The vectors point in the same direction; cosine normalizes away overall magnitude.

4A system indexes passages with embedding model A but embeds new queries with an unrelated model B. Why is this dangerous?▼

Correct Answer: Their vector spaces may be incompatible, making distances meaningless

Similarity is meaningful only when query and corpus vectors inhabit compatible representation spaces.

5A search system must find exact invoice numbers such as `INV-009381`. What should the team consider?▼

Correct Answer: Lexical or hybrid retrieval because exact identifiers are often better matched lexically

Semantic search is not universally superior; exact terms/codes often benefit from lexical search or a hybrid design.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next