NLP
Advanced 16 min read NLP

Embedding Search and Semantic Similarity

Matching meaning, not just vocabulary

Semantic search compares meanings rather than keywords: embed queries and documents, then find nearest neighbors. Cosine similarity plus vector indexes and hybrid ranking make it production-ready.

semantic searchembeddingscosine similarityvector indexHNSWhybrid search
Prerequisites: Word Embeddings
Before we start

What you will learn

  • Embed documents and queries into a shared space
  • Rank by cosine similarity with correct math and indexing
  • Combine lexical + semantic signals for hybrid ranking
Introduction

What is this?

Semantic search replaces keyword matching with meaning: each query and document is embedded into a dense vector space where similarity reflects semantic closeness. Ranking = nearest-neighbor retrieval by cosine similarity (or dot product on normalized vectors) supported by ANN indexes like HNSW or scaled product quantization for millions of vectors. In practice the best systems are hybrid — BM25 for exact terms, embeddings for meaning — fused to cover each other's blind spots.

Motivation

Why do you need it?

  • Users search by concept; keyword search fails on paraphrase ('how do I change my pwd?' vs 'password reset').
  • Embeddings are cheap to serve: precompute doc vectors, embed the query once, retrieve by index.
  • Hybrid retrieval measurably beats either alone on real corpora.
  • Semantic similarity powers more than search: dedup, clustering, question-answering context.
Think about it

Mental model

Imagine

A library with two catalogues — by title and by subject-matter index

Think of

Lexical + semantic retrieval

The title catalogue finds exact matches fast; the subject index finds 'books about this idea' whose titles never overlap. The best library uses both and merges the results — that's hybrid search.

Mechanics

How it works

  • Embed legal docs (chunked) with a sentence/retriever model into dense vectors.
  • Normalize and store in a vector index (faiss, hnswlib, pgvector, Milvus).
  • At query time embed the query with the SAME model — model parity is non-negotiable.
  • Retrieve top-k by cosine (inner product on normalized) with ANN for scale.
  • Hybrid: BM25 lexical scores + semantic scores → rank fusion (RRF or learned blend).

Documents → vectors → ANN → ranked results.

Corpus
Embed
Index
Query
Hybrid fuse
Real world

In production

  • Customer support RAG retrieves resolution docs by semantic meaning ahead of LLM answer.
  • Product search blends embedding relevance with a boosted exact-match for SKU codes.
  • A knowledge base dedupes near-duplicate articles via similarity clusters.
Guidelines

Best practices

  • Embed at chunk size that matches the query's granularity and the answer length.
  • Use the same retriever model at index and query time; freeze version changes behind a rebuild.
  • Normalize vectors; pick one distance metric and keep the index consistent with the metric.
  • Build a hybrid with BM25 and tune fusion weights on a labeled relevance set.
Watch out

Common mistakes

  • Mixing embedding-model versions across index and query (silent distribution gap).
  • Retrieving by raw cosine on unnormalized vectors — magnitude dominates similarity.
  • Treating recall@10 on synthetic eval as production relevance — judgments need real queries.
  • Over-chunking legal docs into units smaller than the answer, losing the answer across chunks.
Root cause analysis

Common issues

Error
Semantic-only search misses exact SKU queries
Root cause

Embeddings scatter the literal code

Fix

Add hybrid: BM25 exact-token branch scores SKU codes overwhelmingly and fuses in.

Error
Retrieval quality drops after an index rebuild
Root cause

Embedding model version changed or vectors not re-normalized

Fix

Pin the model + metadata, verify a golden set's recalls before and after the rebuild.

When things break

Debugging tips

  • For a broken match, print the top-3 nearest neighbors' text — hard negative inspection is fastest.
  • If short queries underperform, embed with padding or use the query-aggregation convention of your model.
  • ANN recall < 100% — tune ef/candidates trade-off; monitor recall on a quality sample.
  • Compare a lexical-only baseline: metric lift proves the semantic layer adds value.
Interviews

Interview checkpoint

Practice

Hands-on lab

Semantic Search With Cosine Ranking
35 min · advanced
In progress
Objectives
  • Embed a small corpus and a query into the same space
  • Rank by cosine similarity by hand
  • Show the semantic advantage over keyword match

Semantic Search With Cosine Ranking

35 min · advanced

0/5 steps
0%
sandbox · Linux sandbox
$
Try these commands
Test yourself

Quick quiz

0/2
1

ANN indexes are needed when:

2

Cosine similarity between unnormalized vectors equals normalized dot product.

Go deeper

Official documentation