LLM & AI agents

Embeddings and Semantic Search: Measuring Text Similarity

The article explains comparable text vectors through cosine similarity, dot products and Euclidean distance. Approximate nearest-neighbour search is considered alongside data cleaning, access filters and lexical retrieval rather than as a standalone solution. Technical-support queries illustrate evaluation with Recall@k, MRR and nDCG, including the tests needed for multilingual use and embedding-model migrations.

On this page

What problem does an embedding model solve?

An embedding model represents sentences, paragraphs or document passages as fixed-length vectors. Training encourages related examples to be close in the representation space and unrelated examples to be further apart. This proximity is not an absolute measure of semantic truth: it depends on training objectives, domains and negative examples. A retriever trained for question–passage relevance may behave differently from a general sentence-similarity model. Query length, technical vocabulary and multilingual coverage all affect model selection. Larger vector dimensions alone do not guarantee better retrieval.

Cosine similarity, dot product and Euclidean distance

Cosine similarity measures the angle between vectors: a·b / (||a|| ||b||). With L2-normalized vectors, cosine and dot-product rankings can become equivalent. An unnormalized dot product also responds to vector magnitude, which may be intentional for some models. Euclidean distance captures both direction and magnitude differences. Swapping metrics without checking the embedding model can change nearest-neighbor rankings. Keep the indexing metric consistent with model recommendations and revisit any fixed similarity threshold after a model migration.

Stages of semantic searchText passageEmbedding modelVector indexNearest candidatesRelevance test
Figure 1. Document preparation, embeddings and indexing form the offline pipeline; filtered candidates are evaluated at query time.

Why do vector indexes matter?

Brute-force vector comparison is simple for a few hundred documents but becomes expensive at millions of passages. Approximate nearest-neighbor (ANN) indexes trade a little retrieval recall for lower latency or memory demand. Graph approaches such as HNSW and compression approaches such as product quantization suit different workloads. Operational details—insertions, deletions, rebuilding and metadata filtering—matter as much as the index's headline speed. An in-memory synthetic benchmark may not resemble a corporate archive that is updated throughout the day.

Good search begins with document preparation

An archive contains tables, headings and repeated page headers as well as paragraphs. When a chunk boundary separates a condition from its consequence, a vector from the right document can still return incomplete evidence. Document identity, section, version, language and permissions therefore matter alongside the embedding. Old and current manuals appearing together often point to document-version management rather than a need for a stronger embedding model.

How do semantic and lexical retrieval complement each other?

Embedding search can connect semantically related phrases, but exact part numbers, error codes and rare product names often benefit from lexical retrieval such as BM25. Hybrid search combines both candidate lists, commonly through rank fusion or calibrated score combinations. Raw scores from unrelated retrievers should not be mixed without understanding their distributions. Evaluate separate query categories—identifiers, natural language, multilingual phrasing—rather than relying only on one aggregate recall number.

Distinctions that matter in designCosine: directional similarityDot product: scale-sensitiveRecall@k: evidence coverageMRR/nDCG: ranking quality
Figure 2. Similarity measures, exact product-code matching and retrieval quality are not interchangeable.

What do Recall@k, MRR and nDCG tell us?

A retrieval metric depends on a clear definition of which documents are relevant to each question. Recall@k describes evidence found in the first k results, MRR emphasises the first relevant rank, and nDCG accounts for graded relevance. High Recall@20 is not sufficient when the generator receives only three chunks. What matters is whether the evidence enters the context the model actually sees. Independently labelled queries provide a common reference for that distinction.

How should multilingual and out-of-domain queries be tested?

Cross-language retrieval—such as answering a Turkish maintenance question from English manuals—is a useful reason to choose multilingual embeddings. A multilingual label does not imply equal quality for every language pair. Test abbreviations, industry jargon, typos and newly introduced part names separately. Also test unanswerable queries: when the archive contains no relevant passage, the system should not force a misleading near neighbor into the answer. Rejection behavior needs to be designed and evaluated alongside relevance.

When should embeddings be updated?

When a document changes, its affected passage embeddings must be updated. After changing an embedding model or tokenizer, old and new vectors should not be assumed compatible in the same index. Migration can use a separate index, shadow queries and a rollback plan. Failing to delete vectors for removed documents creates privacy and misinformation risks. Track document versions and indexing lag so retrieval reflects the intended current corpus. Reliable retrieval is a synchronization problem as much as a vector mathematics problem.

What determines the choice of a search service?

BM25, a single embedding model and hybrid retrieval can behave differently across queries. Product codes, document versions and permissions make those differences easier to interpret on a common question set. Hiding a document in the interface does not resolve access problems if retrieval still returns it. Index-update cost and latency also change with the choice. The meaning of top-k depends not just on documents found, but on how well they support the subsequent answers.

Different wording for the same fault in a maintenance record

Illustrative scenario; not a measured project result.

Suppose one maintenance record says “the engine overheats while idling” and another says “thermal alarm at idle”. Different words may refer to the same type of fault. Semantic retrieval can capture that relationship, but a report for another engine type or an outdated record can still be wrong. Product identity, date and access information complement text similarity. This example concerns a running engine at idle, not a stopped engine.

Similar text is not necessarily the right result

A support question can express the same meaning in different words, while a one-character change in a product code can identify a different part. This is why semantic and lexical retrieval complement each other. A nearby vector must still belong to the right product, document version and permission scope. Changing the embedding model changes not just the vectors but the behaviour of those matches.

Frequently asked questions

When is cosine similarity appropriate?

It is common when the embedding model supports angular similarity and normalization is handled consistently.

Should an embedding model change trigger reindexing?

Usually yes; new vector spaces are not generally compatible with old embeddings.

Is semantic search sufficient on its own?

Exact identifiers and permissions often require lexical search and structured filters alongside vectors.

References and further reading

  1. Sentence-BERT (EMNLP 2019)
  2. BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation
  3. Elastic — BM25 similarity
  4. scikit-learn — User Guide