Local document search with Sentence Transformers

Sentence Transformers turns texts into vectors that you can compare in a few lines of Python. This tutorial builds a small semantic search for internal documents that runs on your own machine.

Niklas Schult4 min read

Illustration: A magnet pulls a few matching wooden blocks out of a row, like a search that finds similar items.

What you will have at the end and what you need

At the end you will have a short Python script that embeds three German sample sentences and ranks them against a question by similarity. The approach comes from the Sentence Transformers README, which describes the framework as a way to compute embeddings and use them for semantic search.

The README recommends Python 3.10 or newer, PyTorch 2.2 or newer and transformers v5.0 or newer. You also need a terminal on a machine where you may install Python packages. The documentation does not say how much memory or which hardware you need, so test on the machine you plan to use.

Installing the package and loading a model

The first command installs or updates the library from PyPI. The README lists optional extras such as onnx or train, but the basic search needs none of them. The documentation also points to a separate installation page for uv, conda and source installs, which is useful if your company manages Python environments centrally.

Shell
pip install -U sentence-transformers

The next snippet imports the main class and loads the pretrained model all-MiniLM-L6-v2. The README uses this model in its own embedding example. On the first run the model is fetched from the Hugging Face Hub, so that step needs an internet connection.

Python
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

Embedding documents and ranking them by cosine similarity

The following code defines three sample sentences from an imagined intranet, encodes them and encodes one question. The call to encode returns numpy arrays with one embedding per text. Printing the shape shows how many texts were encoded and how many dimensions each vector has.

Python
docs = [
    "Urlaubsanträge werden über das Personalportal gestellt.",
    "Die Wartung der Presse erfolgt alle sechs Monate.",
    "Reisekosten müssen binnen vier Wochen abgerechnet werden.",
]
doc_emb = model.encode(docs)
query_emb = model.encode(["Wie beantrage ich Urlaub?"])
print(doc_emb.shape)

The method model.similarity compares the question vector with every document vector and returns a tensor of scores. The code then sorts the indices from highest to lowest score and prints each document with its score. The README does not state which similarity function the model uses by default, so check the model card if the exact measure matters to you.

Python
scores = model.similarity(query_emb, doc_emb)[0]
ranking = scores.argsort(descending=True)
for idx in ranking:
    print(f"{scores[idx]:.3f}  {docs[idx]}")

How to check that it works

For the three sample texts the shape printed in the previous step should start with 3. The README example with three sentences prints (3, 384) for this model, so a second number of 384 is the expected value. The leave request sentence should appear at the top of your ranking, because it answers the question about holiday.

The README also shows that identical texts score 1.0000 against themselves. Comparing a few of your own sentences this way gives a quick sense of how the scores behave. A handful of examples is only a smoke test, so a real rollout needs a set of typical questions from your staff and a check of the top results.

Typical pitfalls according to the documentation

The README names a few points that matter in practice. Versions of Python, PyTorch and transformers should meet the stated minimums, otherwise the import or the model loading can fail. The first load downloads the model, and the README mentions that logging in with hf auth login raises the Hugging Face Hub rate limits and gives access to private or gated models.

The all-MiniLM-L6-v2 model is the one the README uses in its examples, and its sample texts are English. The README says the project offers pretrained models for more than 100 languages, so for German documents compare a multilingual model from the model list. The README also states that the repository contains experimental software published to give background on the research.

Where this fits in a company

Once the model files are on disk, the computation runs on your own hardware and the document texts stay on your machine. Someone still has to own the script: updating the package, deciding when to recompute embeddings after documents change, and storing the vectors. Where personal data sits in the documents, involve your data protection officer and, if one exists, the Betriebsrat (works council) before indexing HR material.

A script like this covers retrieval only. Permissions, source citations and answers still need to be built around it. That work is what a platform handles. souveraen.ai is an AI platform for company knowledge from clouditiv GmbH in Auerbach, and it runs either hosted in Germany or on-premise.

For background see local AI, knowledge management with AI, answers with sources and the OpenAI-compatible developer API. The README also lists further application examples such as clustering and paraphrase mining, which reuse the same embeddings and can be tried once the basic search works. It describes a retrieve and re-rank pattern as well, in which a reranker model reorders the first results.

Sources

More articles

All articles

OpenAI Private Inference: Is It Fit for Confidential Data?

OpenAI is testing an offer called Private Inference with first business customers, under which the provider is not meant to see the data it processes. Law firms, public bodies and companies with sensitive files need to know whether this makes ChatGPT services usable for confidential content.

Data protection4 min

Self-host Langfuse for LLM monitoring in your company

Langfuse records prompts, answers and costs of AI applications, and the README describes how to run it on your own infrastructure. This tutorial takes you from an empty machine to a first logged model call.

Tutorial4 min

AI applicant profiles: what employers may use from the web

AI tools can turn social media posts and press articles into an applicant profile within seconds. Employers in Germany need to know which public data the GDPR and the BDSG allow them to use in hiring.

Data protection4 min

Test it with your own documents.

Free for 3 days, then from €24.90 per user per month. Cancellable monthly.

Free for 3 days, then from €24.90 per user per month.Free for 3 days
Try free for 3 days