Skip to content
Vector database engineering on Kubernetes · Chapter 2 of 20 Day 1: Understanding vectors – embeddings, distances and exact search

Day 1: Understanding vectors – embeddings, distances and exact search

Goal: split a real corpus from the Kubernetes documentation into sections, translate them into vectors with the embedding model in the cluster, recompute distance measures, search exactly and record 100 test questions with their exact best hits as the ground truth for the coming days · Duration: about 150 min, of which a good 60 min is waiting time during embedding · Prerequisite: Day 0

State before this chapter

The cluster from Day 0 is running, and Ollama with nomic-embed-text answers in the headquarters. Check at which address the librarian can be reached:

# on vdb1
kubectl -n ollama get service ollama

Expected:

NAME     TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)     AGE
ollama   ClusterIP   10.43.16.22   <none>        11434/TCP   83m

What you see: You need the cluster IP in the CLUSTER-IP column in every program call today. Yours shows a different address – wherever the chapter says 10.43.16.22, insert yours.

Introduction

Before you operate a vector database, you need to know what it actually stores and what it computes. Otherwise you won’t be able to judge later whether a search is “correct”, whether a setting costs quality, or whether 3 GB of RAM for one million entries is a lot or a little.

Today you therefore rebuild, without a database and with only Python and numpy, what a vector database does at its core: translate texts into vectors, measure distances, find the most similar entries. For this you take a real corpus – around 13,000 sections from the Kubernetes documentation – and not toy data. At the end you have three things the whole course needs: the corpus as a text file, its vectors and a ground truth: the exact best ten hits for 100 questions. From Day 4 on, you use it to measure how much a fast search with Qdrant loses compared with the exact one.

Today you will learn:

  • to fetch a text corpus from a Git repository and split it into searchable sections,
  • to translate texts into vectors with the embedding model in the cluster,
  • to recompute cosine, dot product and Euclidean distance and to explain why they deliver the same result for normalized vectors,
  • to search exactly and to measure how the search time grows with the corpus,
  • to record a ground truth for later recall measurements,
  • to find an error in the data preparation that no error message reveals.

Background

The picture of the day: the librarian shelves the books

In the library from Day 0, every book stands where similar books stand. Today the books arrive. The librarian (the embedding model) reads every book and gives it a place in the room: a position with 768 coordinates instead of three. Books on similar topics get places close to each other.

When a reader asks a question, the librarian also reads the question and gives it a place. What is sought, then, are the books that stand closest to this place. For that you need a tape measure – the distance measure – and a way through the shelves:

  • Exact search: You walk along every shelf and measure the distance to every book. The result is guaranteed to be correct, but the walk grows with every new book.
  • Approximate search (ANN): You follow signposts and only look into the aisles that look promising. This is much faster, but it can miss a matching book. You build that from Day 2 on.

Today you walk along every shelf. That is the yardstick against which you measure everything faster.

The terms

Term Meaning In the picture
Vector list of numbers of fixed length, here 768 floating-point numbers place of a book in the room
Dimension number of numbers in the vector number of coordinates
Embedding vector that a model computes from a text place that the librarian assigns
Section (chunk) piece of text that is embedded as one entry one book
Corpus all sections together the library’s holdings
Cosine similarity angle between two vectors, 1 = same direction tape measure that only measures direction
Dot product sum of the products of all coordinates tape measure for direction and length
Euclidean distance straight line between two points distance with a folding rule
Normalize bring a vector to length 1 all books equally far from the entrance
Exact search (kNN) compute the distance to every entry walk along every shelf
ANN approximate nearest neighbours, approximate search search with signposts
Ground truth exact best hits for fixed test questions inventory list against which you check signposts
Recall@10 share of the exact best ten that a search finds how many of the right books the signpost shows

Remember: A vector database stores places in a room and finds the nearest ones. Everything that makes it faster is a shortcut compared with walking along all shelves – and every shortcut is measured against exact search.

Why sections and not whole pages

An embedding sums up an entire text in one vector. On a long page about PersistentVolumes, access modes, expansion, reclaiming and snapshots get mixed up in it – the vector points somewhere into the middle. Short sections on one topic give more precise places. But too short is bad too: a sentence without context tells the model too little. The course uses sections of at most 1,000 and at least 200 characters, split at headings and sentence ends. For operations, one consequence matters above all: the number of sections determines the number of vectors, and that determines storage, load time and search time.

Why two prefixes

nomic-embed-text is trained to mark documents and questions differently: before embedding, sections get search_document:, questions get search_query:. This way the model learns that a short question can match a long section. The prefixes belong to the model – a different model expects different ones or none at all.

Drill 1: Fetching the corpus

Where you are: on vdb1.

What you have afterwards: the English Kubernetes documentation at a fixed state in ~/labor/tag01/k8s-doku.

The Kubernetes documentation is licensed under CC BY 4.0 and lives in the repository kubernetes/website. You only need the English pages under content/en/docs from it – not the translations, images and tools. Git can do exactly that: fetch only part of a repository.

Step 1 – create a working directory.

# on vdb1
mkdir -p ~/labor/tag01
# on vdb1
cd ~/labor/tag01

-p also creates missing parent directories and reports no error if the directory already exists. All commands in this chapter run in ~/labor/tag01.

Step 2 – clone the repository without files.

# on vdb1
git clone --depth 1 --branch release-1.36 --filter=blob:none --sparse https://github.com/kubernetes/website.git k8s-doku
Setting Value Meaning
--depth 1 only the last commit, no history
--branch release-1.36 the branch with the documentation for Kubernetes 1.36 – a fixed state instead of main
--filter=blob:none fetch file contents only when they are needed
--sparse initially check out only the files in the top-level directory
last argument k8s-doku target directory

Expected:

Cloning into 'k8s-doku'...

Step 3 – check out only the English documentation.

# on vdb1
git -C k8s-doku sparse-checkout set content/en/docs
  • -C k8s-doku runs the command as if you were standing in this directory.
  • sparse-checkout set <pfad> specifies which directories appear in the working directory. Only now does Git download the contents of these files.

The command prints nothing.

Step 4 – record the state.

# on vdb1
git -C k8s-doku log -1 --format='%H %cs'
  • log -1 shows only the last commit.
  • --format='%H %cs' prints the full hash (%H) and the date of the commit (%cs, short).

Expected:

1de955ebabe7e17da1ebb4f582635491227f4157 2026-08-26

What you see: This hash names the corpus unambiguously. If you fetch the branch again later, the documentation may have changed – and with it the number and content of the sections. Your hash may be different; the numbers in the chapter will then differ slightly.

Step 5 – look at the size.

# on vdb1
find k8s-doku/content/en/docs -name '*.md' | wc -l
  • find <verzeichnis> -name '*.md' lists all Markdown files below it.
  • wc -l counts the lines, that is, the files.

Expected:

1672
# on vdb1
du -sh k8s-doku/content/en/docs

-s sums the directory up into one number, -h writes it in human-readable form.

Expected:

22M k8s-doku/content/en/docs

Remember: A corpus needs a fixed state. Anyone who embeds “the current documentation” can no longer repeat today’s measurement tomorrow.

Save your progress? Sign up for free

Drill 2: Splitting into sections

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: the file korpus.jsonl with 13,220 sections, one per line.

The Markdown pages contain more than text: front matter, code blocks, shortcodes of the website generator Hugo, and HTML. All of that would confuse the librarian. A small program cleans the pages, splits them at headings and sentence ends and writes each section as a JSON line.

Step 1 – create the program.

# on vdb1
nano korpus.py
~/labor/tag01/korpus.py new file
"""Zerlegt die Kubernetes-Doku in Abschnitte und schreibt sie nach korpus.jsonl."""
import json
import pathlib
import re

QUELLE = pathlib.Path("k8s-doku/content/en/docs")
BEREICHE = {"concepts", "tasks", "tutorials", "setup", "reference"}
HOECHSTENS = 1000   # Zeichen pro Abschnitt
MINDESTENS = 200    # kürzere Reste werden weggelassen


def saeubern(text):
    text = re.sub(r"\A---\n.*?\n---\n", "", text, flags=re.S)   # Kopfdaten der Seite
    text = re.sub(r"`{3}.*?`{3}", "", text, flags=re.S)         # Codeblöcke
    text = re.sub(r'\{\{< *glossary_tooltip text="([^"]*)".*?>\}\}', r"\1", text)  # Begriff behalten
    text = re.sub(r"\{\{[<%].*?[%>]\}\}", "", text)              # übrige Hugo-Kürzel
    text = re.sub(r"<[^>]+>", "", text)                          # HTML-Reste
    text = text.replace("&nbsp;", " ")
    return text


def abschnitte(text):
    titel = ""
    for block in re.split(r"\n(?=#{1,4} )", saeubern(text)):
        zeilen = block.strip().splitlines()
        if zeilen and zeilen[0].startswith("#"):
            titel = re.sub(r" *\{#.*?\}", "", zeilen[0].lstrip("#")).strip()  # ohne {#anker}
            zeilen = zeilen[1:]
        rumpf = re.sub(r"\s+", " ", " ".join(zeilen)).strip()
        stueck = ""
        saetze = re.split(r"(?<=[.!?]) ", rumpf)
        # überlange „Sätze“ (Tabellen, Listen) in Stücke schneiden
        saetze = [s[i:i + HOECHSTENS] for s in saetze for i in range(0, len(s), HOECHSTENS)]
        for satz in saetze:
            if len(stueck) + len(satz) > HOECHSTENS and len(stueck) >= MINDESTENS:
                yield titel, stueck
                stueck = ""
            stueck = (stueck + " " + satz).strip()
        if len(stueck) >= MINDESTENS:
            yield titel, stueck


nummer = 0
with open("korpus.jsonl", "w", encoding="utf-8") as ziel:
    for datei in sorted(QUELLE.rglob("*.md")):
        pfad = datei.relative_to(QUELLE).as_posix()
        bereich = pfad.split("/")[0]
        if bereich not in BEREICHE:
            continue
        for titel, text in abschnitte(datei.read_text(encoding="utf-8")):
            eintrag = {"id": nummer, "bereich": bereich, "pfad": pfad,
                       "titel": titel, "text": text}
            ziel.write(json.dumps(eintrag, ensure_ascii=False) + "\n")
            nummer += 1
print(f"{nummer} Abschnitte geschrieben")

This is how the program works:

Part What it does Why
BEREICHE only five areas of the documentation contribute (guide for documentation authors) and test pages are not Kubernetes knowledge
HOECHSTENS, MINDESTENS limits for the length of a section see “Why sections” in the background
saeubern removes front matter, code blocks, Hugo shortcodes and HTML the model should read sentences, not markup
glossary_tooltip line replaces the shortcode with the term itself otherwise a word is missing in the middle of the sentence – more on this in the diagnosis task
re.split(r"\n(?=#{1,4} )") splits before every heading of levels 1 to 4 a section stays on one topic
remove {#anker} Hugo anchors like {#allow-volume-expansion} from the title the title is later part of the display and the test questions
collect sentences fills a section up to 1,000 characters, then the next one begins boundaries at sentence ends instead of in the middle of a word
cut overlong sentences tables without a period into 1,000-character pieces otherwise a single section with 10,000 characters is created
id sequential number it links section and vector together

Step 2 – run it.

# on vdb1
~/werkbank/bin/python korpus.py

You call the workbench’s Python directly. That way you don’t have to activate the environment and you always know which Python is running.

Expected:

13220 Abschnitte geschrieben

Step 3 – look at a section.

# on vdb1
jq 'select(.id == 1702)' korpus.jsonl

jq reads the file line by line as JSON. select(.id == 1702) outputs only the object whose id field is 1702.

Expected:

{
  "id": 1702,
  "bereich": "concepts",
  "pfad": "concepts/storage/persistent-volumes.md",
  "titel": "Expanding Persistent Volumes Claims",
  "text": "Support for expanding PersistentVolumeClaims (PVCs) is enabled by default. You can expand the following types of volumes: * csi (including some CSI migrated volume types) * flexVolume (deprecated) * portworxVolume (deprecated) You can only expand a PVC if its storage class's `allowVolumeExpansion` field is set to true. To request a larger volume for a PVC, edit the PVC object and specify a larger size. This triggers expansion of the volume that backs the underlying PersistentVolume. A new PersistentVolume is never created to satisfy the claim. Instead, an existing volume is resized. Directly editing the size of a PersistentVolume can prevent an automatic resize of that volume. If you edit the capacity of a PersistentVolume, and then edit the `.spec` of a matching PersistentVolumeClaim to make the size of the PersistentVolumeClaim match the PersistentVolume, then no storage resize happens."
}

What you see: A section on exactly one topic, just under 1,000 characters. pfad and titel are the index card on the book: they are not embedded but stored along with it, so that a hit shows where it comes from. In Qdrant this will later be called the payload.

Step 4 – look at a bad section.

# on vdb1
jq 'select(.id == 5000)' korpus.jsonl

Expected:

{
  "id": 5000,
  "bereich": "reference",
  "pfad": "reference/kubectl/generated/kubectl_label/_index.md",
  "titel": "",
  "text": "-s, --server string The address and port of the Kubernetes API server --storage-driver-buffer-duration duration Default: 1m0s Writes in the storage driver will be buffered for this duration, and committed to the non memory backends as a single transaction --storage-driver-db string Default: \"cadvisor\" database name --storage-driver-host string Default: \"localhost:8086\" database host:port --storage-driver-password string Default: \"root\" database password --storage-driver-secure use secure connection with database --storage-driver-table string Default: \"stats\" table name --storage-driver-user string Default: \"root\" database username --tls-server-name string Server name to use for server certificate validation."
}

What you see: An options table of kubectl label, merged into running text. Such sections are hardly usable for a search by meaning – they stand in the library, but nobody wants to borrow them.

Step 5 – count where the sections come from.

# on vdb1
jq -s 'group_by(.bereich) | map({(.[0].bereich): length}) | add' korpus.jsonl
Setting Meaning
-s reads all lines into one array (slurp)
group_by(.bereich) forms groups with the same area
map({(.[0].bereich): length}) turns each group into an object “area: count”
add merges the objects into one

The pipe characters here belong to the jq language, not to the shell: only one program runs.

Expected:

{
  "concepts": 2623,
  "reference": 8267,
  "setup": 235,
  "tasks": 1747,
  "tutorials": 348
}

What you see: Almost two thirds of all sections (8,267 of 13,220) come from reference – mainly generated API and option pages like the one you just saw. For the course this is intended: a real corpus is never clean, and precisely the many similar reference pages make the search harder later. If you want to save time, remove "reference" from BEREICHE: then in the next drill you embed only a good third of the sections. Your numbers will then differ from those in the book from Drill 4 on.

Remember: Data preparation decides how many vectors are created and how good they are. Operations pays for every section with storage and compute time – including the ones nobody finds.

Save your progress? Sign up for free

Drill 3: How the librarian measures similarity

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: three distance measures recomputed on real vectors.

Before you embed 13,000 sections, you look at four sentences to see what the vectors say. Two sentences are about persistent storage, one about network rules, one about baking bread.

Step 1 – create the program.

# on vdb1
nano aehnlich.py
~/labor/tag01/aehnlich.py new file
"""Vergleicht vier Sätze mit drei Abstandsmaßen."""
import sys

import numpy as np
import requests

OLLAMA = sys.argv[1]
SAETZE = [
    "A PersistentVolume provides storage that outlives the pod.",
    "Data on a persistent volume survives when the container restarts.",
    "A NetworkPolicy controls which pods may talk to each other.",
    "Knead the dough for ten minutes and let it rest.",
]

antwort = requests.post(f"{OLLAMA}/api/embed",
                        json={"model": "nomic-embed-text", "input": SAETZE}, timeout=120)
v = np.array(antwort.json()["embeddings"], dtype=np.float32)

print("Länge jedes Vektors:", np.round(np.linalg.norm(v, axis=1), 4))
print()
print("Kosinus zu Satz 1:  ", np.round(v @ v[0] / (np.linalg.norm(v, axis=1) * np.linalg.norm(v[0])), 3))
print("Skalarprodukt:      ", np.round(v @ v[0], 3))
print("Euklidischer Abstand:", np.round(np.linalg.norm(v - v[0], axis=1), 3))
  • requests.post(…/api/embed) sends all four sentences to Ollama in one request; input may be a list.
  • np.linalg.norm(v, axis=1) computes the length of each vector.
  • v @ v[0] is the dot product of each vector with the first one – @ is matrix multiplication in numpy.
  • Cosine = dot product divided by the product of the two lengths.
  • Euclidean distance = length of the difference vector.

The sentences get no prefix here; this is only about comparing them with each other.

Step 2 – run it.

# on vdb1
~/werkbank/bin/python aehnlich.py http://10.43.16.22:11434

The argument is the librarian’s address: cluster IP and port of the Ollama service.

Expected:

Länge jedes Vektors: [1. 1. 1. 1.]

Kosinus zu Satz 1:   [1.    0.779 0.537 0.382]
Skalarprodukt:       [1.    0.779 0.537 0.382]
Euklidischer Abstand: [0.    0.665 0.962 1.112]

What you see:

Sentence Cosine Distance Interpretation
1 PersistentVolume 1 0 the sentence itself
2 persistent volume survives 0.779 0.665 same topic, different words – closest
3 NetworkPolicy 0.537 0.962 also Kubernetes, but a different topic
4 kneading dough 0.382 1.112 nothing in common – farthest away

Three observations:

  1. All vectors have length 1. nomic-embed-text delivers normalized vectors via Ollama.
  2. That is why cosine and dot product are equal. The cosine divides by the lengths – with length 1, that changes nothing.
  3. The Euclidean distance orders the same way. For normalized vectors, distance = √(2 − 2 · cosine). Check it: √(2 − 2 · 0.779) = √0.442 = 0.665.

Sentence 2 shares hardly any words with sentence 1 (“survives” instead of “outlives”, “container restarts” instead of “pod”), but it is the closest. That is exactly the difference from full-text search: meaning is compared. Note also that even the bread sentence still has a cosine of 0.382 and not 0 – there is no fixed value above which something is “similar”. A vector search always returns the nearest entries, even if none really matches.

Remember: For normalized vectors, cosine, dot product and Euclidean distance measure the same order – just in different numbers. In the database, choose the measure the model is built for, and never compare values of different measures.

Save your progress? Sign up for free

Drill 4: Embedding the whole corpus

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: vektoren.npy with 13,220 vectors of 768 numbers each.

Now every section gets its place. The program sends the texts to Ollama in batches of 32 and stores all vectors as one numpy matrix. Row i of the matrix belongs to the section with id i.

Step 1 – create the program.

# on vdb1
nano einbetten.py
~/labor/tag01/einbetten.py new file
"""Bettet alle Abschnitte aus korpus.jsonl ein und speichert die Vektoren in vektoren.npy."""
import json
import sys
import time

import numpy as np
import requests

OLLAMA = sys.argv[1]            # z. B. http://10.43.16.22:11434
MODELL = "nomic-embed-text"
STAPEL = 32                     # Texte pro Anfrage

texte = []
with open("korpus.jsonl", encoding="utf-8") as quelle:
    for zeile in quelle:
        texte.append("search_document: " + json.loads(zeile)["text"])

vektoren = []
beginn = time.time()
for start in range(0, len(texte), STAPEL):
    antwort = requests.post(f"{OLLAMA}/api/embed",
                            json={"model": MODELL, "input": texte[start:start + STAPEL]},
                            timeout=300)
    antwort.raise_for_status()
    vektoren.extend(antwort.json()["embeddings"])
    if start % (STAPEL * 50) == 0:
        print(f"{start + STAPEL:6d} von {len(texte)} nach {time.time() - beginn:5.0f} s", flush=True)

matrix = np.array(vektoren, dtype=np.float32)
np.save("vektoren.npy", matrix)
dauer = time.time() - beginn
print(f"fertig: {matrix.shape[0]} Vektoren mit {matrix.shape[1]} Dimensionen "
      f"in {dauer:.0f} s ({matrix.shape[0] / dauer:.1f} pro Sekunde)")
  • "search_document: " + puts the document prefix in front of every text.
  • STAPEL = 32: one request per text would be slower because every request costs overhead.
  • raise_for_status() aborts immediately on an HTTP error response instead of silently carrying on.
  • dtype=np.float32: 4 bytes per number. This is also the format in which Qdrant stores vectors without quantization.
  • The loop is in the program, not in the shell – you only type one command.

Step 2 – run it and wait.

# on vdb1
~/werkbank/bin/python einbetten.py http://10.43.16.22:11434

Expected (excerpt – beginning and end):

    32 von 13220 nach    10 s
  1632 von 13220 nach   464 s
  3232 von 13220 nach   883 s
  4832 von 13220 nach  1359 s
 11232 von 13220 nach  3320 s
 12832 von 13220 nach  3726 s
fertig: 13220 Vektoren mit 768 Dimensionen in 3828 s (3.5 pro Sekunde)

What you see: Just under 64 minutes for 13,220 sections, 3.5 per second – on 12 CPU cores without a GPU. Leave the terminal open; if the SSH connection drops, the program aborts too. The number is a first capacity figure: a corpus of one million sections would take more than three days with this setup. In production, embedding is therefore often the slowest step when filling the database – not the database itself.

Step 3 – check the result.

# on vdb1
~/werkbank/bin/python -c "import numpy as np; m = np.load('vektoren.npy'); print(m.shape, m.dtype, m.nbytes)"

-c runs the following text as a Python program. shape is the shape of the matrix, dtype the number type, nbytes the size in bytes.

Expected:

(13220, 768) float32 40611840

What you see: 13,220 rows of 768 columns. 13,220 × 768 × 4 bytes = 40,611,840 bytes, a good 38 MiB. That is the raw size of the vectors. Every database needs more: for the index, the index cards and management. How much more, you measure on Day 3 and Day 9.

Remember: A vector with 768 float32 numbers costs 3 KiB before any database touches it. Always calculate capacity like this first: count × dimension × 4 bytes.

Save your progress? Sign up for free

Drill 5: Searching exactly

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: a search over the whole corpus that is guaranteed to deliver the best hits.

Exact search means: the question is embedded and compared with every vector. Because the vectors are normalized, a single matrix multiplication is enough.

Step 1 – create the program.

# on vdb1
nano suche.py
~/labor/tag01/suche.py new file
"""Exakte Suche: vergleicht eine Frage mit jedem Vektor des Bestands."""
import json
import sys
import time

import numpy as np
import requests

OLLAMA, FRAGE = sys.argv[1], sys.argv[2]

eintraege = [json.loads(z) for z in open("korpus.jsonl", encoding="utf-8")]
bestand = np.load("vektoren.npy")
bestand = bestand / np.linalg.norm(bestand, axis=1, keepdims=True)   # auf Länge 1 bringen

antwort = requests.post(f"{OLLAMA}/api/embed",
                        json={"model": "nomic-embed-text", "input": "search_query: " + FRAGE},
                        timeout=60)
frage = np.array(antwort.json()["embeddings"][0], dtype=np.float32)
frage = frage / np.linalg.norm(frage)

beginn = time.perf_counter()
werte = bestand @ frage                     # Kosinus zu allen Einträgen auf einmal
beste = np.argsort(-werte)[:5]              # die fünf größten
dauer = (time.perf_counter() - beginn) * 1000

for i in beste:
    e = eintraege[i]
    print(f"{werte[i]:.3f}  {e['pfad']}  [{e['titel']}]")
print(f"{len(bestand)} Vektoren verglichen in {dauer:.1f} ms")
  • The program normalizes the corpus and the question itself. The vectors from Ollama already have length 1, but a program that relies on this silently delivers wrong values with a different model.
  • "search_query: " is the prefix for questions.
  • bestand @ frage delivers 13,220 cosine values at once.
  • np.argsort(-werte)[:5] sorts in descending order and takes the first five.
  • Only the comparison is measured, not loading the files and not the request to Ollama.

Step 2 – ask a question.

# on vdb1
~/werkbank/bin/python suche.py http://10.43.16.22:11434 "How do I make a persistent volume bigger?"

The second argument is in quotation marks so that the shell passes the question as one argument.

Expected:

0.794  concepts/storage/storage-classes.md  [Volume expansion]
0.794  concepts/storage/persistent-volumes.md  [Expanding Persistent Volumes Claims]
0.768  tutorials/configuration/configure-persistent-volume-storage.md  [Create a PersistentVolumeClaim]
0.743  reference/access-authn-authz/admission-controllers.md  [PersistentVolumeClaimResize]
0.742  concepts/storage/persistent-volumes.md  []
13220 Vektoren verglichen in 39.8 ms

What you see: The question contains neither “expand” nor “resize”, and yet the sections about volume expansion are at the very top – including section 1702 from Drill 2. The first two are so close to each other that, rounded, they have the same value. Even a tiny deviation, for example from a different index, can swap their order; this becomes important on Day 4 when you compare result lists. The last hit has an empty title: it comes from the text before the first heading of the page.

Step 3 – the same question once more.

# on vdb1
~/werkbank/bin/python suche.py http://10.43.16.22:11434 "How do I make a persistent volume bigger?"

Expected:

0.794  concepts/storage/storage-classes.md  [Volume expansion]
0.794  concepts/storage/persistent-volumes.md  [Expanding Persistent Volumes Claims]
0.768  tutorials/configuration/configure-persistent-volume-storage.md  [Create a PersistentVolumeClaim]
0.743  reference/access-authn-authz/admission-controllers.md  [PersistentVolumeClaimResize]
0.742  concepts/storage/persistent-volumes.md  []
13220 Vektoren verglichen in 5.5 ms

What you see: The same hits, but 5.5 instead of 39.8 ms – for exactly the same computation. On the author’s very first run it was even 106 ms. Reasons can be caches, the CPU clock and other load on the VM; from the outside you only see the spread. A single measurement therefore says little – on Day 8 you measure latency as a distribution over many requests.

Remember: Exact search always delivers the right hits because it walks along every shelf. Never measure only once: the first run is almost always the slowest.

Save your progress? Sign up for free

Drill 6: What walking along all shelves costs

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: measured search times for 10,000, 100,000 and 1,000,000 vectors.

5.5 ms for 13,220 vectors sounds like “that’s enough”. But the question in operations is: what happens when the corpus grows? You measure this with random vectors of the same dimension. For the computation time it doesn’t matter whether the numbers come from a model.

Step 1 – create the program.

# on vdb1
nano skalierung.py
~/labor/tag01/skalierung.py new file
"""Misst, wie lange eine exakte Suche bei wachsendem Bestand dauert (Zufallsvektoren)."""
import time

import numpy as np

rng = np.random.default_rng(42)
frage = rng.standard_normal(768).astype(np.float32)

for anzahl in (10_000, 100_000, 1_000_000):
    bestand = rng.standard_normal((anzahl, 768), dtype=np.float32)
    zeiten = []
    for _ in range(20):
        beginn = time.perf_counter()
        werte = bestand @ frage
        np.argpartition(-werte, 10)[:10]
        zeiten.append((time.perf_counter() - beginn) * 1000)
    groesse = bestand.nbytes / 2**20
    print(f"{anzahl:>9,d} Vektoren  {groesse:7.0f} MiB  Median {np.median(zeiten):7.2f} ms pro Suche")
    del bestand
  • default_rng(42): fixed seed so that the random numbers are the same on every run.
  • 20 searches per size, and of those the median – the middle value, insensitive to outliers such as the slow first run.
  • np.argpartition(-werte, 10)[:10] finds the best ten without sorting everything – faster than argsort.
  • del bestand frees the memory before the next size is created. The largest matrix needs almost 3 GiB; vdb1 has enough, smaller VMs don’t.

Step 2 – run it.

# on vdb1
~/werkbank/bin/python skalierung.py

Expected (your times will differ):

   10,000 Vektoren       29 MiB  Median    1.39 ms pro Suche
  100,000 Vektoren      293 MiB  Median   16.41 ms pro Suche
1,000,000 Vektoren     2930 MiB  Median  124.27 ms pro Suche

What you see:

Corpus Memory Time Ratio to the previous row
10,000 29 MiB 1.4 ms –
100,000 293 MiB 16.4 ms ten times as many vectors, almost twelve times as long
1,000,000 2,930 MiB 124 ms ten times as many vectors, a good seven times as long

The time grows roughly linearly with the corpus – with fluctuations, because caches and threads take effect differently at each size. With one million vectors, a single search takes over 120 ms. A program that answers questions one after the other thus manages only eight searches per second. The memory grows exactly linearly: 3 KiB per vector.

Remember: Exact search grows linearly with the corpus. From a few hundred thousand vectors on, you need signposts – an ANN index. You measure its price, a few missed hits, against exact search.

Save your progress? Sign up for free

Drill 7: Recording the ground truth

Where you are: on vdb1, in ~/labor/tag01.

What you have afterwards: 100 test questions with their exact best ten hits in wahrheit.json and the question vectors in fragen.npy.

From Day 2 on, Qdrant searches with an HNSW index. Whether it loses hits in the process, you can only tell if you know what the right hits are. For this, you now define once: 100 questions and for each the exact best ten sections. As questions you take headings from the corpus – they sound like real search queries and cost no manual work.

Step 1 – create the program.

# on vdb1
nano wahrheit.py
~/labor/tag01/wahrheit.py new file
"""Legt 100 Testfragen fest und speichert für jede die exakt besten 10 Treffer."""
import json
import sys

import numpy as np
import requests

OLLAMA = sys.argv[1]

eintraege = [json.loads(z) for z in open("korpus.jsonl", encoding="utf-8")]
bestand = np.load("vektoren.npy")
bestand = bestand / np.linalg.norm(bestand, axis=1, keepdims=True)

# 100 Abschnitte mit Überschrift zufällig, aber wiederholbar auswählen;
# ihre Überschrift wird zur Frage
rng = np.random.default_rng(7)
mit_titel = [e for e in eintraege if len(e["titel"]) > 10]
auswahl = rng.choice(len(mit_titel), size=100, replace=False)
fragen = [mit_titel[i]["titel"] for i in auswahl]

antwort = requests.post(f"{OLLAMA}/api/embed",
                        json={"model": "nomic-embed-text",
                              "input": ["search_query: " + f for f in fragen]}, timeout=300)
fv = np.array(antwort.json()["embeddings"], dtype=np.float32)
fv = fv / np.linalg.norm(fv, axis=1, keepdims=True)

ergebnis = []
for frage, vektor in zip(fragen, fv):
    werte = bestand @ vektor
    beste = np.argsort(-werte)[:10]
    ergebnis.append({"frage": frage, "beste10": [int(i) for i in beste]})

np.save("fragen.npy", fv)
json.dump(ergebnis, open("wahrheit.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(f"{len(ergebnis)} Fragen, erste: {ergebnis[0]['frage']!r} -> {ergebnis[0]['beste10'][:3]}")
  • len(e["titel"]) > 10: only headings with more than ten characters – “Examples” is not a question.
  • rng.choice(…, replace=False) selects 100 different entries; the fixed seed 7 makes the selection repeatable.
  • fragen.npy stores the question vectors. On Day 4 and Day 8 you search Qdrant with them without asking Ollama again – that way you measure the database and not the model.
  • beste10 contains the id of the sections, in descending order of similarity.

Step 2 – run it.

# on vdb1
~/werkbank/bin/python wahrheit.py http://10.43.16.22:11434

Expected:

100 Fragen, erste: 'Query Parameters' -> [9840, 1811, 5091]

Step 3 – look at the file.

# on vdb1
jq -c '{frage: .[1].frage, beste3: .[1].beste10[:3]}' wahrheit.json
  • -c prints the result compactly on one line.
  • .[1] is the second question (counting starts at 0), .beste10[:3] the first three hits.

Expected:

{"frage":"Avoid dependency loops","beste3":[148,787,786]}
# on vdb1
jq -c 'select(.id == 9840) | {pfad, titel}' korpus.jsonl

Expected:

{"pfad":"reference/kubernetes-api/storage/volume-attributes-class-v1.md","titel":"VolumeAttributesClass"}

What you see: The best hit for the question “Query Parameters” is a section from the API reference. Such headings exist there dozens of times with almost the same text. For the ground truth this doesn’t matter: it records what exact search delivers, not what a human considers the best answer. This course does not assess the quality of the model – but it does assess the database’s fidelity to exact search.

Remember: Recall measures how many of the exact best hits a fast search finds. Without a recorded ground truth, you can only guess about the quality of an index.

Save your progress? Sign up for free

Diagnosis task: The vanished word

A colleague has “tidied up” korpus.py. Since then, while looking through the corpus, you notice that some sentences have gaps. There are no error messages.

Symptom: Section 0 looks like this:

"The Concepts section helps you learn about the parts of the Kubernetes system and the abstractions Kubernetes uses to represent your , and helps you obtain a deeper understanding of how Kubernetes works."

Find the cause before you read on. Hint: in the original page there is a Hugo shortcode at the gap.

Solution, step by step. You reproduce the error by rebuilding your colleague’s line:

Step 1 – introduce the error. Open korpus.py and put a # in front of the line with glossary_tooltip so that it becomes a comment.

# on vdb1
nano korpus.py
~/labor/tag01/korpus.py (Auszug: Funktion saeubern) changes in green
def saeubern(text):
    text = re.sub(r"\A---\n.*?\n---\n", "", text, flags=re.S)   # Kopfdaten der Seite
    text = re.sub(r"`{3}.*?`{3}", "", text, flags=re.S)         # Codeblöcke
    # text = re.sub(r'\{\{< *glossary_tooltip text="([^"]*)".*?>\}\}', r"\1", text)  # Begriff behalten
    text = re.sub(r"\{\{[<%].*?[%>]\}\}", "", text)              # übrige Hugo-Kürzel
    text = re.sub(r"<[^>]+>", "", text)                          # HTML-Reste
    text = text.replace("&nbsp;", " ")
    return text

Step 2 – rebuild the corpus.

# on vdb1
~/werkbank/bin/python korpus.py

Expected:

13210 Abschnitte geschrieben

Step 3 – look at section 0.

# on vdb1
jq 'select(.id == 0) | .text' korpus.jsonl

Expected:

"The Concepts section helps you learn about the parts of the Kubernetes system and the abstractions Kubernetes uses to represent your , and helps you obtain a deeper understanding of how Kubernetes works."

Step 4 – count the extent.

# on vdb1
grep -c ' , ' korpus.jsonl

grep -c counts the lines in which the pattern occurs – here a comma preceded by a space, the typical trace of a deleted word.

Expected:

139

The cause: At this point the documentation contains {{< glossary_tooltip text="cluster" term_id="cluster" >}}. The line for glossary_tooltip replaces the shortcode with its text. If it is missing, the next line takes effect, which deletes all Hugo shortcodes without replacement – including the word “cluster”. The order of the lines is therefore part of the logic.

Step 5 – repair. Remove the # again so that korpus.py looks as in Drill 2, and rebuild the corpus.

# on vdb1
nano korpus.py
# on vdb1
~/werkbank/bin/python korpus.py

Expected:

13220 Abschnitte geschrieben
# on vdb1
grep -c ' , ' korpus.jsonl

Expected:

75

What you see: 13,220 sections again, and 64 fewer gaps. The remaining 75 are further gaps left by other shortcodes: glossary_tooltip without text=, only with term_id (“Addons use Kubernetes resources (, , etc)”), and version shortcodes like {{< skew currentVersion >}} (“For Kubernetes , two control plane components”). The course deliberately leaves them: fixing them would mean re-embedding the whole corpus for an hour, and for operating the database a few missing words change nothing. If you want to fix them – it’s a good exercise – do it before Drill 4.

More important than the word is the number: with the error, 13,210 instead of 13,220 sections were created. Because the id is only a sequential number, almost all numbers would be shifted afterwards. Row 1702 in vektoren.npy would then have belonged to a completely different text – every search would have shown wrong index cards without an error appearing anywhere.

Remember: Vectors and texts belong together via the ID. If the preparation changes, the corpus and the vectors must be created anew together – otherwise the hits point to the wrong books.

Checkpoint

# on vdb1
ls -lh ~/labor/tag01

Expected (excerpt, date and time will differ):

-rw-rw-r-- 1 ubuntu ubuntu 301K Dec  4 17:20 fragen.npy
drwxrwxr-x 5 ubuntu ubuntu 4.0K Dec  4 16:13 k8s-doku
-rw-rw-r-- 1 ubuntu ubuntu  11M Dec  4 17:19 korpus.jsonl
-rw-rw-r-- 1 ubuntu ubuntu  39M Dec  4 17:18 vektoren.npy
-rw-rw-r-- 1 ubuntu ubuntu  16K Dec  4 17:20 wahrheit.json
# on vdb1
~/werkbank/bin/python -c "import numpy as np; m = np.load('vektoren.npy'); print(m.shape, m.dtype, m.nbytes)"

Expected: (13220, 768) float32 40611840.

# on vdb1
jq 'length' wahrheit.json

Expected: 100.

# on vdb1
~/werkbank/bin/python korpus.py

Expected: 13220 Abschnitte geschrieben – the same number as when embedding. Only then do korpus.jsonl and vektoren.npy match.

Test yourself

  1. Why do cosine and dot product deliver the same values in Drill 3, and when would that not be the case?
  2. A search returns a section with cosine 0.41 as the best hit. Is that an error?
  3. Roughly how much RAM do the raw vectors of 5 million sections with 768 dimensions in float32 need?
  4. Why does suche.py measure the time only for the comparison and not for the whole program run?
  5. You remove "reference" from BEREICHE and rebuild korpus.jsonl, but don’t re-embed. What happens on the next search?
  6. Why does wahrheit.py store the question vectors in a separate file?

Answers:

  1. Because all vectors have length 1: the cosine is the dot product divided by the product of the lengths, and that is 1. With non-normalized vectors, the lengths enter into the dot product – a long vector then appears “more similar” even though the direction doesn’t match better.
  2. Not necessarily. A vector search always returns the nearest entries, even if none matches. Whether 0.41 is good or bad depends on the model; in the lab even the bread sentence still had 0.382. For “no matching answer”, the application needs its own threshold, measured on real questions.
  3. 5,000,000 × 768 × 4 bytes = 15,360,000,000 bytes, a good 14 GiB – just for the raw data, without index and payload.
  4. So that the number contains only what a database has to deliver: the comparison. Loading the files and the request to the model depend on the disk and Ollama and would mask the measurement.
  5. korpus.jsonl then has around 5,000 lines, vektoren.npy still 13,220. Depending on the program, there is an index error (hit ID greater than the number of texts) or – worse – hits with wrong texts, because the IDs no longer match.
  6. So that later measurements test only the database. If you ask the model anew every time, you measure its runtime too, and with a different model version the vectors could change slightly – the ground truth would then no longer match exactly.

Interview note

“When do you need a vector database at all – isn’t numpy enough?” – For a few tens of thousands of vectors, an exact in-memory search is enough, as measured today: a few milliseconds. The database pays off when the corpus goes into the hundreds of thousands or millions (exact search grows linearly), when there are constant writes, when you need to filter by metadata, and when fault tolerance, backup and access control are required. A good answer with a number: “With one million vectors of 768 dimensions, an exact search takes over 100 ms for us – too slow for interactive search.”

Enterprise note

In production, the corpus is rarely finished: documents are added, change, are deleted. The preparation therefore runs as a pipeline with stable IDs – for example a hash of path and position instead of a sequential number – so that a changed document replaces only its own vectors. The model is versioned like a dependency: a model change means re-embedding the whole corpus, usually into a new collection that you switch to only once it is complete. Embedding costs the most compute time and runs on GPUs or as a separate, scalable service.

Summary

  • The corpus: 13,220 sections from the Kubernetes documentation (release-1.36, commit 1de955e), almost two thirds of them from the reference.
  • nomic-embed-text delivers normalized vectors with 768 dimensions; cosine, dot product and Euclidean distance then order the same way.
  • Embedding on 12 CPU cores: 3.5 sections per second, a good hour for the corpus.
  • Raw size: 3 KiB per vector, 38 MiB for the corpus.
  • Exact search: 5.5 ms for 13,220 vectors, 124 ms for one million – growing linearly.
  • wahrheit.json and fragen.npy record 100 questions with their exact best ten hits.
  • Texts and vectors belong together via the ID; a changed preparation requires re-embedding.

Commands at a glance

Command Purpose
git clone --depth 1 --branch release-1.36 --filter=blob:none --sparse <url> k8s-doku fetch a repository without contents
git -C k8s-doku sparse-checkout set content/en/docs check out only one directory
git -C k8s-doku log -1 --format='%H %cs' record the state of the corpus
~/werkbank/bin/python korpus.py split the documentation into sections
jq 'select(.id == 1702)' korpus.jsonl look at a section
jq -s 'group_by(.bereich) \| map({(.[0].bereich): length}) \| add' korpus.jsonl count sections per area
~/werkbank/bin/python aehnlich.py <ollama-url> compare distance measures
~/werkbank/bin/python einbetten.py <ollama-url> embed the whole corpus
~/werkbank/bin/python suche.py <ollama-url> "<question>" search exactly
~/werkbank/bin/python skalierung.py measure search time with a growing corpus
~/werkbank/bin/python wahrheit.py <ollama-url> record the ground truth for recall
grep -c ' , ' korpus.jsonl count traces of deleted words

Contents

More