Knowledge / Artificial Intelligence and Data Science / Text embeddings and semantic search

Text embeddings and semantic search

Artificial Intelligence and Data Science (B.E./B.Tech) · AI applications · free study notes for exams, placements and interviews

In short

A text embedding is a fixed-length vector of real numbers that represents the meaning of a word, sentence or document, learned so that texts with similar meaning land close together in the vector space. Semantic search uses these vectors: the query is embedded, and documents are ranked by vector similarity instead of by exact keyword match, so "two-wheeler loan EMI" can retrieve "bike finance instalment". Embeddings are the measurement layer under search, recommendation, deduplication, classification and clustering, and they are asked in AI/DS university papers, GATE DA (vector representations, similarity, evaluation metrics) and in almost every applied-AI interview at Indian employers. Typical production work is choosing an embedding model, chunking text, computing cosine similarity, and tuning recall against latency and cost.

Explained

What an embedding is

How embeddings are learned

Similarity, distance and the geometry

The semantic search pipeline

  1. Chunk: split documents into retrievable units (typically 200–500 tokens with 10–20% overlap); respect headings so a chunk is self-contained. Over-long chunks dilute meaning; over-short chunks lose context.
  2. Embed (offline): run every chunk through the encoder, L2-normalise, store vector + text + metadata (source, date, language, access tag).
  3. Index: exact flat index (brute force, 100% recall) for small corpora; approximate nearest neighbour for large ones — IVF (cluster, probe nprobe lists), HNSW (navigable small-world graph; parameters M, efConstruction, efSearch), PQ/IVF-PQ (product quantisation, heavy compression), ScaNN.
  4. Query: embed the query with the same model and same normalisation, retrieve top-k (k = 50–200 for reranking), optionally filter by metadata.
  5. Rerank: a cross-encoder scores (query, passage) jointly and is far more accurate but O(k) forward passes — so it is applied only to the shortlist. The retriever is a bi-encoder (independent, precomputable, fast).
  6. Hybrid: combine dense scores with lexical BM25 (good at rare words, codes, product numbers like "HSN 8471") using weighted sum or Reciprocal Rank Fusion (RRF): score = Σ 1/(60 + rank).
  7. Asymmetric search: short query vs long passage — use a model trained for it, often with instruction prefixes ("query: ", "passage: "). Symmetric search (duplicate questions) uses the same prefix for both.

Evaluation and tuning

Limits, Indian-language practice and compliance

Key points

Formulas and examples

Cosine similarity: cos θ = (a · b) / (‖a‖ ‖b‖), where a · b = Σᵢ aᵢbᵢ and ‖a‖ = √(Σᵢ aᵢ²); dimensionless, range −1 to +1
Euclidean distance: ‖a − b‖ = √(Σᵢ (aᵢ − bᵢ)²); relation: ‖a − b‖² = ‖a‖² + ‖b‖² − 2(a · b)
For unit vectors: ‖a − b‖² = 2 − 2 cos θ, so cos θ = 1 − ‖a − b‖²/2
TF-IDF weight: w = tf × log(N / df); N = number of documents, df = documents containing the term
PMI(w, c) = log[ P(w, c) / (P(w) P(c)) ]; PPMI = max(PMI, 0)
Skip-gram with negative sampling: L = −log σ(v_c · v_w) − Σ_{j=1..k} log σ(−v_{nj} · v_w), σ(x) = 1/(1 + e−x)
InfoNCE (contrastive): L = −log[ exp(s(q, p⁺)/τ) / Σ_j exp(s(q, pⱼ)/τ) ]; τ = temperature (≈0.01–0.1)
MRR = (1/|Q|) Σ_q 1/rank_q (0 if no relevant result retrieved)
DCG@k = Σ_{i=1..k} relᵢ / log₂(i + 1); nDCG@k = DCG@k / IDCG@k
Recall@k = (relevant items in top k) / (total relevant items)
Reciprocal Rank Fusion: RRF(d) = Σ_lists 1/(60 + rank_list(d))
Storage (float32) = N × d × 4 bytes; brute-force query cost ≈ N × d multiply-adds

Example 1 — cosine, distance and their relation. a = [2, 1, 0, 3], b = [1, 0, 1, 2].

Example 2 — normalisation makes metrics interchangeable. Two unit vectors have cos θ = 0.90.

Example 3 — TF-IDF vs embedding behaviour. Corpus N = 10,000 documents; the term "subvention" appears in df = 50 documents; a document of 100 words uses it 3 times.

Example 4 — retrieval evaluation on 3 queries. Rank of the first relevant document: q1 = 1, q2 = 3, q3 = not found in top 10. Each query has exactly 1 relevant document.

DCG = 3/log₂2 + 0/log₂3 + 2/log₂4 = 3/1 + 0 + 2/2 = 4.000 Ideal order [3, 2, 0]: IDCG = 3/1 + 2/1.585 + 0 = 3 + 1.262 = 4.262 nDCG@3 = 4.000/4.262 = 0.939

Example 5 — storage, latency and cost of a 1-million-chunk index. d = 768, N = 1,000,000.

Lexical (BM25/TF-IDF)Dense embeddingsCross-encoder rerank
MatchingExact terms, weightedMeaning, paraphraseJoint query–passage reading
Handles synonymsNoYesYes
Handles codes, IDs, namesVery wellPoorlyWell
PrecomputeInverted indexVectors offlineNothing — runtime only
Latency for 1M docsMillisecondsMilliseconds with ANNToo slow (used on top 50–100)
Training data neededNonePairs for fine-tuningLabelled pairs
InterpretabilityHigh (term matches)LowLow
Embedding typeVector perExample modelsStrengthWeakness
Static wordWord typeword2vec, GloVeTiny, instant lookupNo context, no OOV
SubwordWord + n-gramsfastTextOOV, Indic morphologyStill context-free
Contextual tokenOccurrenceBERT, MuRIL, IndicBERTDisambiguates meaningNeeds pooling for sentences
Sentence/passageWhole textSBERT, E5, BGE, LaBSEReady for cosine searchMax-length truncation

Where it is used

Interview questions

Common mistakes

Related topics

Natural language processing basics · Retrieval-augmented generation and vector databases · Large language models and prompt engineering · Recommender systems · Information retrieval and ranking · Dimensionality reduction and clustering

Open in the Knowledge reader →Find jobs →