Skip to content
RAG infrastructure on Kubernetes · Chapter 14 of 20 Day 13: Reindexing without downtime

Day 13: Reindexing without downtime

Goal: Write the cards with a new embedding model into a second collection, compare it against the old one on the test bench from Day 7 and switch the answer service over via an alias – without a single request failing, with a measured way back · Duration: approx. 120 min · Prerequisite: Day 12

State before this chapter

First you check that all services from Day 12 are running. Today you work with the embedding service embed, with Qdrant, the answer service and the helper pod curl.

# on rag1
kubectl -n rag get pods -o wide --field-selector=status.phase=Running
  • --field-selector=status.phase=Running – only running pods; finished jobs of the last days stay out.

Expected (cut off on the right):

NAME                      READY   STATUS    RESTARTS        AGE     IP           NODE
antwort-9bb959975-6wsvs   1/1     Running   0               2m58s   10.42.1.21   rag2
antwort-9bb959975-989b5   1/1     Running   0               2m46s   10.42.0.65   rag1
curl                      1/1     Running   0               4h40m   10.42.0.56   rag1
embed-66bdc7c6c9-rqqpn    1/1     Running   1 (8h ago)      25h     10.42.0.33   rag1
llm-579476976d-6rx9d      1/1     Running   0               5h17m   10.42.0.50   rag1
pg-1                      1/1     Running   1 (4h27m ago)   4h31m   10.42.1.3    rag2
qdrant-0                  1/1     Running   0               4h28m   10.42.1.4    rag2
qdrant-1                  1/1     Running   0               4h40m   10.42.0.58   rag1

What you see: All eight pods 1/1 Running, the two answer services on two nodes, the two Qdrant peers on two nodes. Your names, ages and IP addresses differ.

Introduction

So far every card in wissen got its vector from the model bge-m3. Some day you will want to change that: a new model finds the correct cards more often, is faster or needs less memory. Then you have to embed every card again. That is called reindexing.

The problem: vectors of two models do not fit together. A question embedded with the new model finds nothing sensible among the old vectors – and vice versa. So you cannot replace the cards in wissen one by one while the desk is open. In between there would be a mix of both worlds.

The usual way, in three steps:

  1. Fill a second collection completely with the new model while the old one keeps answering.
  2. Check the second collection – with the same test questions as the old one.
  3. Switch the answer service to the new collection in one step. The old one stays, so you can go back.

For step 3 Qdrant has an alias: a second name that points to a collection and can be moved to another one with a single call. The answer service only asks the alias.

Today you learn:

  • to find out which model a collection was built with and what it consists of,
  • why a reindexing is only as good as the source it reads from – and how to rescue a card that exists only in Qdrant,
  • to build a second collection with qwen3-embedding:0.6b, with a replica and with the model name in the collection’s metadata,
  • to compare both collections on the test bench and justify a decision,
  • to create an alias and move it atomically while a watch measures whether requests fail,
  • why moving the alias alone makes the desk silently wrong – without a single error code,
  • to rebuild the answer service so that it reads model and threshold behind the alias itself,
  • to take the way back in seconds.

Background

The picture for today: moving to a new ordering system

Since moving in, the library has arranged its cards by an ordering system: similar topics stand next to each other, and the location of a card follows from this system (Day 2). Now the library management has bought a new ordering system that places related topics together more precisely.

Re-sorting during opening hours does not work. Under the new system a card stands in a completely different place. If you rearranged the cabinet drawer by drawer, the desk would miss half of the cards for a while.

So the library sets up a second cabinet in the next room. The receiving desk writes the cards for it anew, from the books – not by copying the old cards, because their location belongs to the old system. For every book that is no longer at the receiving desk, the card is missing in the new cabinet.

Visitors find the desk via the sign “Auskunft” (information) above the door. Once the new cabinet is filled and checked, somebody moves the sign. The old cabinet stays. If a mistake shows up, you hang the sign back – that is the way back.

The move has one trap: the librarian at the desk must know which system the cabinet behind the door is ordered by. If she searches the new cabinet with the old location numbers, she finds cards – just the wrong ones. That is why from now on the sign carries a small line underneath saying which ordering system applies.

The terms

Term Meaning in the picture
reindexing embed all cards again with a (new) embedding model and write them into a collection the move to a new ordering system
embedding model the model that turns text into a vector; today bge-m3 (old) and qwen3-embedding:0.6b (new) the ordering system
source of truth the place from which the whole stock can be rebuilt at any time; here the ConfigMap korpus the books at the receiving desk
alias a second name for a collection; Qdrant forwards every request to the collection it points to the sign “Auskunft” above the door
atomic several changes take effect either all or none; there is no in-between state the sign always hangs on exactly one door
collection metadata freely chosen information Qdrant stores with the collection, e.g. model and threshold the small line under the sign
facet a count of points per value of a payload field, e.g. cards per source a tally per book
way back hang the alias back onto the old collection keep the old cabinet standing
The move: source, second cabinet, test bench, moving the sign – with the times from the lab

Remember: With a new embedding model you do not rearrange, you rebuild: second cabinet, check, move the sign, keep the old cabinet as the way back.

Drill 1: Inventory – which ordering system, which books

Where you are: on rag1.

What you have afterwards: the answer to two questions – which model wissen was built with, and whether every card in wissen has a book at the receiving desk.

In this drill: before you move, you write down what stands in the old cabinet and where it comes from.

Step 1 – the folder for today.

# on rag1
mkdir -p ~/kurs/13
# on rag1
cd ~/kurs/13

Step 2 – the shape of the vectors. You fetch the description of the collection wissen into a file.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen > wissen.json

The vector settings are under config.params.vectors.

# on rag1
jq '.result.config.params.vectors' wissen.json

Expected:

{
  "size": 1024,
  "distance": "Cosine"
}
# on rag1
jq '.result.points_count' wissen.json

Expected:

174

What you see: 1024 numbers per vector, cosine as distance, 174 cards. Qdrant does not store the name of the model – a collection does not know who made its vectors. The 1024 match bge-m3 (Day 2), but also any other model with 1024 dimensions.

Step 3 – which model the answer service uses. The model lives in the answer service. set env --list shows the environment variables of a deployment without changing anything.

# on rag1
kubectl -n rag set env deployment/antwort --list
  • set env deployment/antwort – edit the environment variables of the deployment antwort,
  • --list – only show them.

Expected:

# Deployment antwort, container antwort
SAMMLUNG=wissen
KARTEN=3
LLM_TIMEOUT=60
MINDEST_SCORE=0.46
RERANK_URL=
PLAETZE=2

MODELL is not in the list. Then the default in the program applies:

# on rag1
grep -n 'MODELL = ' ~/kurs/10/antwort.py

Expected:

17:MODELL = os.environ.get("MODELL", "bge-m3")
18:LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")

What you see: Line 17 – without an environment variable the answer service embeds every question with bge-m3. Collection and model are therefore fixed in two places: the name wissen in the deployment, the model in the program. That becomes important in Drill 6.

Step 4 – which books stand at the receiving desk. The ingestion from Day 6 reads the ConfigMap korpus, and you built that from the folder ~/kurs/06/korpus.

# on rag1
ls ~/kurs/06/korpus

Expected:

k8s-configmap.md
k8s-pod-lifecycle.md
k8s-pod-qos.md
k8s-secret.md
k8s-taint-and-toleration.md
karte-backup.txt
karte-druck.txt
karte-urlaub.txt
karte-vpn.txt

Nine files.

Step 5 – which sources are in wissen. A facet counts the points per value of a payload field. It needs an index on the field – you created the index on quelle on Day 6. You write the request as a file.

# on rag1
nano facetten.json
~/kurs/13/facetten.json new file
{
  "key": "quelle",
  "exact": true
}
  • key – the payload field to count by,
  • exact – count exactly instead of estimating; with 174 points that costs nothing.
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/wissen/facet \
  -H 'Content-Type: application/json' -d @- \
  < facetten.json > facetten-vorher.json
  • exec -i – pass your input through to curl in the pod,
  • -d @- – read the request body from standard input,
  • < facetten.json / > facetten-vorher.json – request from the file, answer into a file.
# on rag1
jq -c '.result.hits[]' facetten-vorher.json
  • -c – every result on one line.

Expected:

{"value":"k8s-pod-lifecycle.md","count":64}
{"value":"k8s-secret.md","count":43}
{"value":"k8s-taint-and-toleration.md","count":27}
{"value":"k8s-pod-qos.md","count":18}
{"value":"k8s-configmap.md","count":17}
{"value":"karte-backup.txt","count":1}
{"value":"karte-druck.txt","count":1}
{"value":"karte-urlaub.txt","count":1}
{"value":"karte-vpn.txt","count":1}
{"value":"nachtrag-wartung.txt","count":1}

What you see: Ten sources – one more than there are books at the receiving desk. nachtrag-wartung.txt is the card about the maintenance window that you wrote into Qdrant by hand on Day 12. There is no file for it.

Step 6 – the card without a book. A scroll with a filter shows the points of this source.

# on rag1
nano nachtrag-filter.json
~/kurs/13/nachtrag-filter.json new file
{
  "filter": {
    "must": [
      {"key": "quelle", "match": {"value": "nachtrag-wartung.txt"}}
    ]
  },
  "with_payload": ["quelle", "abschnitt"],
  "with_vector": false
}
Setting Value Meaning
filter.must quelle = nachtrag-wartung.txt only cards with this stamp
with_payload quelle, abschnitt return only these two fields
with_vector false leave out the 1024 numbers
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/wissen/points/scroll \
  -H 'Content-Type: application/json' -d @- \
  < nachtrag-filter.json > nachtrag-vorher.json
# on rag1
jq -c '.result.points[]' nachtrag-vorher.json

Expected:

{"id":1201,"payload":{"quelle":"nachtrag-wartung.txt","abschnitt":"Wartungsfenster"}}

What you see: Point 1201 – the fixed ID from Day 12. All other cards carry a long ID that the ingestion computes from model, source and text (Day 6).

Remember: A new cabinet is built from the books, not from the old cabinet. Every card without a book is missing after the move – here the card about the maintenance window.

Save your progress? Sign up for free

Drill 2: The source of truth

Where you are: on rag1, in ~/kurs/13.

What you have afterwards: a ConfigMap korpus with ten files from which wissen can be rebuilt completely, and a maintenance card that comes from the ingestion instead of from a hand.

In this drill: before the move starts, you put the missing book on the shelf of the receiving desk. Then you run the receiving desk once over the old cabinet and watch what it does with the hand-written card.

Step 1 – copy the corpus to today. You work on a copy so the state of Day 6 is kept.

# on rag1
cp -r ~/kurs/06/korpus .
  • -r – copy the folder with all files.

Step 2 – the book about the maintenance window. The text is the same as on Day 12. The cards from Day 1 start with Title: …; the ingestion takes the part before the first colon as the title. The new file follows this pattern.

# on rag1
nano korpus/nachtrag-wartung.txt
~/kurs/13/korpus/nachtrag-wartung.txt new file
Wartungsfenster: Der Kubernetes-Cluster wird jeden Dienstag von 18 bis 20 Uhr gewartet. In dieser Zeit starten die Knoten nacheinander neu, und die Auskunft kann kurz ausfallen. Fragen dazu beantwortet das Plattform-Team.
# on rag1
ls korpus

Expected:

k8s-configmap.md
k8s-pod-lifecycle.md
k8s-pod-qos.md
k8s-secret.md
k8s-taint-and-toleration.md
karte-backup.txt
karte-druck.txt
karte-urlaub.txt
karte-vpn.txt
nachtrag-wartung.txt

Step 3 – recreate the ConfigMap. A ConfigMap cannot be overwritten with create; delete it first, then create it again from the folder.

# on rag1
kubectl -n rag delete configmap korpus

Expected:

configmap "korpus" deleted from rag namespace
# on rag1
kubectl -n rag create configmap korpus --from-file=korpus/

Expected:

configmap/korpus created

Before you start the ingestion – your prediction: wissen has 174 cards, among them point 1201 written by hand. The ingestion now finds ten books with 174 cards in total. How many cards does it write new, how many does it delete – and how many points does wissen have afterwards?

Step 4 – run the receiving desk over the old cabinet. It is the job from Day 6 with SAMMLUNG=wissen and the model bge-m3. A finished job cannot be started again; you delete it first.

# on rag1
kubectl -n rag delete job ingest --ignore-not-found
  • --ignore-not-found – no error if the job is already gone. Jobs from Day 6 and 7 have ttlSecondsAfterFinished: 86400 and disappear on their own after one day.

Expected (or no output if the job was already gone):

job.batch "ingest" deleted from rag namespace
# on rag1
kubectl apply -f ../06/ingest-job.yaml

Expected:

job.batch/ingest created
# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest --timeout=600s

Expected (in the lab after 7 seconds):

job.batch/ingest condition met
# on rag1
kubectl -n rag logs job/ingest

Expected:

k8s-configmap.md: 17 Karten, 0 neu, 0 gelöscht
k8s-pod-lifecycle.md: 64 Karten, 0 neu, 0 gelöscht
k8s-pod-qos.md: 18 Karten, 0 neu, 0 gelöscht
k8s-secret.md: 43 Karten, 0 neu, 0 gelöscht
k8s-taint-and-toleration.md: 27 Karten, 0 neu, 0 gelöscht
karte-backup.txt: 1 Karten, 0 neu, 0 gelöscht
karte-druck.txt: 1 Karten, 0 neu, 0 gelöscht
karte-urlaub.txt: 1 Karten, 0 neu, 0 gelöscht
karte-vpn.txt: 1 Karten, 0 neu, 0 gelöscht
nachtrag-wartung.txt: 1 Karten, 1 neu, 1 gelöscht
{"dokumente": 10, "karten": 174, "neu": 1, "unveraendert": 173, "geloescht": 1, "sekunden": 1.6}

What you see: 173 cards unchanged (unveraendert) – their IDs match, nothing is embedded again. For nachtrag-wartung.txt the ingestion writes one new card (neu) and deletes one (gelöscht): the hand-written 1201. Per source it removes all cards it did not create itself (Day 6). After 1.6 seconds everything was done.

Step 5 – the card now has a book.

# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/wissen/points/scroll \
  -H 'Content-Type: application/json' -d @- \
  < nachtrag-filter.json > nachtrag-nachher.json
# on rag1
jq -c '.result.points[]' nachtrag-nachher.json

Expected:

{"id":"60621d8f-394b-2233-b533-899a4c6cfc6f","payload":{"abschnitt":"Wartungsfenster","quelle":"nachtrag-wartung.txt"}}

The ID is a hash now. With the same text and the same model it is the same ID for you. Point 1201 no longer exists:

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen/points/1201

Expected:

{"status":{"error":"Not found: Point with id 1201 does not exists!"},"time":0.000546918}
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen > wissen.json
# on rag1
jq '.result.points_count' wissen.json

Expected:

174

Step 6 – the desk still knows the maintenance window. You fetch the maintenance question from Day 12 and ask it.

# on rag1
cp ~/kurs/12/wartung.json .
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < wartung.json > wartung-antwort.json
# on rag1
jq '{antwort, quellen}' wartung-antwort.json

Expected:

{
  "antwort": "[1] Das Wartungsfenster für den Kubernetes-Cluster ist jeden Dienstag von 18 bis 20 Uhr.",
  "quellen": [
    {
      "nr": 1,
      "quelle": "nachtrag-wartung.txt",
      "abschnitt": "Wartungsfenster",
      "score": 0.768
    },
    {
      "nr": 2,
      "quelle": "k8s-pod-lifecycle.md",
      "abschnitt": "Detection of kubelet restarts",
      "score": 0.574
    },
    {
      "nr": 3,
      "quelle": "k8s-pod-lifecycle.md",
      "abschnitt": "Pods and fault recovery",
      "score": 0.553
    }
  ]
}

What you see: Correct answer with source (“Tuesdays from 18 to 20 h”). The score rose from 0.739 (Day 12) to 0.768: the ingestion embeds title and section along with the text (Day 7), the hand-made card had only the text.

Resolving your prediction: 1 new, 1 deleted, 174 points. The number stays the same, but the card now comes from a book. From here on wissen can be rebuilt completely from korpus – with any model.

Remember: Make the source complete first, then move. The ingestion is the only place that writes cards; whatever got into the cabinet past it, the next run takes out again.

Save your progress? Sign up for free

Drill 3: The second cabinet

Where you are: on rag1, in ~/kurs/13.

What you have afterwards: the collection wissen-qwen3 with 174 cards from the model qwen3-embedding:0.6b, two copies on two peers and the model name in the metadata – while wissen keeps answering.

In this drill: you put the new ordering system into the embedding service and let the receiving desk fill the second cabinet.

Step 1 – the new model. qwen3-embedding:0.6b is a multilingual embedding model with 0.6 billion parameters. Like bge-m3 it returns vectors with 1024 numbers. You load it into the embedding service from Day 3; it lands on that service’s volume next to bge-m3.

# on rag1
kubectl -n rag exec deploy/embed -- ollama pull qwen3-embedding:0.6b

The output ends with success; in the lab it took 59 seconds.

# on rag1
kubectl -n rag exec deploy/embed -- ollama list

Expected:

NAME                    ID              SIZE      MODIFIED     
qwen3-embedding:0.6b    ac6da0dfba84    639 MB    1 second ago    
bge-m3:latest           790764642607    1.2 GB    28 hours ago    

Step 2 – what the ingestion needs for a new cabinet. The code from Day 7 creates a missing collection with a fixed shape: 1024 numbers, nothing else. For the move that is not enough:

What is missing Why it matters
the dimension as a switch another model may have a different vector length (nomic-embed-text: 768)
replica wissen has had two copies since Day 11; without settings Qdrant creates a new collection without a copy (diagnosis task)
the model in the metadata otherwise a collection does not know which model it was built with (Drill 1, step 2)

You copy the code from Day 7 and add these three things.

# on rag1
cp ../07/ingest.py ingest.py
# on rag1
nano ingest.py
~/kurs/13/ingest.py changes in green
"""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.error
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"))
UEBERLAPPUNG = os.environ.get("UEBERLAPPUNG", "ja") == "ja"
KONTEXT = os.environ.get("KONTEXT", "ja") == "ja"
DIMENSION = int(os.environ.get("DIMENSION", "1024"))
REPLIKATE = int(os.environ.get("REPLIKATE", "2"))
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()
            behalten = UEBERLAPPUNG and len(absaetze[-1]) < MAX_ZEICHEN // 2
            absaetze = [absaetze[-1]] if behalten else []
        absaetze.append(absatz)
    abschliessen()
    return ergebnis


def eingabe(titel, abschnitt, text):
    """Genau dieser Text wird eingebettet."""
    if not KONTEXT:
        return text
    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 sammlung_anlegen():
    """Collection mit Modell-Schild, Replikaten und Index auf quelle anlegen."""
    try:
        anfrage("GET", f"{QDRANT}/collections/{SAMMLUNG}")
        return
    except urllib.error.HTTPError as fehler:
        if fehler.code != 404:
            raise
    anfrage(
        "PUT",
        f"{QDRANT}/collections/{SAMMLUNG}",
        {
            "vectors": {"size": DIMENSION, "distance": "Cosine"},
            "shard_number": 1,
            "replication_factor": REPLIKATE,
            "metadata": {"modell": MODELL},
        },
    )
    anfrage(
        "PUT",
        f"{QDRANT}/collections/{SAMMLUNG}/index?wait=true",
        {"field_name": "quelle", "field_schema": "keyword"},
    )
    print(f"Collection {SAMMLUNG} angelegt", flush=True)


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()
    sammlung_anlegen()
    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())
Line Content Meaning
22 DIMENSION length of the vectors of the new collection, default 1024
23 REPLIKATE copies per shard, default 2 like wissen since Day 11
111 "size": DIMENSION instead of the fixed 1024
112 "shard_number": 1 one shard like wissen; every copy then holds all cards
113 "replication_factor": REPLIKATE two copies on two peers
114 "metadata": {"modell": MODELL} the model name is stored with the collection

For a collection that already exists nothing changes: sammlung_anlegen() returns right away in line 103. So the job from Day 6 runs with the new code just as before.

Step 3 – swap the code.

# on rag1
kubectl -n rag delete configmap ingest-code

Expected:

configmap "ingest-code" deleted from rag namespace
# on rag1
kubectl -n rag create configmap ingest-code --from-file=ingest.py

Expected:

configmap/ingest-code created

Step 4 – the job for the second cabinet. You copy the job from Day 6 and change name, collection and model.

# on rag1
cp ../06/ingest-job.yaml ingest-qwen3.yaml
# on rag1
nano ingest-qwen3.yaml
~/kurs/13/ingest-qwen3.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: ingest-qwen3
  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-qwen3
            - name: MODELL
              value: qwen3-embedding:0.6b
            - name: DIMENSION
              value: "1024"
          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 Value Meaning
metadata.name ingest-qwen3 its own job, ingest stays for wissen
SAMMLUNG wissen-qwen3 the second cabinet; the name says which model is inside
MODELL qwen3-embedding:0.6b the new ordering system
DIMENSION "1024" the vector length of the model; in quotes because environment variables are text

Step 5 – fill the cabinet. Note the time; it goes into the bill at the end.

# on rag1
date -u +%T

Expected (write down your time):

21:39:44
# on rag1
kubectl apply -f ingest-qwen3.yaml

Expected:

job.batch/ingest-qwen3 created
# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest-qwen3 --timeout=900s
  • --timeout=900s – wait up to 15 minutes; every card has to be embedded again.

Expected (in the lab after 4 minutes 24 seconds):

job.batch/ingest-qwen3 condition met
# on rag1
kubectl -n rag logs job/ingest-qwen3

Expected:

Collection wissen-qwen3 angelegt
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
nachtrag-wartung.txt: 1 Karten, 1 neu, 0 gelöscht
{"dokumente": 10, "karten": 174, "neu": 174, "unveraendert": 0, "geloescht": 0, "sekunden": 258.7}

What you see: All 174 cards new, including the maintenance card – the book from Drill 2 was there. 258.7 seconds for the whole stock. During that time wissen kept answering; the receiving desk only wrote into the new cabinet.

Step 6 – check the new cabinet.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen-qwen3 > qwen3.json
# on rag1
jq '.result.points_count' qwen3.json

Expected:

174
# on rag1
jq '.result.config.params' qwen3.json

Expected:

{
  "vectors": {
    "size": 1024,
    "distance": "Cosine"
  },
  "shard_number": 1,
  "replication_factor": 2,
  "write_consistency_factor": 1,
  "on_disk_payload": true
}
# on rag1
jq '.result.config.metadata' qwen3.json

Expected:

{
  "modell": "qwen3-embedding:0.6b"
}
# on rag1
jq '.result.payload_schema' qwen3.json

Expected:

{
  "quelle": {
    "data_type": "keyword",
    "points": 174
  }
}

What you see: One shard, two copies, the model in the metadata, the index on quelle. The full-text index text from Day 8 is missing – no service has used it since Day 9 (hybrid search was no gain). If you needed it, you would have to create it in the new collection just like on Day 8. A move only takes along what you take along.

Step 7 – the two copies. You ask qdrant-1 directly for the distribution of the shards.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant-1.qdrant-headless:6333/collections/wissen-qwen3/cluster \
  > qwen3-cluster.json
# on rag1
jq '.result' qwen3-cluster.json

Expected:

{
  "peer_id": 1806199031829577,
  "shard_count": 1,
  "local_shards": [
    {
      "shard_id": 0,
      "points_count": 174,
      "state": "Active"
    }
  ],
  "remote_shards": [
    {
      "shard_id": 0,
      "peer_id": 3100333476874010,
      "state": "Active"
    }
  ],
  "shard_transfers": []
}

What you see: Shard 0 lives on qdrant-1 (local, 174 cards) and on the other peer (remote_shards), both Active. Your peer numbers differ (Day 11).

Step 8 – what two ordering systems cost. During the move the embedding service has to keep both models ready: the old one for the desk, the new one for the receiving desk.

# on rag1
kubectl -n rag exec deploy/embed -- ollama ps

Expected:

NAME                    ID              SIZE      PROCESSOR    CONTEXT    RUNNER      UNTIL   
qwen3-embedding:0.6b    ac6da0dfba84    1.2 GB    100% CPU     4096       llamacpp    Forever    
bge-m3:latest           790764642607    1.2 GB    100% CPU     4096       llamacpp    Forever    
# on rag1
kubectl -n rag top pod

Expected (excerpt – the line of embed):

embed-66bdc7c6c9-rqqpn    11679m       2665Mi          

What you see: Both models stay loaded (UNTIL Forever, Day 3), 1.2 GB each in memory. The pod needs 2665 MiB – before the move it was 1535 MiB with bge-m3 alone. The limit is 3 GiB (3072 MiB). A third model would no longer fit safely: in the lab kubectl top showed 2803 MiB with three models.

Remember: The second cabinet is filled while the first one answers. It must bring along everything the first one has – copies, indexes – plus a sign saying which system it is ordered by.

Save your progress? Sign up for free

Drill 4: The test bench decides

Where you are: on rag1, in ~/kurs/13.

What you have afterwards: hits@k and MRR for both collections with the same 13 test questions, a threshold for the new model – and a justified decision.

In this drill: before the sign is moved, you ask both cabinets the same questions.

Before you measure – your prediction: Day 7 measured wissen: hits@5 0.77, MRR 0.72. Will the new model be better, equal or worse? And for which questions?

Step 1 – the old cabinet. The test bench from Day 7 runs as job eval with SAMMLUNG=wissen and the model bge-m3.

# on rag1
kubectl -n rag delete job eval --ignore-not-found

Expected:

job.batch "eval" deleted from rag namespace
# on rag1
kubectl apply -f ../07/eval-job.yaml

Expected:

job.batch/eval created
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval --timeout=300s

Expected:

job.batch/eval condition met
# on rag1
kubectl -n rag logs job/eval

Expected:

 f01  Platz -    0.5 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz 1    0.1 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz 1    0.3 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz 1    0.5 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz 1    0.5 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz 1    0.2 s  Wozu dient eine Startup-Probe?
 f07  Platz 3    0.3 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz 1    0.2 s  Welche Phasen kann ein Pod haben?
 f09  Platz -    0.2 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz -    0.2 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz 1    0.1 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz 1    0.2 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz 1    0.2 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "dicht", "rerank": false, "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.77, "mrr": 0.72, "im_pool": 0.77, "sekunden_je_frage": 0.26}

What you see: The same values as on Day 7 – the new maintenance card has not pushed out any test question. bge-m3 does not find f01, f09 and f10 among the first five (Platz -).

Step 2 – the test bench for the new cabinet. The same job with a different collection and a different model. The model is mandatory: the test questions must be embedded with the same model as the cards.

# on rag1
cp ../07/eval-job.yaml eval-qwen3.yaml
# on rag1
nano eval-qwen3.yaml
~/kurs/13/eval-qwen3.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: eval-qwen3
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: eval
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/eval.py"]
          env:
            - name: SAMMLUNG
              value: wissen-qwen3
            - name: MODELL
              value: qwen3-embedding:0.6b
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: testfragen
              mountPath: /testfragen
      volumes:
        - name: code
          configMap:
            name: eval-code
        - name: testfragen
          configMap:
            name: testfragen
# on rag1
kubectl apply -f eval-qwen3.yaml

Expected:

job.batch/eval-qwen3 created
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval-qwen3 --timeout=300s

Expected:

job.batch/eval-qwen3 condition met
# on rag1
kubectl -n rag logs job/eval-qwen3

Expected:

 f01  Platz -    0.6 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz 1    0.6 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz 1    0.3 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz 2    0.2 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz 1    0.2 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz 1    0.2 s  Wozu dient eine Startup-Probe?
 f07  Platz 1    0.2 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz 1    0.2 s  Welche Phasen kann ein Pod haben?
 f09  Platz 5    0.2 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz 2    0.2 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz 1    0.3 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz 1    0.2 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz 1    0.3 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen-qwen3", "suche": "dicht", "rerank": false, "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.85, "treffer@5": 0.92, "mrr": 0.78, "im_pool": 0.92, "sekunden_je_frage": 0.27}

Step 3 – the comparison.

Metric wissen (bge-m3) wissen-qwen3 Meaning
hits@1 0.69 0.69 equally often the correct card at the very top
hits@3 0.77 0.85 f07 moves from rank 3 to 1, f10 reaches rank 2
hits@5 0.77 0.92 only f01 is missing; f09 and f10 are in now
MRR 0.72 0.78 on average the correct card stands higher
seconds per question 0.26 0.27 equally fast
ingestion 246.6 s (Day 6) 258.7 s equally expensive

The new model lost only on f04 (rank 1 → 2). It gained on f07, f09 and f10.

Step 4 – the threshold no longer fits. Since Day 9 the answer service rejects questions whose best card is below MINDEST_SCORE 0.46. You determined that number for bge-m3. In the lab the search (without the language model) gave these values for the best card with both models:

Question bge-m3 qwen3-embedding
f02 secret size (correct) 0.733 0.554
f12 printer (correct) 0.642 0.538
f06 startup probe (correct) 0.680 0.502
f13 VPN (correct, weakest) 0.489 0.446
canteen? (not in stock) 0.539 0.466
install Kubernetes? (not in stock) 0.566 0.457
vacation days? (not in stock) 0.599 0.402
reset password? (not in stock) 0.588 0.356
laptop? (not in stock) 0.452 0.332
bicycle parking? (not in stock) 0.403 0.188

What you see: The new model gives lower scores overall. With the old threshold 0.46 it would reject the VPN question (0.446) although the correct card is in front. On the other hand the questions without an answer lie further away from the correct ones: a threshold of 0.42 lets f13 through and rejects six of the eight questions without an answer. With bge-m3 and 0.46 it was four. As on Day 9: this is a lab number for this stock and this model.

Resolving your prediction: Better – hits@5 from 0.77 to 0.92, MRR from 0.72 to 0.78, at the same speed. But only with a new threshold: 0.46 would reject a correct question.

Remember: A new model is chosen on the test bench, not by reputation. And the threshold changes with the model – scores of two models cannot be compared.

Save your progress? Sign up for free

Drill 5: The sign above the door

Where you are: on rag1, in ~/kurs/13.

What you have afterwards: an alias auskunft pointing to wissen, an answer service that only asks auskunft – and a watch that measured that no request failed meanwhile.

In this drill: you hang up the sign and switch the desk to it. For now the sign still points to the old cabinet.

Step 1 – create the alias. You create aliases via POST /collections/aliases. The body is a list of actions; today it contains just one.

# on rag1
nano schild-anlegen.json
~/kurs/13/schild-anlegen.json new file
{
  "actions": [
    {
      "create_alias": {
        "collection_name": "wissen",
        "alias_name": "auskunft"
      }
    }
  ]
}
  • create_alias – create an alias,
  • collection_name – the collection it points to,
  • alias_name – the new name.
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < schild-anlegen.json

Expected:

{"result":true,"status":"ok","time":0.119705811}
# on rag1
kubectl -n rag exec curl -- curl -s http://qdrant.rag:6333/aliases

Expected:

{"result":{"aliases":[{"alias_name":"auskunft","collection_name":"wissen"}]},"status":"ok","time":0.000074013}

Step 2 – through the door with the sign. Every request to auskunft goes to wissen.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/auskunft > auskunft.json
# on rag1
jq '.result.points_count' auskunft.json

Expected:

174

Step 3 – the watch. As on Day 11 a pod keeps asking the answer service a question and writes down time, HTTP status and duration. You use the laptop question: it is below the threshold, so the answer service only searches and does not wake up the language model. That way the watch measures the path through the sign without creating load. The loop runs in the pod – you do not type it.

# on rag1
nano wache.yaml
~/kurs/13/wache.yaml new file
apiVersion: v1
kind: Pod
metadata:
  name: wache
  namespace: rag
spec:
  nodeSelector:
    kubernetes.io/hostname: rag1
  containers:
    - name: wache
      image: curlimages/curl:8.17.0
      command: ["sh", "-c"]
      args:
        - |
          while true; do
            a=$(curl -s -o /tmp/antwort -m 5 -w '%{http_code} %{time_total}' \
              -H 'Content-Type: application/json' -d "$FRAGE" \
              http://antwort.rag/frage)
            s=$(grep -o '"sammlung": "[^"]*"' /tmp/antwort | head -1)
            echo "$(date +%T) $a $s"
            sleep 1
          done
      env:
        - name: FRAGE
          value: '{"frage": "Wie bekomme ich einen neuen Laptop?"}'
      resources:
        requests:
          cpu: 10m
          memory: 16Mi
        limits:
          memory: 32Mi
Lines Content Meaning
7–8 nodeSelector rag1 the watch stands on rag1
16 -o /tmp/antwort -m 5 answer into a file, wait at most 5 seconds
16 -w '%{http_code} %{time_total}' print only status and duration
19 grep -o '"sammlung": "[^"]*"' cut the collection out of the answer – today’s answer service does not write it yet, from Drill 7 on it does
20 echo "$(date +%T) $a $s" one line per question
21 sleep 1 a bit more than one question per second
# on rag1
kubectl apply -f wache.yaml

Expected:

pod/wache created
# on rag1
kubectl -n rag wait --for=condition=Ready pod/wache --timeout=120s

Expected:

pod/wache condition met

Wait a few seconds, then:

# on rag1
kubectl -n rag logs wache --tail=3

Expected:

21:45:33 200 0.367427 
21:45:34 200 0.205807 
21:45:36 200 0.287324 

Status 200, roughly 0.2 to 0.4 seconds per question. From now on the watch’s clock is your timeline.

Step 4 – switch the desk to the sign. In the manifest from Day 11 you change a single line.

# on rag1
cp ../11/antwort.yaml antwort.yaml
# on rag1
nano antwort.yaml
~/kurs/13/antwort.yaml changes in green
apiVersion: apps/v1
kind: Deployment
metadata:
  name: antwort
  namespace: rag
spec:
  replicas: 2
  selector:
    matchLabels:
      app: antwort
  template:
    metadata:
      labels:
        app: antwort
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: antwort
          matchLabelKeys:
            - pod-template-hash
      containers:
        - name: antwort
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/antwort.py"]
          env:
            - name: SAMMLUNG
              value: auskunft
            - name: KARTEN
              value: "3"
            - name: LLM_TIMEOUT
              value: "60"
            - name: MINDEST_SCORE
              value: "0.46"
            - name: RERANK_URL
              value: ""
            - name: PLAETZE
              value: "2"
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
          volumeMounts:
            - name: code
              mountPath: /code
      volumes:
        - name: code
          configMap:
            name: antwort-code
---
apiVersion: v1
kind: Service
metadata:
  name: antwort
  namespace: rag
spec:
  selector:
    app: antwort
  ports:
    - port: 80
      targetPort: 8080
  • Line 31 – SAMMLUNG is now auskunft, the alias instead of the collection.
# on rag1
date -u +%T

Expected:

21:45:37
# on rag1
kubectl apply -f antwort.yaml

Expected:

deployment.apps/antwort configured
service/antwort unchanged
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (last line, in the lab after 24 seconds):

deployment "antwort" successfully rolled out

Step 5 – what the desk does now.

# on rag1
kubectl -n rag logs -l app=antwort --prefix --tail=1
  • -l app=antwort – both answer services,
  • --prefix – pod name in front of every line,
  • --tail=1 – only the last line per pod.

Expected:

[pod/antwort-9bbbd7695-z5qkk/antwort] keine Karte  bester 0.452  Wie bekomme ich einen neuen Laptop?
[pod/antwort-9bbbd7695-k5bqg/antwort] keine Karte  bester 0.452  Wie bekomme ich einen neuen Laptop?

What you see: Both new pods answer the watch (“keine Karte” = no card). Best score 0.452 – the same value as on Day 9 and in the table of Drill 4: behind the sign there is still wissen.

Step 6 – what the watch experienced.

# on rag1
kubectl -n rag logs wache --since=60s
  • --since=60s – only the lines of the last 60 seconds.

Expected:

21:45:32 200 0.655287 
21:45:33 200 0.367427 
21:45:34 200 0.205807 
21:45:36 200 0.287324 
21:45:37 200 0.340507 
21:45:38 200 0.316110 
21:45:40 200 0.480624 
21:45:41 200 0.291789 
21:45:43 200 0.498031 
21:45:44 200 0.216043 
21:45:45 200 0.162323 
21:45:47 200 0.275430 
21:45:48 200 0.188132 
21:45:49 200 0.216886 
21:45:51 200 0.424182 
21:45:52 200 0.188146 
21:45:53 200 0.185562 
21:45:54 200 0.188491 
21:45:56 200 0.182113 
21:45:57 200 0.229201 
21:45:58 200 0.129718 
21:45:59 200 0.276672 
21:46:01 200 0.146567 
21:46:02 200 0.307759 
21:46:03 200 0.232970 
21:46:04 200 0.159260 
21:46:06 200 0.189526 
21:46:07 200 0.332173 

The rollout ran from 21:45:37 to 21:46:01. Instead of reading every line, you count the lines without 200:

# on rag1
kubectl -n rag logs wache | grep -c -v ' 200 '
  • -v – lines that do not contain the pattern,
  • -c – only count.

Expected:

0

What you see: No request failed while Kubernetes replaced both answer services. The deployment first starts a new pod, waits until it is ready and only then removes an old one (rolling update).

Remember: You hang up the sign once, while it still points to the old cabinet. From then on the desk only asks the sign – and the move itself no longer needs a restart of the desk.

Save your progress? Sign up for free

Drill 6: Moving the sign without asking the desk

Where you are: on rag1, in ~/kurs/13. The watch is running.

What you have afterwards: a measured failure that no monitoring reports – and the first way back.

In this drill: you move the sign to the new cabinet without telling the librarian that a different ordering system applies there.

Step 1 – the secret question before. You fetch the question from Day 9 and ask it via the sign to wissen.

# on rag1
cp ~/kurs/09/f02.json .
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < f02.json > f02-wissen.json
# on rag1
jq '{antwort, quellen}' f02-wissen.json

Expected:

{
  "antwort": "[1] Ein Secret darf maximal 1 MiB in Größe betragen.",
  "quellen": [
    {
      "nr": 1,
      "quelle": "k8s-secret.md",
      "abschnitt": "Size limit",
      "score": 0.733
    },
    {
      "nr": 2,
      "quelle": "k8s-secret.md",
      "abschnitt": "Secrets",
      "score": 0.608
    },
    {
      "nr": 3,
      "quelle": "k8s-secret.md",
      "abschnitt": "Secrets",
      "score": 0.582
    }
  ]
}

Step 2 – the move request. Two actions in one request: take the sign down and hang it on the new door. Qdrant executes both together – there is no moment in which auskunft is missing or points to both.

# on rag1
nano umhaengen-qwen3.json
~/kurs/13/umhaengen-qwen3.json new file
{
  "actions": [
    {
      "delete_alias": {
        "alias_name": "auskunft"
      }
    },
    {
      "create_alias": {
        "collection_name": "wissen-qwen3",
        "alias_name": "auskunft"
      }
    }
  ]
}
  • delete_alias – remove the alias auskunft,
  • create_alias – create it again right away for wissen-qwen3.

Before you move the sign – your prediction:

  1. The answer service keeps embedding with bge-m3 but searches cards made by qwen3-embedding. Both return 1024 numbers. Does the watch get an error?
  2. What does the desk answer to the secret question?

Write down both answers.

Step 3 – move the sign.

# on rag1
date -u +%T

Expected:

21:46:18
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < umhaengen-qwen3.json

Expected:

{"result":true,"status":"ok","time":0.180818152}
# on rag1
kubectl -n rag exec curl -- curl -s http://qdrant.rag:6333/aliases

Expected:

{"result":{"aliases":[{"alias_name":"auskunft","collection_name":"wissen-qwen3"}]},"status":"ok","time":0.000084104}

Qdrant needed 0.18 seconds. Wait a few seconds, then:

Step 4 – the watch.

# on rag1
kubectl -n rag logs wache --tail=6

Expected:

21:46:19 200 0.459411 
21:46:21 200 0.260714 
21:46:22 200 0.190635 
21:46:23 200 0.237615 
21:46:24 200 0.138592 
21:46:26 200 0.264009 

All 200. From the outside the desk looks healthy.

Step 5 – the secret question.

# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < f02.json > f02-falsch.json
# on rag1
jq '{antwort, quellen}' f02-falsch.json

Expected:

{
  "antwort": "Dazu steht nichts im Handbuch.",
  "quellen": []
}

A question that was answered correctly a moment ago is now “not in the handbook”. The log shows why:

# on rag1
kubectl -n rag logs -l app=antwort --prefix --tail=2

Expected:

[pod/antwort-9bbbd7695-k5bqg/antwort] keine Karte  bester 0.056  Wie groß darf ein Secret höchstens sein?
[pod/antwort-9bbbd7695-k5bqg/antwort] keine Karte  bester 0.055  Wie bekomme ich einen neuen Laptop?
[pod/antwort-9bbbd7695-z5qkk/antwort] keine Karte  bester 0.055  Wie bekomme ich einen neuen Laptop?
[pod/antwort-9bbbd7695-z5qkk/antwort] keine Karte  bester 0.055  Wie bekomme ich einen neuen Laptop?

What you see: Best score 0.056 instead of 0.733. A vector from bge-m3 and a vector from qwen3-embedding have the same length, but their 1024 numbers mean something completely different – like a location number from the old system in the new cabinet. Qdrant computes a cosine anyway, without an error. All scores fall below the threshold, and the desk tells everybody “Dazu steht nichts im Handbuch” (nothing about that in the handbook) – with status 200.

Step 6 – the way back. The same request in the other direction.

# on rag1
nano umhaengen-wissen.json
~/kurs/13/umhaengen-wissen.json new file
{
  "actions": [
    {
      "delete_alias": {
        "alias_name": "auskunft"
      }
    },
    {
      "create_alias": {
        "collection_name": "wissen",
        "alias_name": "auskunft"
      }
    }
  ]
}
# on rag1
date -u +%T

Expected:

21:46:27
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < umhaengen-wissen.json

Expected:

{"result":true,"status":"ok","time":0.155617923}
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < f02.json > f02-zurueck.json
# on rag1
jq '.antwort' f02-zurueck.json

Expected:

"[1] Ein Secret darf maximal 1 MiB in Größe betragen."

What you see: The desk answers correctly again. The silent failure lasted from 21:46:19 to 21:46:28 – nine seconds, because you were looking for it. Without a targeted question nobody would have noticed: the watch counted only 200.

Resolving your prediction:

  1. No. No error, no other status – the watch saw only 200.
  2. “Dazu steht nichts im Handbuch.” The best score fell to 0.056. If the new model had a different vector length, there would at least be a loud error from Qdrant. With the same length it stays silent.

Remember: Moving the sign is not enough if the desk searches with the old system. Same dimension does not mean same model – the failure is silent then, and only a content check finds it.

Save your progress? Sign up for free

Drill 7: The desk reads the sign

Where you are: on rag1, in ~/kurs/13. The watch is running, auskunft points to wissen.

What you have afterwards: model and threshold as metadata on both collections, an answer service that reads them behind the alias – and a move in which no request fails and the answers are right.

In this drill: the sign gets the small line underneath, and the librarian reads it for every question.

Step 1 – rebuild the answer service. So far collection, model and threshold live in three places (deployment, program, deployment). From now on the answer service asks Qdrant for every question: which collection does the alias point to, and what is in its metadata?

# on rag1
cp ../10/antwort.py antwort.py
# on rag1
nano antwort.py
~/kurs/13/antwort.py changes in green
"""Antwortdienst: Frage einbetten, Karten suchen, mit Quellenangabe antworten."""

import json
import os
import signal
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
LLM = os.environ.get("LLM_URL", "http://llm.rag:11434")
RERANK = os.environ.get("RERANK_URL", "")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")
KARTEN = int(os.environ.get("KARTEN", "3"))
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
MINDEST = float(os.environ.get("MINDEST_SCORE", "0"))
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
MAX_TOKEN = int(os.environ.get("MAX_TOKEN", "300"))
PLAETZE = int(os.environ.get("PLAETZE", "0"))
KEINE = "Dazu steht nichts im Handbuch."
THEKE = threading.BoundedSemaphore(PLAETZE) if PLAETZE else None

ANWEISUNG = (
    "Du bist die IT-Auskunft einer Firma. Beantworte die Frage des Nutzers auf "
    "Deutsch, kurz, und nur mit dem Inhalt der Karten unten. Nenne hinter jeder "
    "Aussage die Nummer der Karte in eckigen Klammern, zum Beispiel [1]. Steht die "
    f"Antwort auf keiner Karte, antworte genau: {KEINE}\n\nKarten:\n"
)


def anfrage(url, daten, timeout=30):
    req = urllib.request.Request(
        url,
        data=json.dumps(daten).encode(),
        headers={"Content-Type": "application/json"},
    )
    return urllib.request.urlopen(req, timeout=timeout)


def lesen(url):
    """GET an Qdrant, Antwort als JSON."""
    with urllib.request.urlopen(url, timeout=5) as a:
        return json.load(a)


def schild():
    """Hinter dem Schild nachsehen: welche Collection, welches Modell, welche Schwelle."""
    name = SAMMLUNG
    for eintrag in lesen(f"{QDRANT}/aliases")["result"]["aliases"]:
        if eintrag["alias_name"] == SAMMLUNG:
            name = eintrag["collection_name"]
    config = lesen(f"{QDRANT}/collections/{name}")["result"]["config"]
    angaben = config.get("metadata") or {}
    return name, angaben.get("modell", MODELL), angaben.get("mindest_score", MINDEST)


def suchen(frage):
    """Frage mit dem Modell der Collection einbetten, Karten holen, ggf. neu ordnen."""
    name, modell, mindest = schild()
    with anfrage(f"{EMBED}/api/embed", {"model": modell, "input": [frage]}) as a:
        vektor = json.load(a)["embeddings"][0]
    koerper = {
        "query": vektor,
        "limit": KANDIDATEN if RERANK else KARTEN,
        "with_payload": True,
    }
    with anfrage(f"{QDRANT}/collections/{name}/points/query", koerper) as a:
        punkte = json.load(a)["result"]["points"]
    if RERANK and punkte:
        texte = [p["payload"]["text"] for p in punkte]
        with anfrage(f"{RERANK}/rerank", {"query": frage, "texts": texte}, 120) as a:
            punkte = [punkte[u["index"]] for u in json.load(a)]
    return punkte[:KARTEN], name, mindest


def nachrichten(frage, punkte):
    """Anweisung und nummerierte Karten als System-, die Frage als Nutzernachricht."""
    karten = [
        f"[{nr}] {p['payload']['abschnitt']}\n{p['payload']['text']}\n"
        for nr, p in enumerate(punkte, start=1)
    ]
    return [
        {"role": "system", "content": ANWEISUNG + "\n".join(karten)},
        {"role": "user", "content": frage},
    ]


class Auskunft(BaseHTTPRequestHandler):
    def senden(self, status, daten):
        rumpf = json.dumps(daten, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(rumpf)))
        self.end_headers()
        self.wfile.write(rumpf)

    def zeile(self, daten):
        self.wfile.write(json.dumps(daten, ensure_ascii=False).encode() + b"\n")
        self.wfile.flush()

    def do_GET(self):
        if self.path == "/health":
            self.senden(200, {"status": "ok"})
        else:
            self.senden(404, {"fehler": "unbekannter Pfad"})

    def do_POST(self):
        if self.path != "/frage":
            self.senden(404, {"fehler": "unbekannter Pfad"})
            return
        laenge = int(self.headers.get("Content-Length", 0))
        eingabe = json.loads(self.rfile.read(laenge) or b"{}")
        frage = str(eingabe.get("frage", "")).strip()
        if not frage:
            self.senden(400, {"fehler": "frage fehlt"})
            return
        if THEKE and not THEKE.acquire(blocking=False):
            print(f"abgewiesen, {PLAETZE} Plätze belegt  {frage}", flush=True)
            self.send_response(503)
            self.send_header("Retry-After", "30")
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b'{"fehler": "zu viele Fragen gleichzeitig"}')
            return
        try:
            self.beantworten(frage, eingabe)
        finally:
            if THEKE:
                THEKE.release()

    def beantworten(self, frage, eingabe):
        """Suchen, Schwelle prüfen, dann ganz oder als Strom antworten."""
        start = time.time()
        punkte, sammlung, mindest = suchen(frage)
        zeiten = {"suche": round(time.time() - start, 2)}
        bester = punkte[0]["score"] if punkte else 0.0
        if bester < mindest:
            print(f"keine Karte  bester {bester:.3f}  {sammlung}  {frage}", flush=True)
            self.senden(
                200,
                {
                    "antwort": KEINE,
                    "quellen": [],
                    "sammlung": sammlung,
                    "sekunden": zeiten,
                },
            )
            return
        quellen = [
            {
                "nr": nr,
                "quelle": p["payload"]["quelle"],
                "abschnitt": p["payload"]["abschnitt"],
                "score": round(p["score"], 3),
                "sammlung": sammlung,
            }
            for nr, p in enumerate(punkte, start=1)
        ]
        if eingabe.get("stream"):
            self.strom(frage, punkte, quellen, start, zeiten)
        else:
            self.ganz(frage, punkte, quellen, start, zeiten)

    def ganz(self, frage, punkte, quellen, start, zeiten):
        """Auf die ganze Antwort warten und sie in einem Stück senden."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": False,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                antwort = json.load(a)["message"]["content"].strip()
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            self.senden(504, {"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            self.senden(502, {"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"antwort  {zeiten}  {frage}", flush=True)
        self.senden(200, {"antwort": antwort, "quellen": quellen, "sekunden": zeiten})

    def strom(self, frage, punkte, quellen, start, zeiten):
        """Jedes Stück der Antwort sofort weiterreichen, eine JSON-Zeile je Stück."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": True,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        self.send_response(200)
        self.send_header("Content-Type", "application/x-ndjson")
        self.end_headers()
        self.zeile({"quellen": quellen})
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                for roh in a:
                    stueck = json.loads(roh)["message"]["content"]
                    if stueck and "erstes_wort" not in zeiten:
                        zeiten["erstes_wort"] = round(time.time() - start, 2)
                    if stueck:
                        self.zeile({"text": stueck})
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            self.zeile({"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            self.zeile({"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"strom  {zeiten}  {frage}", flush=True)
        self.zeile({"fertig": True, "sekunden": zeiten})

    def log_message(self, format, *args):
        pass


def beenden(signum, frame):
    """Auf SIGTERM von Kubernetes sofort und sauber enden."""
    print("SIGTERM erhalten, Antwortdienst endet", flush=True)
    raise SystemExit(0)


if __name__ == "__main__":
    signal.signal(signal.SIGTERM, beenden)
    print(
        f"Antwortdienst auf Port 8080, Sammlung {SAMMLUNG}, LLM {LLM_MODELL}",
        flush=True,
    )
    ThreadingHTTPServer(("", 8080), Auskunft).serve_forever()
Lines Content Meaning
45–48 lesen() a plain GET to Qdrant
53–56 /aliases fetch the list of all aliases and look up which collection SAMMLUNG points to; if SAMMLUNG is not an alias, the name stays
57–59 config.metadata read model and threshold of the collection; if they are missing, MODELL and MINDEST_SCORE apply as before
64–65 schild(), "model": modell embed the question with the model of this collection
72 /collections/{name}/points/query search directly in the collection found, not in the alias
78, 139 name, mindest pass collection and threshold on to the answer
142 bester < mindest the collection’s threshold instead of the fixed number
149, 160 "sammlung": sammlung every answer says which cabinet it comes from

Why line 72 uses the real name and not the alias: between line 64 and 72 lies the embedding of the question. If somebody moves the sign at that moment, a search via the alias would already land in the new cabinet – with the vector of the old model. This way every request stays with one collection from start to finish.

Step 2 – label the sign. You set the metadata with PATCH on the collection. For wissen that is the old model and the threshold from Day 9.

# on rag1
nano schild-wissen.json
~/kurs/13/schild-wissen.json new file
{
  "metadata": {
    "modell": "bge-m3",
    "mindest_score": 0.46
  }
}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X PATCH \
  http://qdrant.rag:6333/collections/wissen \
  -H 'Content-Type: application/json' -d @- < schild-wissen.json
  • -X PATCH – change settings of an existing collection; the cards stay untouched.

Expected:

{"result":true,"status":"ok","time":0.061761901}

For wissen-qwen3 the model is already there (Drill 3); the threshold 0.42 from Drill 4 is added.

# on rag1
nano schild-qwen3.json
~/kurs/13/schild-qwen3.json new file
{
  "metadata": {
    "modell": "qwen3-embedding:0.6b",
    "mindest_score": 0.42
  }
}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X PATCH \
  http://qdrant.rag:6333/collections/wissen-qwen3 \
  -H 'Content-Type: application/json' -d @- < schild-qwen3.json

Expected:

{"result":true,"status":"ok","time":0.048622169}

You check both signs.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen > wissen.json
# on rag1
jq '.result.config.metadata' wissen.json

Expected:

{
  "modell": "bge-m3",
  "mindest_score": 0.46
}
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen-qwen3 > qwen3.json
# on rag1
jq '.result.config.metadata' qwen3.json

Expected:

{
  "modell": "qwen3-embedding:0.6b",
  "mindest_score": 0.42
}

Step 3 – swap the code and restart the desk. This time nothing changes in the deployment – only the ConfigMap. Kubernetes therefore does not start a new pod by itself; rollout restart does, again pod by pod.

# on rag1
kubectl -n rag delete configmap antwort-code

Expected:

configmap "antwort-code" deleted from rag namespace
# on rag1
kubectl -n rag create configmap antwort-code --from-file=antwort.py

Expected:

configmap/antwort-code created
# on rag1
date -u +%T

Expected:

21:46:53
# on rag1
kubectl -n rag rollout restart deployment/antwort

Expected:

deployment.apps/antwort restarted
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (last line, in the lab at 21:47:17):

deployment "antwort" successfully rolled out

Wait a few seconds, then:

# on rag1
kubectl -n rag logs wache --tail=4

Expected:

21:47:17 200 0.537784 "sammlung": "wissen"
21:47:19 200 0.363154 "sammlung": "wissen"
21:47:20 200 0.486027 "sammlung": "wissen"
21:47:22 200 0.522243 "sammlung": "wissen"

What you see: Now every line says which cabinet the answer came from – wissen, via the sign.

Before you move the sign – your prediction: In which line of the watch do you see the switch? And how many lines without 200 do you expect?

Step 4 – move the sign, properly this time. The same file as in Drill 6.

# on rag1
date -u +%T

Expected:

21:47:22
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < umhaengen-qwen3.json

Expected:

{"result":true,"status":"ok","time":0.141291432}

Wait a few seconds, then:

# on rag1
kubectl -n rag logs wache --tail=8

Expected:

21:47:19 200 0.363154 "sammlung": "wissen"
21:47:20 200 0.486027 "sammlung": "wissen"
21:47:22 200 0.522243 "sammlung": "wissen"
21:47:23 200 0.325650 "sammlung": "wissen"
21:47:25 200 0.301046 "sammlung": "wissen-qwen3"
21:47:26 200 0.252591 "sammlung": "wissen-qwen3"
21:47:27 200 0.203808 "sammlung": "wissen-qwen3"
21:47:29 200 0.434438 "sammlung": "wissen-qwen3"

What you see: Up to 21:47:23 wissen, from 21:47:25 wissen-qwen3. No gap in between, no other status. The response times stay the same although the answer service sends two extra GETs to Qdrant for every question.

Step 5 – are the answers right? The watch only checks the status. So now the content check from Drill 6.

# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < f02.json > f02-qwen3.json
# on rag1
jq '{antwort, quellen}' f02-qwen3.json

Expected:

{
  "antwort": "[1] Ein Secret darf maximal 1 MiB in Größe haben.",
  "quellen": [
    {
      "nr": 1,
      "quelle": "k8s-secret.md",
      "abschnitt": "Size limit",
      "score": 0.554,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 2,
      "quelle": "k8s-secret.md",
      "abschnitt": "Constraints on Secret names and data",
      "score": 0.426,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 3,
      "quelle": "k8s-secret.md",
      "abschnitt": "Alternatives to Secrets",
      "score": 0.411,
      "sammlung": "wissen-qwen3"
    }
  ]
}

What you see: Correct answer (“at most 1 MiB”), correct card in front, score 0.554 – exactly the value from the table in Drill 4. Cards 2 and 3 differ from bge-m3: a different ordering system puts different neighbours next to the card.

Now the weakest correct question, which the old threshold would have rejected:

# on rag1
nano f13.json
~/kurs/13/f13.json new file
{"frage": "Wie komme ich von zu Hause ins Firmennetz?"}
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < f13.json > f13-qwen3.json
# on rag1
jq '{antwort, quellen}' f13-qwen3.json

Expected:

{
  "antwort": "[1] VPN-Zugang einrichten: Lade das Profil firma.ovpn aus dem Self-Service-Portal und importiere es in den OpenVPN-Client. Benutzername ist deine Personalnummer, das Einmalpasswort kommt aus der Authenticator-App.",
  "quellen": [
    {
      "nr": 1,
      "quelle": "karte-vpn.txt",
      "abschnitt": "VPN-Zugang einrichten",
      "score": 0.446,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 2,
      "quelle": "karte-urlaub.txt",
      "abschnitt": "Urlaub beantragen",
      "score": 0.304,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 3,
      "quelle": "karte-backup.txt",
      "abschnitt": "Backup wiederherstellen",
      "score": 0.21,
      "sammlung": "wissen-qwen3"
    }
  ]
}

What you see: 0.446 is above the new threshold 0.42 – the desk answers with the VPN card. With the fixed threshold 0.46 from the deployment the answer would have been “Dazu steht nichts im Handbuch”.

# on rag1
kubectl -n rag logs -l app=antwort --prefix --tail=3

Expected:

[pod/antwort-7fb4c78dc5-8hh7m/antwort] keine Karte  bester 0.332  wissen-qwen3  Wie bekomme ich einen neuen Laptop?
[pod/antwort-7fb4c78dc5-8hh7m/antwort] antwort  {'suche': 0.21, 'gesamt': 11.93}  Wie groß darf ein Secret höchstens sein?
[pod/antwort-7fb4c78dc5-8hh7m/antwort] keine Karte  bester 0.332  wissen-qwen3  Wie bekomme ich einen neuen Laptop?
[pod/antwort-7fb4c78dc5-686x2/antwort] keine Karte  bester 0.332  wissen-qwen3  Wie bekomme ich einen neuen Laptop?
[pod/antwort-7fb4c78dc5-686x2/antwort] keine Karte  bester 0.332  wissen-qwen3  Wie bekomme ich einen neuen Laptop?
[pod/antwort-7fb4c78dc5-686x2/antwort] antwort  {'suche': 0.49, 'gesamt': 19.18}  Wie komme ich von zu Hause ins Firmennetz?

What you see: The watch’s laptop question gets 0.332 with the new model – below 0.42, so it is still rejected without waking the language model. The search itself takes 0.2 to 0.5 seconds.

Resolving your prediction: The switch lies between 21:47:23 and 21:47:25 – between two questions of the watch. Zero lines without 200. And this time the answers are right, too.

Remember: The sign carries the ordering system and the threshold, and the desk reads both for every question. Then moving is a single call – and every request stays in one cabinet from start to finish.

Save your progress? Sign up for free

Drill 8: The way back

Where you are: on rag1, in ~/kurs/13. The watch is running, auskunft points to wissen-qwen3.

What you have afterwards: a measured way back and forward again, a balance from the watch – and the decision what happens to the old cabinet.

In this drill: suppose users complain about the new desk tomorrow. How fast are you back?

Step 1 – back to wissen.

# on rag1
date -u +%T

Expected:

21:48:02
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < umhaengen-wissen.json

Expected:

{"result":true,"status":"ok","time":0.092931099}

Wait a few seconds, then:

# on rag1
kubectl -n rag logs wache --tail=6

Expected:

21:48:02 200 0.539566 "sammlung": "wissen-qwen3"
21:48:04 200 0.229983 "sammlung": "wissen"
21:48:05 200 0.213133 "sammlung": "wissen"
21:48:06 200 0.407712 "sammlung": "wissen"
21:48:08 200 0.380716 "sammlung": "wissen"
21:48:09 200 0.388082 "sammlung": "wissen"

What you see: The next question after the call already came from wissen – with the old model and the old threshold, because those are on the old sign. No restart, no deployment.

Step 2 – and forward again. The test bench decided for wissen-qwen3; so you hang the sign back.

# on rag1
date -u +%T

Expected:

21:48:09
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < umhaengen-qwen3.json

Expected:

{"result":true,"status":"ok","time":0.10282641}
# on rag1
kubectl -n rag logs wache --tail=6

Expected:

21:48:09 200 0.388082 "sammlung": "wissen"
21:48:10 200 0.231487 "sammlung": "wissen-qwen3"
21:48:12 200 0.370111 "sammlung": "wissen-qwen3"
21:48:13 200 0.277819 "sammlung": "wissen-qwen3"
21:48:15 200 0.457220 "sammlung": "wissen-qwen3"
21:48:16 200 0.210007 "sammlung": "wissen-qwen3"

Step 3 – the watch’s balance. The watch ran through two rollouts and four moves of the sign. You count its lines.

# on rag1
kubectl -n rag logs wache | grep -c ' 200 '

Expected:

97
# on rag1
kubectl -n rag logs wache | grep -c -v ' 200 '

Expected:

0

What you see: 97 questions, 97 times 200, not a single one failed. The nine seconds of wrong answers from Drill 6 are included in these 97 – the status alone would never have given them away.

Step 4 – who still points to the old cabinet? Before you think about deleting wissen, you ask which aliases point to a collection.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen/aliases

Expected:

{"result":{"aliases":[]},"status":"ok","time":0.00002332}
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/wissen-qwen3/aliases

Expected:

{"result":{"aliases":[{"alias_name":"auskunft","collection_name":"wissen-qwen3"}]},"status":"ok","time":0.000010186}

What you see: No sign points to wissen. You still do not delete it: as long as it stands, the way back is a call of 0.1 seconds. Once it is gone, the way back is a reindexing of a good four minutes – and only because the source has been complete since Drill 2. Delete the old collection only once the new one has proven itself in operation. In the lab wissen stays.

Deleting a collection that an alias points to also deletes the alias, by the way. In the lab a test collection showed Not found: Collection…doesn't exist! afterwards – via the sign just as via the name. Then the desk would stand in front of a door without a sign.

Step 5 – withdraw the watch.

# on rag1
kubectl -n rag delete pod wache

Expected (in the lab after 31 seconds – the shell in the pod does not react to SIGTERM, Kubernetes waits for the grace period, as on Day 11):

pod "wache" deleted from rag namespace

Remember: The way back is as fast as moving the sign – as long as the old cabinet stands. Delete it only when you really no longer need it, and check beforehand that no sign points to it any more.

Save your progress? Sign up for free

The bill: what the move cost

Item measured Meaning
load the model 59 s, 639 MB on the volume once
fill the second cabinet 258.7 s for 174 cards grows with the stock; the desk keeps answering from the old one meanwhile
memory in the embedding service 2665 MiB instead of 1535 MiB both models loaded as long as the way back is open
memory in Qdrant second collection with two copies stays until the old cabinet is deleted
test bench under 10 s per collection 13 questions without the language model
moving the sign 0.09 to 0.18 s in Qdrant one call, no restart
rollouts of the desk 24 s each, 0 failed requests needed twice: introduce the alias, read the sign
watch in total 97 questions, 97 × 200 including the nine seconds of wrong answers

What stands out: filling the second cabinet and keeping two models ready is what costs. Moving the sign itself costs nothing – provided the desk reads the sign.

If it does not work

Symptom Cause Fix
after moving the sign the desk says “Dazu steht nichts im Handbuch” to everything, status 200, scores around 0.05 the answer service embeds with the old model but searches the new collection (Drill 6) way back, then write the model to the collection and read it in the answer service (Drill 7)
correct questions are rejected after the move the threshold comes from the old model; the new one gives lower scores (Drill 4) determine the threshold for the new model and write it into the metadata
maintenance card missing after reindexing the card existed only in Qdrant, not in the source (Drill 1) add the book to korpus, run the ingestion over the old collection (Drill 2)
new collection has shard_number: 2, replication_factor: 1 created without these settings; Qdrant then spreads one shard per peer without a copy (diagnosis task) delete it and create it again with shard_number 1 and replication_factor 2 (ingest.py from Drill 3)
Not found: Collection … does not exist when moving, alias unchanged typo in the name of the target collection (challenge) check the name, repeat the request – the sign still hangs on the old door
Not found: Collectionauskunftdoesn't exist! the collection the alias pointed to was deleted; the alias disappears with it create the alias again on an existing collection (schild-anlegen.json)

Diagnosis task

The situation: A colleague built the second cabinet with the ingestion code from Day 7. The 1024 happened to fit, the test bench was good, the sign was moved. Two weeks later rag2 fails – and the desk only finds about half of the cards. wissen survived that on Day 11. What is different?

You recreate the situation with an empty collection probe. The code from Day 7 sends exactly this body when it creates a collection:

# on rag1
nano probe.json
~/kurs/13/probe.json new file
{
  "vectors": {
    "size": 1024,
    "distance": "Cosine"
  }
}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X PUT \
  http://qdrant.rag:6333/collections/probe \
  -H 'Content-Type: application/json' -d @- < probe.json

Expected:

{"result":true,"status":"ok","time":0.395957284}

Try it yourself first, then read on.

Solution path.

Step 1 – the settings of the collection.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant.rag:6333/collections/probe > probe-info.json
# on rag1
jq '.result.config.params' probe-info.json

Expected:

{
  "vectors": {
    "size": 1024,
    "distance": "Cosine"
  },
  "shard_number": 2,
  "replication_factor": 1,
  "write_consistency_factor": 1,
  "on_disk_payload": true
}

Step 2 – where the shards live.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant-1.qdrant-headless:6333/collections/probe/cluster \
  > probe-cluster.json
# on rag1
jq '.result' probe-cluster.json

Expected:

{
  "peer_id": 1806199031829577,
  "shard_count": 2,
  "local_shards": [
    {
      "shard_id": 1,
      "points_count": 0,
      "state": "Active"
    }
  ],
  "remote_shards": [
    {
      "shard_id": 0,
      "peer_id": 3100333476874010,
      "state": "Active"
    }
  ],
  "shard_transfers": []
}

The cause: Without settings, Qdrant creates two shards in a cluster with two peers, one per peer, and no copy (replication_factor: 1). Every card then exists exactly once – half on qdrant-0, half on qdrant-1. If a node fails, its half is missing. The replication_factor 2 from Day 11 applies only to the collection you set it on – not to the cluster.

Step 3 – comparison with the correct cabinet.

# on rag1
jq '.result.config.params' qwen3.json

Expected:

{
  "vectors": {
    "size": 1024,
    "distance": "Cosine"
  },
  "shard_number": 1,
  "replication_factor": 2,
  "write_consistency_factor": 1,
  "on_disk_payload": true
}

wissen-qwen3 has one shard with two copies – lines 112 and 113 in ingest.py from Drill 3.

Step 4 – clean up.

# on rag1
kubectl -n rag exec curl -- \
  curl -s -X DELETE http://qdrant.rag:6333/collections/probe

Expected:

{"result":true,"status":"ok","time":0.121264217}

You would treat the colleague’s broken cabinet the same way: build a new collection with ingest.py from Drill 3, check it, move the sign, delete the wrong one. Turning an existing collection into one shard is not possible with a PATCH.

Challenge

When moving the sign, somebody makes a typo: wissen-qwen instead of wissen-qwen3. The request contains delete_alias first and then create_alias. Is the sign gone afterwards? Try it and find out what auskunft points to afterwards.

The author’s solution.

# on rag1
nano tippfehler.json
~/kurs/13/tippfehler.json new file
{
  "actions": [
    {
      "delete_alias": {
        "alias_name": "auskunft"
      }
    },
    {
      "create_alias": {
        "collection_name": "wissen-qwen",
        "alias_name": "auskunft"
      }
    }
  ]
}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST \
  http://qdrant.rag:6333/collections/aliases \
  -H 'Content-Type: application/json' -d @- < tippfehler.json

Expected:

{"status":{"error":"Not found: Collection `wissen-qwen` does not exist"},"time":0.056877342}
# on rag1
kubectl -n rag exec curl -- curl -s http://qdrant.rag:6333/aliases

Expected:

{"result":{"aliases":[{"alias_name":"auskunft","collection_name":"wissen-qwen3"}]},"status":"ok","time":0.000045735}

What you see: The second action failed, and Qdrant did not execute the first one either – the sign still hangs on wissen-qwen3. That is exactly what atomic means: all actions of a request or none. With two separate requests (delete first, then create) the desk would now be without a sign.

Save your progress? Sign up for free

Checkpoint

The sign points to the new cabinet – the output from the challenge. The new cabinet has two active copies; this time you ask the other peer:

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://qdrant-0.qdrant-headless:6333/collections/wissen-qwen3/cluster \
  > qwen3-cluster-0.json
# on rag1
jq '.result' qwen3-cluster-0.json

Expected:

{
  "peer_id": 3100333476874010,
  "shard_count": 1,
  "local_shards": [
    {
      "shard_id": 0,
      "points_count": 174,
      "state": "Active"
    }
  ],
  "remote_shards": [
    {
      "shard_id": 0,
      "peer_id": 1806199031829577,
      "state": "Active"
    }
  ],
  "shard_transfers": []
}

The answer service asks the sign:

# on rag1
kubectl -n rag set env deployment/antwort --list

Expected:

# Deployment antwort, container antwort
SAMMLUNG=auskunft
KARTEN=3
LLM_TIMEOUT=60
MINDEST_SCORE=0.46
RERANK_URL=
PLAETZE=2

MINDEST_SCORE=0.46 now only applies to a collection without metadata. The desk knows the maintenance window after the move, too:

# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < wartung.json > wartung-qwen3.json
# on rag1
jq '{antwort, quellen}' wartung-qwen3.json

Expected:

{
  "antwort": "[1] Das Wartungsfenster für den Kubernetes-Cluster ist jeden Dienstag von 18 bis 20 Uhr.",
  "quellen": [
    {
      "nr": 1,
      "quelle": "nachtrag-wartung.txt",
      "abschnitt": "Wartungsfenster",
      "score": 0.83,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 2,
      "quelle": "k8s-pod-lifecycle.md",
      "abschnitt": "Startup probe",
      "score": 0.457,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 3,
      "quelle": "k8s-pod-lifecycle.md",
      "abschnitt": "Reduced container restart delay",
      "score": 0.445,
      "sammlung": "wissen-qwen3"
    }
  ]
}

The watch is gone:

# on rag1
kubectl -n rag get pod wache

Expected:

Error from server (NotFound): pods "wache" not found

Both ordering systems are loaded – the way back is open:

# on rag1
kubectl -n rag exec deploy/embed -- ollama ps

Expected:

NAME                    ID              SIZE      PROCESSOR    CONTEXT    RUNNER      UNTIL   
qwen3-embedding:0.6b    ac6da0dfba84    1.2 GB    100% CPU     4096       llamacpp    Forever    
bge-m3:latest           790764642607    1.2 GB    100% CPU     4096       llamacpp    Forever    

One sign on wissen-qwen3, two copies with 174 cards, a desk that reads model and threshold behind the sign, the maintenance card from the source – and wissen as the way back.

Test yourself

  1. Why can’t you simply re-embed the cards in wissen one by one with the new model while the desk is open?
  2. After a reindexing a card is missing that used to be found. Where do you look first?
  3. You move the sign and the watch reports only 200. Why is that not yet proof that the move worked?
  4. How would you have recognised in Drill 6 that the desk searches with the wrong model – if you only had the answer service’s log?
  5. Why does the new answer service search with the collection’s real name and not with the alias?
  6. When may you delete the old collection, and what do you check first?

Answers:

  1. Vectors of two models do not fit together. During the rebuild wissen would hold a mix, and every question would search sensibly in only part of the cards. Hence a second cabinet, check, then move the sign.
  2. In the source. The ingestion only builds from what is in korpus; a card that got into Qdrant past it is missing in the new cabinet – and the next run over the old cabinet deletes it there, too (Drill 2: “1 gelöscht”).
  3. The status only says that the desk answered, not what. In Drill 6 wrong answers came with 200 for nine seconds. After every move a content check belongs to it: a question with a known answer, or the test bench via the alias.
  4. By the scores: “keine Karte bester 0.056” for the secret question, which had 0.733 before. Values near zero for questions that are certainly in the stock almost always mean: question and cards come from different models.
  5. So that a request does not change cabinets halfway through. Between looking behind the sign and the search lies the embedding. If the sign is moved at that moment, a search via the alias would land in the new cabinet with the vector of the old model.
  6. When the new collection has proven itself in operation and you no longer need the way back. Beforehand you check with GET /collections/<name>/aliases that no alias points to it any more – otherwise the alias disappears with it and the desk stands in front of a door without a sign.

Interview note

“How do you change the embedding model of a production RAG application?” – Never in place. I build a second collection from the source, with the same replicas and indexes, and compare both with a fixed set of test questions. In the lab: qwen3-embedding:0.6b instead of bge-m3, hits@5 from 0.77 to 0.92, ingestion a good four minutes. The service reads via a Qdrant alias that I move with one atomic request – 0.1 seconds, 97 requests of the watch without an error. The most important point: model and score threshold belong to the collection, not to the service. I store them as collection metadata, and the service reads them behind the alias. Without that, moving the alias with the same dimension silently returns wrong results – in the lab the best score fell from 0.733 to 0.056, with status 200. The old collection stays as the way back until the new one has proven itself.

Enterprise note

In operations reindexing is a planned procedure with approval: one job builds the new collection, a second job runs the test bench and aborts if hits@k or MRR are below the old collection. Only then does a person or a pipeline move the alias. Large stocks need hours instead of minutes; then changes during the build go into both collections, or the ingestion catches up on them after the build via its hashes (Day 6). Many teams give every collection a version number in its name (wissen-v7) and keep track of which model, which chunk size and which corpus state are inside – the collection metadata is the natural place for that. The threshold is recalibrated per model; before/after comparisons also use real, anonymised user questions. Memory for two collections and two models is planned in, because the way back costs exactly these resources. The old collection is deleted after a fixed period – and backed up beforehand (Day 12).

Summary

  • A collection does not know which model it was built with; for wissen it was only in the answer service’s program.
  • The facet on quelle showed ten sources for nine books: the maintenance card from Day 12 had no file. With nachtrag-wartung.txt in korpus the source of truth is complete; the ingestion replaced the hand-made card (1 new, 1 deleted).
  • The second collection wissen-qwen3 was built in 258.7 seconds with one shard, two copies and the model in the metadata, while wissen kept answering.
  • On the test bench qwen3-embedding:0.6b beat the old model: hits@5 0.92 instead of 0.77, MRR 0.78 instead of 0.72. The threshold went down from 0.46 to 0.42 because the new model gives lower scores.
  • An alias auskunft was introduced; the rollout of the answer service ran without a failed request.
  • Moving the sign without a model change at the desk: no error, just wrong answers – best score 0.056, everything “nothing in the handbook”, status 200.
  • The answer service now reads collection, model and threshold behind the alias. Moving the sign and the way back took 0.09 to 0.18 seconds in Qdrant; the watch counted 97 × 200.
  • Without shard_number and replication_factor Qdrant creates a collection without a copy; an alias request with a typo changes nothing (atomic).

Commands at a glance

Command what it does important options
kubectl -n <ns> set env deployment/<name> --list show the environment variables of a deployment --list
curl -X POST …/collections/<name>/facet -d '{"key":…}' count points per value of a payload field exact
curl -X POST …/collections/<name>/points/scroll -d '{"filter":…}' page through points with a filter with_payload, with_vector
kubectl -n <ns> delete job <name> --ignore-not-found remove a job, even if it is already gone --ignore-not-found
kubectl -n rag exec deploy/embed -- ollama pull <model> load a model into the embedding service –
kubectl -n rag exec deploy/embed -- ollama ps loaded models and their memory –
curl -X PUT …/collections/<name> -d '{"vectors":…,"shard_number":1,"replication_factor":2,"metadata":…}' create a collection with copies and metadata shard_number, replication_factor, metadata
curl -X PATCH …/collections/<name> -d '{"metadata":…}' set or extend the metadata of a collection –
curl -X POST …/collections/aliases -d '{"actions":[…]}' create, delete, move aliases – all actions atomic create_alias, delete_alias
curl …/aliases all aliases and their collections –
curl …/collections/<name>/aliases aliases pointing to this collection –
kubectl -n <ns> rollout restart deployment/<name> restart pods, e.g. after a changed ConfigMap –
kubectl -n <ns> logs <pod> \| grep -c -v ' 200 ' count lines without status 200 -c, -v

Contents

More