Day 6: The Ingestion Pipeline – the Intake Desk
Goal: Load documents, clean them, split them into cards, stamp them and store them in Qdrant – as a Kubernetes job that duplicates nothing on its second run and replaces changed cards · Duration: approx. 90 min · Prerequisite: Day 5
State before this chapter
# on rag1
kubectl -n rag get deploy embed statefulset/qdrantExpected: both with READY 1/1.
# on rag1
curl -s http://127.0.0.1:6333/Expected: Qdrant’s answer with
"version":"1.20.3". If nothing comes back, restart the
port-forward from Day 4 in the second terminal.
Introduction
Until now you wrote cards by hand and classified them individually. A real knowledge system receives whole books: manuals, documentation, wiki pages – with formatting, comments, links and headings. Someone has to unpack them, tidy them up, split them into handy cards, stamp every card and classify it. And when a page changes tomorrow, only the changed card should be created anew.
This intake desk is called the ingestion pipeline. Today you build it: a small Python program without third-party libraries that runs as a Kubernetes job. You see how long classifying really takes, why a second run is done in 0.2 seconds – and how you can trip yourself up along the way.
Today you learn:
- to assemble a corpus of freely licensed texts with a pinned version,
- to clean Markdown and split it by headings into cards with overlap,
- to stamp cards with metadata (source, section, licence),
- to make the pipeline idempotent: a card ID from a hash over everything that determines the vector,
- to run the pipeline as a job with ConfigMaps,
- to create a payload index for filters.
Background
The picture for today: the library’s intake desk
New books arrive in boxes at the intake desk. There they are unpacked, and flyers and delivery notes are thrown out (cleaning). Then someone writes index cards: one card per thought, with the chapter heading on top so that later you know what it is about. So that no thought is torn apart at a card boundary, the last paragraph of a card also appears on the next one (overlap). Every card gets stamps: from which book, which section, under which licence.
The intake desk keeps an accession register: for every card it notes a fingerprint. If the same box arrives again, it checks the register – “we already have that” – and files nothing twice. If a page is reprinted, only its card gets a new fingerprint; the old card is taken out of the cabinet.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Corpus | all documents the system should know | the delivered books |
| Ingestion | loading, cleaning, splitting, embedding, storing | intake desk |
| Chunk | a piece of text that gets embedded | an index card |
| Overlap | text that appears on two neighbouring chunks | last paragraph also on the next card |
| Metadata | source, section, licence … in the payload | stamps |
| Idempotent | running twice gives the same result as running once | accession register |
| Content hash | fingerprint from the content; same content, same hash | fingerprint in the accession register |
| Job | Kubernetes resource for work that runs once and ends | a shift at the intake desk |
Remember: A pipeline that re-embeds everything on every run costs the full computing time on every run. The fingerprint of every card makes the second run almost free.
Drill 1: Delivering the books
Where you are: on rag1.
What you have afterwards: nine files in the folder
~/kurs/06/korpus: five pages of the Kubernetes documentation and the four cards of the practice company.
Step 1 – the folder.
# on rag1
mkdir -p ~/kurs/06/korpus-p also creates ~/kurs/06.
# on rag1
cd ~/kurs/06Step 2 – the documentation with a pinned version. The Kubernetes documentation is licensed under CC BY 4.0 and is available as Markdown on GitHub. You download it from a fixed commit so that your cards match exactly this course. The URL is long; two variables make it manageable:
# on rag1
C=5cea26e314a6a876863a65456c7599f6480b3a95# on rag1
U=https://raw.githubusercontent.com/kubernetes/website/$C/content/en/docs/conceptsC is the commit ID in the repository
kubernetes/website, U the path to the concept
pages in this commit. The variables only apply in this terminal.
Step 3 – download five pages. One command per page:
# on rag1
curl -sf -o korpus/k8s-configmap.md $U/configuration/configmap.md| Option | Meaning |
|---|---|
-s |
no progress display |
-f |
on an HTTP error (such as 404) save nothing and exit with an error |
-o korpus/k8s-configmap.md |
target file; the pipeline later recognises the licence by the prefix
k8s- |
# on rag1
curl -sf -o korpus/k8s-secret.md $U/configuration/secret.md# on rag1
curl -sf -o korpus/k8s-pod-qos.md $U/workloads/pods/pod-qos.md# on rag1
curl -sf -o korpus/k8s-taint-and-toleration.md $U/scheduling-eviction/taint-and-toleration.md# on rag1
curl -sf -o korpus/k8s-pod-lifecycle.md $U/workloads/pods/pod-lifecycle.mdStep 4 – add the practice company’s cards.
# on rag1
cp ../01/karte-*.txt korpus/# on rag1
ls -l korpusExpected (excerpt – the documentation pages; the
four karte-*.txt come on top):
-rw-rw-r-- 1 ubuntu ubuntu 12932 Dec 1 20:48 k8s-configmap.md
-rw-rw-r-- 1 ubuntu ubuntu 46643 Dec 1 20:48 k8s-pod-lifecycle.md
-rw-rw-r-- 1 ubuntu ubuntu 12110 Dec 1 20:48 k8s-pod-qos.md
-rw-rw-r-- 1 ubuntu ubuntu 32981 Dec 1 20:48 k8s-secret.md
-rw-rw-r-- 1 ubuntu ubuntu 18885 Dec 1 20:48 k8s-taint-and-toleration.md
Step 5 – what a book in the box looks like.
# on rag1
head -24 korpus/k8s-pod-qos.mdExpected (excerpt – the beginning and the lines with link and shortcode):
---
title: Pod Quality of Service Classes
content_type: concept
weight: 85
---
<!-- overview -->
This page introduces _Quality of Service (QoS) classes_ in Kubernetes, and explains
[resource requests](/docs/concepts/configuration/manage-resources-containers/)
of the {{< glossary_tooltip text="Containers" term_id="container" >}} in that Pod, along with
What you see: between the two --- lines
is the front matter with the title. On top of that come HTML comments
(such as the overview marker above), links
([text](address)) and Hugo shortcodes
({{< … >}}), with which the website builds in
tooltips. For embedding this is noise: a model should read “Containers”,
not glossary_tooltip.
Remember: Licence and version belong to the corpus just like the texts themselves. Whoever later asks where an answer comes from needs both.
Save your progress? Sign up for free
Drill 2: The intake desk as a program
Where you are: on rag1, in
~/kurs/06.What you have afterwards:
ingest.py– the whole pipeline in one file, using only Python’s standard library.
Step 1 – the program. Identifiers and comments are in German, as in the rest of the course code; the table in step 2 explains every part.
# on rag1
nano ingest.py"""Annahmestelle: Dokumente laden, säubern, in Karten teilen, einbetten, in Qdrant ablegen."""
import hashlib
import json
import os
import pathlib
import re
import sys
import time
import urllib.request
import uuid
KORPUS = pathlib.Path(os.environ.get("KORPUS", "/korpus"))
EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
MAX_ZEICHEN = int(os.environ.get("MAX_ZEICHEN", "1000"))
STAPEL = 16
def anfrage(methode, url, daten=None):
body = json.dumps(daten).encode() if daten is not None else None
req = urllib.request.Request(
url, data=body, method=methode, headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=300) as antwort:
return json.load(antwort)
def saeubern(text):
"""Front Matter, Kommentare, Hugo-Shortcodes und Links entfernen; Titel zurückgeben."""
titel = None
kopf = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL)
if kopf:
t = re.search(r"^title:\s*(.+)$", kopf.group(1), re.MULTILINE)
titel = t.group(1).strip().strip('"') if t else None
text = text[kopf.end() :]
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
text = re.sub(
r'\{\{<\s*glossary_tooltip[^>]*?text="([^"]+)"[^>]*>\}\}', r"\1", text
)
text = re.sub(r"\{\{[<%].*?[%>]\}\}", "", text, flags=re.DOTALL)
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return titel, text.strip()
def karten(titel, text):
"""Nach Überschriften trennen, Absätze bis MAX_ZEICHEN bündeln, letzter Absatz als Überlappung."""
abschnitt, absaetze, ergebnis = titel, [], []
def abschliessen():
if absaetze:
ergebnis.append((abschnitt, "\n\n".join(absaetze)))
for absatz in re.split(r"\n\s*\n", text):
absatz = absatz.strip()
if not absatz:
continue
ueberschrift = re.match(r"^#{1,4}\s+(.+)$", absatz)
if ueberschrift:
abschliessen()
abschnitt, absaetze = (
re.sub(r"\s*\{#[^}]*\}", "", ueberschrift.group(1)).strip(),
[],
)
continue
if absaetze and len("\n\n".join(absaetze)) + len(absatz) > MAX_ZEICHEN:
abschliessen()
absaetze = [absaetze[-1]] if len(absaetze[-1]) < MAX_ZEICHEN // 2 else []
absaetze.append(absatz)
abschliessen()
return ergebnis
def eingabe(titel, abschnitt, text):
"""Genau dieser Text wird eingebettet."""
return f"{titel} – {abschnitt}\n{text}"
def punkt_id(quelle, text):
"""Hash über alles, was den Vektor bestimmt: Modell, Quelle und eingebetteter Text."""
return str(
uuid.UUID(
hashlib.sha256(f"{MODELL}\n{quelle}\n{text}".encode()).hexdigest()[:32]
)
)
def vorhandene(ids):
antwort = anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points",
{"ids": ids, "with_payload": False, "with_vector": False},
)
return {p["id"] for p in antwort["result"]}
def einbetten(texte):
antwort = anfrage("POST", f"{EMBED}/api/embed", {"model": MODELL, "input": texte})
return antwort["embeddings"]
def main():
start = time.time()
zaehler = {"dokumente": 0, "karten": 0, "neu": 0, "unveraendert": 0, "geloescht": 0}
for datei in sorted(KORPUS.iterdir()):
if datei.name.startswith(".") or datei.suffix not in (".md", ".txt"):
continue
titel, text = saeubern(datei.read_text(encoding="utf-8"))
titel = titel or text.split(":", 1)[0]
lizenz = (
"CC BY 4.0, kubernetes.io"
if datei.name.startswith("k8s-")
else "Übungsfirma"
)
liste = karten(titel, text)
punkte = []
for nr, (abschnitt, inhalt) in enumerate(liste):
punkte.append(
{
"id": punkt_id(datei.name, eingabe(titel, abschnitt, inhalt)),
"payload": {
"quelle": datei.name,
"titel": titel,
"abschnitt": abschnitt,
"nr": nr,
"lizenz": lizenz,
"text": inhalt,
},
}
)
alt = vorhandene([p["id"] for p in punkte])
neu = [p for p in punkte if p["id"] not in alt]
for i in range(0, len(neu), STAPEL):
stapel = neu[i : i + STAPEL]
vektoren = einbetten(
[
eingabe(
p["payload"]["titel"],
p["payload"]["abschnitt"],
p["payload"]["text"],
)
for p in stapel
]
)
for p, v in zip(stapel, vektoren):
p["vector"] = v
anfrage(
"PUT",
f"{QDRANT}/collections/{SAMMLUNG}/points?wait=true",
{"points": stapel},
)
# Karten dieser Quelle, die es nicht mehr gibt, entfernen
filter_ = {
"must": [{"key": "quelle", "match": {"value": datei.name}}],
"must_not": [{"has_id": [p["id"] for p in punkte]}],
}
zaehl = anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points/count",
{"filter": filter_, "exact": True},
)["result"]["count"]
if zaehl:
anfrage(
"POST",
f"{QDRANT}/collections/{SAMMLUNG}/points/delete?wait=true",
{"filter": filter_},
)
zaehler["dokumente"] += 1
zaehler["karten"] += len(punkte)
zaehler["neu"] += len(neu)
zaehler["unveraendert"] += len(punkte) - len(neu)
zaehler["geloescht"] += zaehl
print(
f"{datei.name}: {len(punkte)} Karten, {len(neu)} neu, {zaehl} gelöscht",
flush=True,
)
ergebnis = {**zaehler, "sekunden": round(time.time() - start, 1)}
print(json.dumps(ergebnis, ensure_ascii=False), flush=True)
if __name__ == "__main__":
sys.exit(main())Step 2 – what the parts do. Read the program from top to bottom with this table next to it:
| Part | What it does | in the picture |
|---|---|---|
| Constants at the top | addresses of the embedding service and Qdrant, name of the
collection (SAMMLUNG), model, card size
(MAX_ZEICHEN); all changeable via environment
variables |
house rules |
anfrage (request) |
an HTTP request with JSON there and back, with urllib
from the standard library |
telephone |
saeubern (clean) |
read the title from the front matter; remove comments, shortcodes (tooltips keep their text) and link addresses | unpacking, flyers out |
karten (cards) |
split at headings and remove their Hugo anchors such as
{#pod-termination}; bundle paragraphs until 1000 characters
are reached; carry the last paragraph over to the next card if it is
shorter than 500 characters |
writing cards with overlap |
eingabe (input) |
the text that is actually embedded: title – section, then the card | heading on top of the card |
punkt_id (point ID) |
SHA-256 over model, source and embedded text, shortened to a UUID | fingerprint |
vorhandene (existing) |
asks Qdrant which of these IDs already exist | look into the accession register |
einbetten (embed) |
16 cards at once to /api/embed |
classifying |
main |
per file: clean, split, stamp, embed and store only new cards, then delete cards of the same source that no longer occur | one shift |
Three decisions deserve a second look:
- The heading is embedded too. The idea: a card “They may not acquire resources beyond their specified limits” says little on its own; with “Pod Quality of Service Classes – Guaranteed” in front of it, the model is meant to know what it is about. This is common advice – but an assumption. Whether it improves the hits in this corpus is what you measure on Day 7.
- The ID is a content hash. The same text always
gives the same ID. That is why
vorhandenecan ask before the expensive embedding whether the card already exists. - Cleaning up through a filter. After storing, the
program deletes all points with
quelle = <file>(quelleis the source stamp) whose ID is not in the new list (must_notwithhas_id). This is how the old cards of a changed page disappear.
Remember: The fingerprint of a card must contain everything that determines its vector – text, heading and model. If any of that is missing, the pipeline does not recognise changes.
Save your progress? Sign up for free
Drill 3: The new cabinet
Where you are: on rag1, in
~/kurs/06.What you have afterwards: the collection
wissen(knowledge) with an index on the stampquelle.
Step 1 – the collection.
# on rag1
curl -s -X PUT http://127.0.0.1:6333/collections/wissen -H 'Content-Type: application/json' -d '{"vectors":{"size":1024,"distance":"Cosine"}}'Expected:
{"result":true,"status":"ok","time":0.136433475}
Step 2 – an index on the stamp. The pipeline filters
by quelle for every file. A payload index makes such
filters fast, like a register on the card cabinet:
# on rag1
curl -s -X PUT 'http://127.0.0.1:6333/collections/wissen/index?wait=true' -H 'Content-Type: application/json' -d '{"field_name":"quelle","field_schema":"keyword"}'| Option | Meaning |
|---|---|
…/collections/wissen/index |
create a payload index of the collection |
"field_name":"quelle" |
for the field quelle |
"field_schema":"keyword" |
as a keyword: exact comparison of whole values |
Expected:
{"result":{"operation_id":2,"status":"completed"},"status":"ok","time":0.122836644}
Remember: The HNSW index orders the vectors, a payload index orders the stamps. Fields you filter by get one.
Save your progress? Sign up for free
Drill 4: The first shift – the pipeline as a job
Where you are: on rag1, in
~/kurs/06.What you have afterwards: all 173 cards in
wissen– classified by a job in the cluster.
Step 1 – program and corpus into the cluster. The job needs the program and the documents. Each goes into a ConfigMap of its own:
# on rag1
kubectl -n rag create configmap ingest-code --from-file=ingest.py# on rag1
kubectl -n rag create configmap korpus --from-file=korpus/--from-file=korpus/ turns every file in the folder into
an entry of the ConfigMap. Together they are about 124,000 characters. A
ConfigMap may be at most 1 MiB in size – incidentally, that is written
on one of the pages you are classifying right now. Larger corpora belong
on a volume or in object storage.
Step 2 – the manifest.
# on rag1
nano ingest-job.yamlapiVersion: batch/v1
kind: Job
metadata:
name: ingest
namespace: rag
spec:
backoffLimit: 1
ttlSecondsAfterFinished: 86400
template:
spec:
restartPolicy: Never
containers:
- name: ingest
image: python:3.14.10-slim-trixie
command: ["python", "/code/ingest.py"]
env:
- name: SAMMLUNG
value: wissen
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 256Mi
volumeMounts:
- name: code
mountPath: /code
- name: korpus
mountPath: /korpus
volumes:
- name: code
configMap:
name: ingest-code
- name: korpus
configMap:
name: korpus| Setting | Meaning |
|---|---|
kind: Job |
runs once until it finishes, instead of permanently like a deployment |
backoffLimit: 1 |
on an error, retry at most once |
ttlSecondsAfterFinished: 86400 |
clean up the finished job by itself after one day |
restartPolicy: Never |
do not restart a failed container in the same pod |
image: python:3.14.10-slim-trixie |
slim Python image with a pinned version; the program needs nothing more |
env SAMMLUNG |
the collection that is written to |
resources |
little CPU, memory limited – the embedding service does the work |
volumeMounts / volumes |
the two ConfigMaps as the folders /code and
/korpus |
The program defaults to http://embed.rag:11434 and
http://qdrant.rag:6333: inside the cluster, the job talks
to the services directly, without a port-forward.
Step 3 – the shift begins.
# on rag1
date +%T# on rag1
kubectl apply -f ingest-job.yamlExpected:
job.batch/ingest created
# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest --timeout=900sExpected:
job.batch/ingest condition met
# on rag1
date +%TIn the lab from 21:00:32 to 21:04:44 – a good four minutes.
Step 4 – what the shift reports.
# on rag1
kubectl -n rag logs job/ingestExpected (per file: cards, new, deleted –
Karten, neu, gelöscht):
k8s-configmap.md: 17 Karten, 17 neu, 0 gelöscht
k8s-pod-lifecycle.md: 64 Karten, 64 neu, 0 gelöscht
k8s-pod-qos.md: 18 Karten, 18 neu, 0 gelöscht
k8s-secret.md: 43 Karten, 43 neu, 0 gelöscht
k8s-taint-and-toleration.md: 27 Karten, 27 neu, 0 gelöscht
karte-backup.txt: 1 Karten, 1 neu, 0 gelöscht
karte-druck.txt: 1 Karten, 1 neu, 0 gelöscht
karte-urlaub.txt: 1 Karten, 1 neu, 0 gelöscht
karte-vpn.txt: 1 Karten, 1 neu, 0 gelöscht
{"dokumente": 9, "karten": 173, "neu": 173, "unveraendert": 0, "geloescht": 0, "sekunden": 246.6}
What you see: 173 cards in 246.6 seconds – about 1.4 seconds per card. Almost all of the time, the embedding service is computing on the CPU. Extrapolated, 10,000 cards would take almost four hours on this hardware.
# on rag1
kubectl -n rag get pods -l job-name=ingest -o wideExpected (excerpt – cut off on the right):
NAME READY STATUS RESTARTS AGE IP NODE
ingest-cn78r 0/1 Completed 0 4m12s 10.42.1.15 rag2
The pod is finished (Completed) and stays around so that
you can read the logs.
Remember: Embedding is the expensive part of the intake desk. Everything that makes the pipeline smarter aims at re-embedding as few cards as possible.
Save your progress? Sign up for free
Drill 5: The second shift – nothing twice
Where you are: on rag1, in
~/kurs/06.What you have afterwards: proof that the pipeline is idempotent – and that it recognises changes.
Step 1 – the same job once more. You do not restart a finished job; you delete it and create it again:
# on rag1
kubectl -n rag delete job ingest# on rag1
kubectl apply -f ingest-job.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest --timeout=900s# on rag1
kubectl -n rag logs job/ingestExpected (excerpt – the last two lines):
karte-vpn.txt: 1 Karten, 0 neu, 0 gelöscht
{"dokumente": 9, "karten": 173, "neu": 0, "unveraendert": 173, "geloescht": 0, "sekunden": 0.2}
What you see: 0.2 seconds instead of 246. All
fingerprints were already in the accession register
(unveraendert means unchanged).
Step 2 – a page is reprinted. The print server is
now called druck02:
# on rag1
nano korpus/karte-druck.txtDruckdienst neu starten: Melde dich am Druckserver druck02 an und führe sudo systemctl restart cups aus. Prüfe danach mit lpstat -r, ob der Dienst läuft. Hängen Aufträge, leere die Warteschlange mit cancel -a.Step 3 – renew the ConfigMap. create
only creates new ones; so delete the old one and create it again:
# on rag1
kubectl -n rag delete configmap korpus# on rag1
kubectl -n rag create configmap korpus --from-file=korpus/Step 4 – the third shift.
# on rag1
kubectl -n rag delete job ingest# on rag1
kubectl apply -f ingest-job.yaml# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest --timeout=900s# on rag1
kubectl -n rag logs job/ingestExpected (excerpt – the last four lines):
karte-druck.txt: 1 Karten, 1 neu, 1 gelöscht
karte-urlaub.txt: 1 Karten, 0 neu, 0 gelöscht
karte-vpn.txt: 1 Karten, 0 neu, 0 gelöscht
{"dokumente": 9, "karten": 173, "neu": 1, "unveraendert": 172, "geloescht": 1, "sekunden": 1.2}
What you see: exactly one card was re-embedded, the old one removed. 173 cards remain.
Step 5 – the new card in the cabinet.
# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/scroll -H 'Content-Type: application/json' -d '{"filter":{"must":[{"key":"quelle","match":{"value":"karte-druck.txt"}}]},"with_payload":true}' -o druck.json| Option | Meaning |
|---|---|
…/points/scroll |
page through points, without a search |
filter.must with quelle |
only points with this stamp |
"with_payload":true |
return all stamps |
# on rag1
jq '.result.points[0] | {id, payload: (.payload | .text |= .[0:70])}' druck.json.text |= .[0:70] shortens only the text to 70 characters
so that the output stays readable.
Expected:
{
"id": "d4d25b67-bc51-83dc-af11-e456c6fe226d",
"payload": {
"quelle": "karte-druck.txt",
"titel": "Druckdienst neu starten",
"abschnitt": "Druckdienst neu starten",
"nr": 0,
"lizenz": "Übungsfirma",
"text": "Druckdienst neu starten: Melde dich am Druckserver druck02 an und führ"
}
}
Remember: Idempotent means: the pipeline may run at any time, after every commit, every night. It only does what has changed.
Save your progress? Sign up for free
Drill 6: What the librarian finds now
Where you are: on rag1, in
~/kurs/06.What you have afterwards: a German question against English documentation – and an open bill for tomorrow.
Step 1 – wake up the helper pod. The pod
curl from Day 3 only sleeps for one hour
(sleep 3600) and has finished afterwards:
# on rag1
kubectl -n rag get pod curlExpected (if Day 3 was more than an hour ago):
NAME READY STATUS RESTARTS AGE
curl 0/1 Completed 0 73m
A finished pod does not start again. You delete it and create it anew, this time without an expiry:
# on rag1
kubectl -n rag delete pod curl# on rag1
kubectl run -n rag curl --image=curlimages/curl:8.17.0 --restart=Never --overrides='{"spec":{"nodeSelector":{"kubernetes.io/hostname":"rag2"}}}' --command -- sleep infinitysleep infinity sleeps until the pod is deleted.
Everything else is as on Day 3.
# on rag1
kubectl -n rag wait --for=condition=Ready pod/curl --timeout=120sExpected:
pod/curl condition met
Step 2 – classify the question. This time you ask
the embedding service in the cluster, through the helper pod
curl. The question is German (“Which pods are evicted first
when a node runs out of memory?”); the documentation is English, and
bge-m3 is multilingual:
# on rag1
jq -n --arg f "Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?" '{model: "bge-m3", input: [$f]}' > frage-anfrage.json# on rag1
kubectl -n rag exec -i curl -- curl -s embed.rag:11434/api/embed -d @- < frage-anfrage.json > frage-embed.json| Part | Meaning |
|---|---|
exec -i curl -- curl … |
run curl in the pod curl, with input
passed through |
-d @- |
read the request body from standard input |
< frage-anfrage.json |
the input comes from this file on rag1 |
> frage-embed.json |
the response lands in this file on rag1 |
Step 3 – search.
# on rag1
jq '{query: .embeddings[0], limit: 3, with_payload: ["quelle", "abschnitt"]}' frage-embed.json > suche.json# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H 'Content-Type: application/json' -d @suche.json -o treffer.json# on rag1
jq -c '.result.points[] | {score, quelle: .payload.quelle, abschnitt: .payload.abschnitt}' treffer.jsonExpected:
{"score":0.61473,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Pods and fault recovery"}
{"score":0.61206716,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Termination of Pods"}
{"score":0.6078077,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Termination of Pods"}
What you see: the German question finds English
cards – bge-m3 places both languages on the same shelf. But the answer
is somewhere else: the page k8s-pod-qos.md, in the section
“Quality of Service classes”, says that BestEffort pods are
evicted first, then Burstable, and Guaranteed
last. None of these cards is among the first three.
Step 4 – search only in the right page.
# on rag1
jq '{query: .embeddings[0], limit: 3, with_payload: ["quelle", "abschnitt"], filter: {must: [{key: "quelle", match: {value: "k8s-pod-qos.md"}}]}}' frage-embed.json > suche-qos.json# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H 'Content-Type: application/json' -d @suche-qos.json -o treffer-qos.json# on rag1
jq -c '.result.points[] | {score, abschnitt: .payload.abschnitt}' treffer-qos.jsonExpected:
{"score":0.57501614,"abschnitt":"Guaranteed"}
{"score":0.5627321,"abschnitt":"Disabling or rolling back Memory QoS"}
{"score":0.562461,"abschnitt":"Memory QoS with cgroup v2"}
What you see: even within the right page, the card you are looking for is not in front. The pipeline works correctly – the hits are still bad. Whether this is due to the card size, the heading, the language or pure vector search is not something you guess, you measure it: on Day 7 with test questions and hits@k, on Day 8 with hybrid search and reranking.
Remember: An error-free pipeline does not guarantee good hits. Whether the librarian brings the right card is a measure of its own.
Save your progress? Sign up for free
Diagnosis task
A colleague built the pipeline in an earlier version. Her ID was a hash over just source and card text:
def punkt_id(quelle, text):
return str(uuid.UUID(hashlib.sha256(f"{quelle}\n{text}".encode()).hexdigest()[:32]))Her search results contained sections such as
Termination of Pods {#pod-termination}. She then added the
line in karten that removes the Hugo anchors from headings,
and ran the pipeline again. In the lab this gave:
{"dokumente": 9, "karten": 173, "neu": 0, "unveraendert": 173, "geloescht": 0, "sekunden": 0.2}
{"score":0.6176556,"abschnitt":"Termination of Pods {#pod-termination}"}
The anchors are still there. You have ten minutes.
Solution: The run reports "neu": 0 –
the pipeline considers all cards known. Their fingerprint contains only
the card text, and that has not changed. What has changed is the
heading, which is embedded along with it and stored as a stamp. So
vorhandene finds all IDs, nothing is written anew, vectors
and stamps stay old. The solution is the version from Drill 2: the hash
covers the embedded text with title and section and the
model. In the lab, the next run with this version gave
"neu": 173 and "geloescht": 173 – every card
got a new fingerprint, the old ones were removed. The same mistake would
hit a model change: without the model in the hash, the old vectors would
stay in place.
Challenge
Delete the file korpus/karte-urlaub.txt, renew the
ConfigMap and run the job. Does the leave card stay in the cabinet?
Check it with points/scroll and a filter on
quelle. The pipeline only cleans up within the files it
sees – how would it have to be extended so that the cards of vanished
files disappear too?
Save your progress? Sign up for free
Checkpoint
# on rag1
curl -s http://127.0.0.1:6333/collections/wissen -o info.json# on rag1
jq '{status: .result.status, points_count: .result.points_count, payload_schema: .result.payload_schema}' info.jsonExpected:
{
"status": "green",
"points_count": 173,
"payload_schema": {
"quelle": {
"data_type": "keyword",
"points": 173
}
}
}
Test yourself
- Why was the second run done in 0.2 seconds?
- Why is the heading part of the embedded text?
- What happens to the old print card when the text changes – and which part of the program takes care of that?
- What belongs in the fingerprint of a card, and what happens if the model is missing?
- Why does the pipeline run as a job and not as a deployment?
- Where does the ConfigMap approach reach its limit?
Answers:
- All IDs already existed in Qdrant. The program only asked and embedded nothing.
- A card on its own often lacks context; title and section are meant to tell the model what it is about. Whether that improves the hits is an assumption – it is measured on Day 7.
- It gets a new ID, and the new card is embedded. Afterwards, the
cleanup with
must_notandhas_iddeletes all points of the same source whose ID no longer occurs. - Everything that determines the vector: embedded text including the heading, source and model. If the model is missing, the old vectors stay after a model change because the IDs stay the same.
- The work has an end. A job runs until it completes and reports
Complete; a deployment would start the container again and again. - At 1 MiB. Larger corpora belong on a volume or in object storage.
Interview note
“How do you keep a vector index up to date when documents change?” – Content hash as the ID, over everything that determines the vector (text, context, model); before embedding, ask what already exists; afterwards, delete outdated chunks per source. The numbers make it tangible: first run 246 seconds, second 0.2, one change 1.2. If you also know the mistake with the incomplete ID, you have run this yourself.
Enterprise note
In companies, documents come from wikis, ticket systems and file
shares, often with permissions. The pipeline then also carries the
access rights over as stamps, so that later only authorised users see
the cards (Day 14). It runs as a CronJob or on events, writes metrics
(cards, duration, errors) and is itself versioned – a new version of
saeubern or karten is a re-indexing (Day 13).
The licences of the sources are carried along so that answers can cite
correctly.
Summary
You delivered five pages of the Kubernetes documentation with a
pinned version and the practice company’s cards. ingest.py
cleans Markdown, splits it by headings into cards with overlap, stamps
source, section and licence, and gives every card a fingerprint. As a
job with two ConfigMaps, the pipeline classified 173 cards in 246.6
seconds; the second run took 0.2 seconds, one changed card 1.2. The
diagnosis showed why the fingerprint must also contain heading and
model. The German question found English cards – but not the right one.
You measure that tomorrow.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
curl -sf -o <file> <url> |
download a file, save nothing on an HTTP error | -f |
curl -X PUT …/collections/wissen/index -d '{"field_name":…,"field_schema":"keyword"}' |
create a payload index | wait=true |
kubectl -n rag create configmap <name> --from-file=<file or folder/> |
files as a ConfigMap | – |
kubectl -n rag delete configmap <name> |
remove a ConfigMap in order to recreate it | – |
kubectl apply -f ingest-job.yaml |
start the job | – |
kubectl -n rag wait --for=condition=Complete job/ingest |
wait for the end | --timeout |
kubectl -n rag logs job/ingest |
report of the shift | – |
kubectl -n rag delete job ingest |
remove a finished job in order to start it again | – |
curl -X POST …/points/scroll -d '{"filter":…}' |
page through points with a filter | with_payload |
kubectl -n rag exec -i curl -- curl -s embed.rag:11434/api/embed -d @- < a.json > b.json |
request an embedding inside the cluster | -d @- |