Skip to content

2.4 The Power of Embeddings: From Text to Meaning

Understanding Embeddings

To explain intuitively what embeddings are, a geographic analogy is convenient. Each text gets coordinates in a multidimensional space, usually hundreds or thousands of dimensions. Texts that are close in meaning end up next to each other. So the question "how do I set up notifications" will be close to a fragment of documentation about configuring alerts, even if they use completely different words.

This very property is what makes semantic search possible. Instead of searching by exact word matches, as in ordinary Ctrl+F, the system searches by meaning. For example, the query "why is the application slow" can lead to an article about performance optimization, even though the wording in the two differs noticeably.

An embedding model converts text into a vector of fixed dimensionality. For popular models this can be a vector of 384 to 4096 numbers. Such models are trained on large sets of text pairs: the model learns to place texts with similar meaning close together and, conversely, to push apart texts that are semantically unrelated.

After training, the model can be applied to new texts that were not in the training set. Thanks to this it becomes possible to index fresh documents and search across them.

The idea behind this is shown in Fig. 13.

Figure 13. How embeddings work: from text to meaning.

Figure 13. How embeddings work: from text to meaning.

from openai import OpenAI

client = OpenAI()

def get_embedding(text, model="text-embedding-ada-002"):
    response = client.embeddings.create(
        input=text,
        model=model
    )
    return response.data[0].embedding

embedding = get_embedding("How do I set up notifications?")
print(f"Dimensionality: {len(embedding)}")
print(f"First 5 values: {embedding[:5]}")

The closeness between vectors is usually measured with cosine similarity or Euclidean distance. Cosine similarity shows the angle between vectors: a value of 1 means the same direction, that is, very close meaning; 0 corresponds to orthogonality, when the texts are practically unrelated; -1 means opposite directions.

import numpy as np

def cosine_similarity(vec1, vec2):
    dot_product = np.dot(vec1, vec2)
    norm1 = np.linalg.norm(vec1)
    norm2 = np.linalg.norm(vec2)
    return dot_product / (norm1 * norm2)

emb1 = get_embedding("How do I set up notifications?")
emb2 = get_embedding("Configuring alerts in the application")
emb3 = get_embedding("A recipe for borscht")

print(f"Similarity 1-2: {cosine_similarity(emb1, emb2):.3f}")
print(f"Similarity 1-3: {cosine_similarity(emb1, emb3):.3f}")

Interestingly, the similarity between the question about notifications and the article about alerts will be close to 1 (very similar), while the similarity with the borscht recipe is close to 0 (unrelated).

Semantic Search in Action

Full-text search requires an exact match of words or phrases. If the user searches for "how to request vacation" and the document is titled "Procedure for granting rest days", search will not connect them, because there are almost no words in common.

Semantic search solves this problem. It finds the connection by meaning, regardless of which words are used.

Often the best option is to combine both approaches. Hybrid search uses the results of full-text search (it is fast and works well on very similar texts) and of semantic search (it finds documents related in meaning). Then the results are merged and ranked:

def hybrid_search(query, es_client, vector_store, alpha=0.5):
    es_results = es_client.search(
        index="documents",
        body={"query": {"match": {"content": query}}},
        size=20
    )
    es_scores = {hit["_id"]: hit["_score"] for hit in es_results["hits"]["hits"]}

    query_embedding = get_embedding(query)
    vector_results = vector_store.similarity_search_with_score(
        embedding=query_embedding,
        k=20
    )
    vector_scores = {doc.metadata["id"]: score for doc, score in vector_results}

    all_ids = set(es_scores.keys()) | set(vector_scores.keys())

    combined_scores = {}
    for doc_id in all_ids:
        es_score = normalize_score(es_scores.get(doc_id, 0), es_scores.values())
        vec_score = normalize_score(vector_scores.get(doc_id, 0), vector_scores.values())
        combined_scores[doc_id] = alpha * es_score + (1 - alpha) * vec_score

    ranked_ids = sorted(combined_scores.keys(), key=lambda x: combined_scores[x], reverse=True)

    return ranked_ids[:10]

The alpha parameter controls the balance: 0.5 means equal weight for both methods. If needed, you can give preference to one of them.

Choosing an Embedding Model

Today many embedding models with different characteristics are available. The choice of a specific model depends on the requirements for quality, speed, cost, and the possibility of local deployment. Cloud API models usually deliver high quality and are regularly improved, and the cost of using them often remains relatively low, although it depends on the volume of requests.

Open-source models, in contrast, can be run locally. This is especially important if you work with sensitive data or do not want to depend on external services:

from langchain_community.embeddings import HuggingFaceEmbeddings

embeddings = HuggingFaceEmbeddings(
    model_name="sentence-transformers/all-MiniLM-L6-v2"
)

vectors = embeddings.embed_documents(["text 1", "text 2"])

For Russian there are specialized models trained specifically on Russian-language data. In many cases they show better results on Russian content than universal multilingual solutions.

It is better to choose a model not by impressive numbers on public benchmarks, but by results on a representative sample of your own data. What works excellently in an abstract test is not necessarily the best solution for your particular system.

Normalizing Text Before Embedding

The quality of embeddings depends directly on the quality of the input text. Noise, typos, and inconsistent formatting degrade the result. That is why text is usually brought to a more uniform form before building embeddings:

import re
import unicodedata

def normalize_for_embedding(text):
    text = unicodedata.normalize('NFKC', text)

    text = text.lower()

    text = re.sub(r'\s+', ' ', text)

    text = text.strip()

    return text

There is one important rule here: the same normalization must be applied both to documents during indexing and to user queries during search. If documents are normalized one way and queries another, the embeddings become incomparable, and search quality drops noticeably.

Versioning and the Index

The embedding index is tightly bound to a specific model and to the parameters of its use. If you replace the model, the index has to be rebuilt completely, because the new model will produce entirely different vectors. The same goes for changes to text normalization or to the chunking strategy.

A good practice is to store the index metadata separately: the model version, the splitting parameters, the creation date, a hash of the configuration, and other important characteristics:

import hashlib
import json

def compute_index_config_hash(config):
    config_str = json.dumps(config, sort_keys=True)
    return hashlib.sha256(config_str.encode()).hexdigest()[:12]

index_config = {
    "embedding_model": "text-embedding-3-small",
    "chunk_size": 1000,
    "chunk_overlap": 200,
    "normalize": True,
    "splitter": "recursive"
}

index_version = compute_index_config_hash(index_config)
index_name = f"documents_v{index_version}"

When any parameter changes, a new index is created, and the old one is kept until the new one is confirmed to work. This makes it possible to roll back quickly if something goes wrong.

Building and Storing the Index

For nearest-neighbor search, the vectors are stored in specialized data structures with optimized search algorithms (HNSW, IVF, and others). A brute-force scan works only for small collections.

The general process of building and storing a vector index is shown in Fig. 14.

Figure 14. Building and storing a vector index.

Figure 14. Building and storing a vector index.

LangChain integrates with several popular vector databases. Chroma is well suited to prototyping:

from langchain_community.vectorstores import Chroma

vector_store = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./chroma_db"
)

results = vector_store.similarity_search(
    query="how to set up notifications",
    k=5
)

FAISS is a solution from Meta that runs locally and scales well:

from langchain_community.vectorstores import FAISS

vector_store = FAISS.from_documents(
    documents=chunks,
    embedding=embeddings
)

vector_store.save_local("faiss_index")

loaded_store = FAISS.load_local("faiss_index", embeddings)

FAISS is especially useful in projects where high speed and local operation matter and there are no requirements for distributed storage. If the document collection is large and horizontal scalability is needed, specialized cloud services are usually considered.

Evaluating Search Quality

In practice, embedding quality is evaluated not on its own but through the search task. For this you need a test set consisting of "query — relevant documents" pairs. On its basis you can compute metrics such as accuracy at top-k, MRR, and NDCG.

The general process of such an evaluation is shown in Fig. 15.

Figure 15. Evaluating search quality.

Figure 15. Evaluating search quality.

def evaluate_retrieval(test_cases, vector_store, k=5):
    hits = 0
    reciprocal_ranks = []

    for query, relevant_ids in test_cases:
        results = vector_store.similarity_search(query, k=k)
        result_ids = [doc.metadata["id"] for doc in results]

        if any(rid in relevant_ids for rid in result_ids):
            hits += 1

        for i, rid in enumerate(result_ids):
            if rid in relevant_ids:
                reciprocal_ranks.append(1 / (i + 1))
                break
        else:
            reciprocal_ranks.append(0)

    accuracy_at_k = hits / len(test_cases)
    mrr = sum(reciprocal_ranks) / len(reciprocal_ranks)

    return {
        "accuracy@k": accuracy_at_k,
        "mrr": mrr
    }

Such metrics help you choose embedding models and search parameters based on real results, not only on general benchmarks. This is exactly what lets you make engineering decisions on the basis of data rather than intuition.

Questions for Reflection and Practice

Theoretical questions

  1. Explain the concept of embeddings and how they make it possible to search by meaning rather than by keywords.

  2. How does semantic search differ from full-text search, and when is each one preferable?

  3. How does cosine similarity work, and why is it suitable for measuring the closeness of vectors?

  4. Which text normalization practices matter for embedding quality, and why must normalization be identical for documents and queries?

  5. What criteria should guide the choice of an embedding model, and what trade-offs exist between quality, speed, and cost?

  6. Why is index versioning needed, and how do you organize the transition between versions?

  7. How does hybrid search combine full-text and semantic approaches, and why is it often more effective than either one alone?

  8. What vector databases exist, and how do you choose the right one for a specific project?

  9. How does the dimensionality of embeddings affect search quality and storage requirements?

  10. Which metrics are used to evaluate search and embedding quality?

Practical exercises

  1. Implement a function that obtains embeddings for a list of texts using an embedding service API.

  2. Create a function that computes cosine similarity between two embeddings and test it on semantically close and distant texts.

  3. Compare the quality of several embedding models on a test set of 20–30 query-document pairs.

  4. Build a vector index with FAISS and implement a function that searches for the top-k similar documents.

  5. Implement an index versioning system that stores configuration metadata and supports rollback.

  6. Create a hybrid search that combines the results of full-text and semantic search with a configurable weight.

  7. Implement a search quality evaluation function with accuracy@k and MRR metrics on a test set.