Learn how embeddings power semantic search, what similarity scores mean and how to test retrieval with a runnable example and a small document collection.
Learn how embeddings power semantic search, what similarity scores mean and how to test retrieval with a runnable example and a small document collection.
A person searches a help center for “stop the monthly charge,” while the relevant article is called “Cancel a subscription.” The words differ, but the task is related. Embeddings help software find that kind of relationship by turning content into numerical representations that can be compared.
The same idea supports document retrieval, recommendation, clustering and parts of retrieval-augmented generation. It is powerful, but a nearby vector is not proof that a document answers the question, states the truth or is available to the person searching. Those checks belong to the larger retrieval workflow.
This guide explains embeddings from the representation to the search result, then shows how to test a small collection. It includes a runnable cosine-similarity example with deliberately invented vectors. That example teaches the calculation; it does not pretend that hand-picked numbers are the output of an embedding model.
An embedding is a vector, or ordered list of numbers, produced to represent an input in a model’s learned space. A text input can be a word, sentence, passage or document. Other embedding models can represent images, audio or combinations of modalities.
The training objective shapes which relationships the representation captures. A model trained for retrieval is not interchangeable with every model that happens to output a vector. Even with a suitable model, “similar” depends on the task: two passages can discuss the same topic while giving opposite instructions.
Do not think of each coordinate as a readable label such as “billing” or “science.” Learned representations usually distribute information across many dimensions. The useful interpretation comes from how the model was trained and how comparisons perform on real examples, not from assigning a story to an individual number.
The Sentence-BERT paper describes sentence representations designed for meaningful similarity comparisons. It is a historical example of learning representations that can be compared efficiently, rather than running a full pairwise language-model comparison for every possible pair in a large collection.
To build a simple semantic search system, divide an approved collection into useful units, encode each unit and store its vector with a stable ID. Retain the original text and metadata separately so a search result can return inspectable content rather than just a list of numbers.
At query time, encode the question with the matching query procedure, compare that vector with the stored document representations and retrieve promising candidates. The query and document encoders must produce compatible representations. Equal vector length alone does not establish compatibility between two different models.
Sentence Transformers’ semantic-search documentation explains why a short question searched against longer passages differs from finding similar questions. Some models use different prompts or routines for queries and documents. Follow the selected model’s intended encoding process rather than assuming all text should be passed through one generic function in the same way.
For a small collection, exact comparison against every stored vector can be practical. At larger scales, an index may use approximate search to trade some retrieval precision for speed or resource savings. The index is a search mechanism; the embedding model defines the representations being searched.
Common comparison measures include cosine similarity, dot product and distance-based measures. Cosine similarity compares the angle between nonzero vectors, while dot product also depends on their magnitudes unless the vectors are normalized. Choose the measure expected by the model and index rather than mixing them casually.
A cosine score is not a calibrated probability that an answer is correct. A score of 0.8 does not mean “80% true” or guarantee that a passage is relevant. Scores vary with the model, data and question, so a threshold chosen for one collection may not work in another.
The following Python 3 example uses three invented two-dimensional vectors. Save it as cosine_demo.py and run python3 cosine_demo.py. It needs only Python’s standard library and does not download a model, call an API or search real documents.
from math import sqrt
def cosine(a, b):
if len(a) != len(b):
raise ValueError("Vectors must have matching dimensions")
norm_a = sqrt(sum(x * x for x in a))
norm_b = sqrt(sum(x * x for x in b))
if norm_a == 0 or norm_b == 0:
raise ValueError("Cosine similarity is undefined for a zero vector")
return sum(x * y for x, y in zip(a, b)) / (norm_a * norm_b)
query = (1.0, 0.0)
invented_vectors = {
"A": (0.8, 0.6),
"B": (0.0, 1.0),
"C": (-1.0, 0.0),
}
scores = [(name, cosine(query, vector))
for name, vector in invented_vectors.items()]
for name, score in sorted(scores, key=lambda item: item[1], reverse=True):
print(f"{name}: {score:.3f}")
The output is A: 0.800, B: 0.000 and C: -1.000. A points closer to the query’s direction than B or C. These are geometric relationships among the invented vectors, not semantic scores for actual sentences. The calculation and ranking have been checked locally.
Real models usually produce many more dimensions, and their score distributions depend on training. You cannot transfer the example’s numbers into a production rule such as “anything above 0.8 is safe to answer.” Determine useful retrieval behavior from a labelled test set for your own task.
Chunking determines what the search system can return. A passage that contains a return deadline but omits the exception in the next paragraph may be incomplete evidence, even if its vector ranks highly. Keep headings, source identity and essential conditions connected to each indexed unit.
Very large chunks can blur several topics together or make the later answer stage consume unnecessary context. Very small chunks can lose the relationship between a rule and its qualification. Start with meaningful sections and inspect the actual retrieved text before tuning a chunk-size number.
Store source URL or file ID, section, version and applicable dates with each record. Where the collection has restricted material, filter candidates using the requesting user’s permissions before returning content to the answering model. Similarity should not decide access rights.
Our RAG comparison guide uses two fictional policy versions to show why selecting the applicable evidence matters. A passage about the right subject can still be wrong for an order placed before a rule changed. Embeddings help find candidates; metadata and application rules help decide which candidates are usable.
Create six short fictional help articles before connecting a large knowledge base. Include instructions for cancelling a subscription, updating a billing address, pausing notifications, exporting a workspace, deleting a workspace and changing the account email. Give each article an ID and keep their actions distinct.
Write questions in ordinary user language. “Stop future charges” should make the cancellation article a candidate, while “stop the email alerts” should point toward notification settings. “Take a copy before closing the workspace” may require both export and deletion information rather than one isolated top result.
Use the embedding model and search tool you are evaluating to retrieve the top few candidates. Record the actual ranked IDs and inspect their text. Do not ask a chat model to invent the scores or simulate a search result and then treat that as a measurement of an embedding system.
RETRIEVAL TEST RECORD
Query ID and exact question
Expected useful article IDs, labelled before running the search
Embedding model, version and query/document encoding procedure
Collection version and chunking rules
Actual top candidate IDs and scores returned by the search tool
Which expected evidence was found and which was missed
Confusing candidates, missing conditions and permission-filter results
Keep observed search output separate from a model's proposed interpretation.
Include a question the collection cannot answer, such as a request for a refund amount when no refund policy was supplied. A vector search can still return something because “nearest” is a relative ranking. The downstream system needs a way to decline or request more information when the evidence does not support an answer.
This is a suggested user-run evaluation, not a reported result from a particular embedding model. Keep the articles and labels fixed while changing one component. That makes a later improvement easier to attribute to the model, chunking or search configuration.
Some questions depend on exact strings: a product code, invoice number, error identifier or unusual name. Dense similarity can complement keyword search, but it should not automatically replace it. A one-character difference may identify a different product even when the surrounding descriptions are almost identical.
Hybrid retrieval combines candidate lists from different retrieval methods. The documentation for reciprocal rank fusion describes one way to combine ranked results without treating the raw scores from different retrievers as if they were directly comparable. This is a design option to evaluate, not a guarantee that adding more retrieval stages will improve every collection.
A reranker can then examine a query and selected candidate passages more closely before deciding their order. That adds computation, so measure whether it improves the evidence returned enough to justify the extra work. Keep the distinction between fast candidate retrieval and a more detailed relevance assessment clear.
Negation and conflicting statements deserve explicit tests. “This plan includes exports” and “this plan does not include exports” share much of their language and topic. A successful system must preserve the condition in the source rather than treating semantic closeness as agreement.
If an assistant gives the wrong answer, inspect the retrieved candidates first. The relevant document may have been missed, filtered incorrectly or outranked by an old version. Separately test what happens when the correct evidence is supplied directly to the answer model.
Use a metric whose meaning you can explain. Suppose ten fictional questions each have one pre-labelled required article, and the top three results contain that article for eight questions. The query-level hit rate at three is 8 out of 10, or 80%. This is another arithmetic example, not a benchmark claim; it also does not measure whether the final answers were correct.
When questions have several relevant articles, use a metric and relevance labels that reflect that situation. Track irrelevant results, missed exceptions and unsupported answers alongside retrieval hits. A high candidate hit rate can coexist with poor answer quality if the generator ignores what it retrieved.
The testing approach in our evaluation guide helps keep comparisons realistic. Include paraphrases, exact identifiers, missing-answer cases and changed policy versions. Review failure examples directly rather than relying only on one average score.
Record the embedding model and its encoding settings with the index. Changing to an incompatible model usually requires re-encoding the stored content and queries into the new space. Do not mix vectors simply because they have the same number of coordinates.
When a document changes, update its relevant chunks and remove obsolete entries under a defined versioning policy. A correct current document can coexist with an old indexed copy if the update process only appends records. Keep stable source IDs so you can reconcile updates rather than accumulating silent duplicates.
Treat stored vectors and their metadata as part of the data system’s security and retention design. Do not assume a numerical representation makes restricted content appropriate for unrestricted sharing. The original text, identifiers and permission filters remain important even when search primarily operates on vectors.
Embeddings are useful because they turn learned relationships into a form software can search efficiently. They are one stage in a larger process: define the task, prepare the content, encode consistently, retrieve candidates and verify the evidence. Once those stages are visible, it becomes easier to build semantic search that helps users find the right information rather than merely the nearest-looking result.
Disclaimer: AIstify is an independent media brand owned and operated by NuvexMedia LLC, publishing news, research, and insights on artificial intelligence, emerging technologies, automation, and related industries. NuvexMedia LLC invests in and collaborates with companies across the AI, technology, software, and digital innovation sectors. These relationships do not influence AIstify’s editorial coverage, and the publication maintains full editorial independence to provide accurate, timely, and objective information. © 2026 NuvexMedia LLC. All rights reserved. This content is for informational purposes only and should not be considered legal, tax, investment, financial, or other professional advice.
Trump says SEC Chair Paul Atkins will make “Super Intelligence” mandatory, extending his push to rename AI without specifying the scope or timing.