Day 4: HNSW and filters – signposts in the closed stacks
Goal: measure the search quality of a vector database (recall@10), build the HNSW index and get to know its tuning knobs
hnsw_ef,mandef_constructwith real numbers, search with filters and understand what a payload index is for · Duration: about 120 min · Prerequisite: Day 0 to Day 3
State before this chapter
The collection doku has 13,220 points and no index yet.
From Day 1, the 100 test questions and their exact best hits are
ready.
# on vdb1
ls ~/labor/tag01Expected (excerpt – look for fragen.npy
and wahrheit.json):
aehnlich.py
einbetten.py
fragen.npy
k8s-doku
korpus.jsonl
korpus.py
skalierung.py
suche.py
vektoren.npy
wahrheit.json
wahrheit.py
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/points/count -H 'Content-Type: application/json' -d '{"exact": true}'Expected: "count":13220.
Introduction
So far, Qdrant has answered every question by comparing all 13,220 vectors with the question. That is exact and fast enough for this corpus. With millions of vectors, it no longer is. That is what an index is for: HNSW, a network of links between similar vectors along which the search jumps instead of looking at everything.
An index makes search faster – and less accurate. It finds the best hits only most of the time. How often is measured by a number you calculate for the first time today: recall@10, the share of the truly best ten hits that the search returns. Without this number, every index setting is guesswork.
Along the way you will discover that a measurement can be wrong too: the first number of the day is wrong, even though the search is correct. Finding that out is the most important part of the day.
Today you will learn:
- to measure recall@10 against an exactly computed ground truth – and to count ties correctly,
- to trigger the HNSW index of a collection and watch it being built,
- to weigh
hnsw_ef(search width) against recall and response time, - to see what
mandef_constructdetermine during building, - to search with filters and measure the difference a payload index makes,
- to recognize why a wrong filter value returns not an error but an empty result.
Background
The picture of the day: signposts in the closed stacks
So far, the librarian walks through the entire closed stacks for every question and compares every book. That way she is sure to find the ten best – but it takes time.
With HNSW, a handful of signposts to similar shelves hang on every shelf. The librarian starts somewhere, follows the signpost that leads closer to the question, and stops when none leads any closer. She sees only a small part of the closed stacks – and sometimes misses a good book.
mis the number of signposts per shelf. More signposts, fewer dead ends.ef_constructis the care taken when putting them up: how many candidates do you check before deciding where a signpost points?hnsw_efis the care taken when searching: how many paths does the librarian follow at the same time?
The payload index is a card catalog by department. If someone asks only for books from “tasks”, she looks it up there instead of turning over every book and looking at its label.
And then there are duplicate copies: the same book several times in the holdings. For the question, they are equally good. Which one she brings is chance – and anyone who only looks at the inventory number will take that for an error.
The terms
| Term | Meaning | In the picture |
|---|---|---|
| recall@10 | share of the truly best 10 hits in the result, averaged over all test questions | how many of the right books she brings |
| exact search | every vector is compared, exact: true |
walking through the entire closed stacks |
| HNSW | graph of links between similar vectors, in layers | signposts between shelves |
m |
number of links per vector in the graph | signposts per shelf |
ef_construct |
candidate list when building the graph | care when putting them up |
hnsw_ef |
candidate list when searching; if not specified, equal to
ef_construct |
care when searching |
indexing_threshold |
segment size in KB above which Qdrant builds an HNSW index | when signposts are put up |
| payload index | index over a payload field, e.g. keyword |
card catalog by department |
| facet | count of the values of a field | holdings list per department |
Remember: An index trades accuracy for speed. Whether the trade pays off, only recall@10 tells you – measured against an exact ground truth.
Drill 1: Measuring recall
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: a measurement program for recall@10 and response time – and a first, strange number.
On Day 1 you computed the exact best 10 sections for 100 test
questions (wahrheit.json) and saved the questions as
vectors (fragen.npy). Now you ask Qdrant the same questions
and count how many of the ten right sections come back.
Step 1 – create the working folder.
# on vdb1
mkdir -p ~/labor/tag04# on vdb1
cd ~/labor/tag04Step 2 – write the measurement program.
# on vdb1
nano recall.py"""Misst recall@10 und Antwortzeit einer Collection gegen die Wahrheit aus Tag 1."""
import json
import statistics
import sys
import time
import numpy as np
from qdrant_client import QdrantClient, models
QDRANT, COLLECTION = sys.argv[1], sys.argv[2]
EF = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] != "-" else None # hnsw_ef, "-" = Standard
EXAKT = len(sys.argv) > 4 and sys.argv[4] == "exakt"
fragen = np.load("../tag01/fragen.npy")
wahrheit = json.load(open("../tag01/wahrheit.json", encoding="utf-8"))
client = QdrantClient(url=QDRANT, timeout=60)
parameter = models.SearchParams(hnsw_ef=EF, exact=EXAKT)
treffer_gesamt, zeiten = 0, []
for vektor, w in zip(fragen, wahrheit):
beginn = time.perf_counter()
punkte = client.query_points(COLLECTION, query=vektor.tolist(), limit=10,
search_params=parameter).points
zeiten.append((time.perf_counter() - beginn) * 1000)
treffer_gesamt += len({p.id for p in punkte} & set(w["beste10"]))
zeiten.sort()
print(f"recall@10 {treffer_gesamt / 1000:.3f} · Median {statistics.median(zeiten):.1f} ms"
f" · p95 {zeiten[94]:.1f} ms · {len(fragen)} Fragen")| Line | Meaning |
|---|---|
sys.argv[3] |
optional hnsw_ef; - means “Qdrant’s
default” |
sys.argv[4] == "exakt" |
optional: Qdrant should search without an index |
SearchParams(hnsw_ef=…, exact=…) |
search parameters for every request |
{p.id …} & set(w["beste10"]) |
intersection: which of the ten right IDs are in the result? |
treffer_gesamt / 1000 |
100 questions × 10 hits = 1,000 possible hits |
zeiten[94] |
the 95th of 100 sorted values: the 95th percentile (p95) |
The program measures the time on vdb1 – it includes the trip over the network and the Python library, not just the search in Qdrant.
Step 3 – measure.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 dokuExpected:
recall@10 0.742 · Median 12.8 ms · p95 16.0 ms · 100 Fragen
What you see: 0.742 – three out of four right hits.
And yet doku has no index at all yet (Day 2:
indexed_vectors_count 0). Without an index, Qdrant searches
exactly. Where does the missing quarter come from?
Step 4 – have Qdrant search exactly, explicitly.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 doku - exakt-leaveshnsw_efat the default.exaktsetsexact: true: Qdrant compares with every vector, regardless of whether an index exists.
Expected:
recall@10 0.742 · Median 12.8 ms · p95 19.6 ms · 100 Fragen
What you see: Even the guaranteed exact search reaches only 0.742. That makes it clear: it is not the search that is inaccurate, but the measurement that counts wrongly. Drill 2 finds out why.
Remember: Before you blame an index, measure exact search with the same program. If it too is below 1.0, your measurement is wrong.
Save your progress? Sign up for free
Drill 2: The duplicate copies
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: the cause of the wrong number and a measurement program that counts correctly.
Step 1 – look at one question in detail. A small program shows, for the first test question, the IDs and similarities from Qdrant and from the ground truth side by side.
# on vdb1
nano vergleich.py"""Zeigt für die erste Testfrage, was Qdrant liefert und was die Wahrheit sagt."""
import json
import sys
import numpy as np
from qdrant_client import QdrantClient, models
QDRANT = sys.argv[1]
fragen = np.load("../tag01/fragen.npy")
wahrheit = json.load(open("../tag01/wahrheit.json", encoding="utf-8"))
bestand = np.load("../tag01/vektoren.npy")
bestand = bestand / np.linalg.norm(bestand, axis=1, keepdims=True)
client = QdrantClient(url=QDRANT, timeout=60)
punkte = client.query_points("doku", query=fragen[0].tolist(), limit=10,
search_params=models.SearchParams(exact=True)).points
print("Frage: ", wahrheit[0]["frage"])
print("Qdrant IDs: ", [p.id for p in punkte])
print("Wahrheit IDs: ", wahrheit[0]["beste10"])
print("Qdrant Scores: ", [round(p.score, 4) for p in punkte])
print("Wahrheit Scores:", [round(float(bestand[i] @ fragen[0]), 4) for i in wahrheit[0]["beste10"]])The last line computes the similarity of the ten right sections itself, as on Day 1: normalized vectors, dot product.
# on vdb1
~/werkbank/bin/python vergleich.py http://10.43.151.237:6333Expected:
Frage: Query Parameters
Qdrant IDs: [9840, 1811, 4546, 4483, 4465, 4500, 4508, 4559, 4567, 4454]
Wahrheit IDs: [9840, 1811, 5091, 5115, 5156, 5019, 5164, 5098, 4983, 4977]
Qdrant Scores: [0.6735, 0.6598, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572]
Wahrheit Scores: [0.6735, 0.6598, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572, 0.6572]
What you see: Only the first two IDs match – but all ten similarities are the same. From place 3 on, eight sections have exactly 0.6572. Qdrant and Day 1 simply selected different sections with the same value. Both results are equally good.
Step 2 – look at two of the sections. The line
number in korpus.jsonl is ID + 1.
# on vdb1
cut -c1-150 ../tag01/korpus.jsonl | sed -n '4547p;5092p'cut -c1-150shortens every line to 150 characters.sed -n '4547p;5092p'prints only lines 4547 and 5092 (IDs 4546 and 5091).
Expected:
{"id": 4546, "bereich": "reference", "pfad": "reference/kubectl/generated/kubectl_certificate/kubectl_certificate_approve.md", "titel": "", "text": "-
{"id": 5091, "bereich": "reference", "pfad": "reference/kubectl/generated/kubectl_rollout/kubectl_rollout_resume.md", "titel": "", "text": "-s, --serv
What you see: Two generated pages of the kubectl
reference, both without a heading. Each of these pages ends with the
same list of global options (-s, --server …) – the same
text, so the same vector, so the same similarity.
Step 3 – how many duplicate copies are there?
# on vdb1
nano duplikate.py"""Zählt Abschnitte mit wortgleichem Text im Bestand."""
import json
from collections import Counter
eintraege = [json.loads(z) for z in open("../tag01/korpus.jsonl", encoding="utf-8")]
zaehler = Counter(e["text"] for e in eintraege)
mehrfach = {text: n for text, n in zaehler.items() if n > 1}
print(f"{len(eintraege)} Abschnitte, {len(zaehler)} verschiedene Texte")
print(f"{len(mehrfach)} Texte kommen mehrfach vor, zusammen {sum(mehrfach.values())} Abschnitte")
text, n = max(mehrfach.items(), key=lambda x: x[1])
print(f"häufigster Text ({n}×): {text[:70]}…")Counter counts how often each text occurs.
# on vdb1
~/werkbank/bin/python duplikate.pyExpected:
13220 Abschnitte, 8920 verschiedene Texte
131 Texte kommen mehrfach vor, zusammen 4431 Abschnitte
häufigster Text (342×): It is highly recommended that resourceVersionMatch be set for list cal…
What you see: A third of the corpus (4,431 sections) are duplicate copies of only 131 texts, one of them 342 times. Generated reference pages repeat building blocks. For every question whose best hits lie in such a group, the choice among ties is arbitrary.
Step 4 – repair the measurement. Every hit is correct that is at least as similar as the tenth-best real neighbor – regardless of its ID.
# on vdb1
nano recall.py"""Misst recall@10 und Antwortzeit einer Collection gegen die Wahrheit aus Tag 1."""
import json
import statistics
import sys
import time
import numpy as np
from qdrant_client import QdrantClient, models
QDRANT, COLLECTION = sys.argv[1], sys.argv[2]
EF = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] != "-" else None # hnsw_ef, "-" = Standard
EXAKT = len(sys.argv) > 4 and sys.argv[4] == "exakt"
fragen = np.load("../tag01/fragen.npy")
wahrheit = json.load(open("../tag01/wahrheit.json", encoding="utf-8"))
bestand = np.load("../tag01/vektoren.npy")
bestand = bestand / np.linalg.norm(bestand, axis=1, keepdims=True)
client = QdrantClient(url=QDRANT, timeout=60)
parameter = models.SearchParams(hnsw_ef=EF, exact=EXAKT)
treffer_gesamt, zeiten = 0, []
for vektor, w in zip(fragen, wahrheit):
beginn = time.perf_counter()
punkte = client.query_points(COLLECTION, query=vektor.tolist(), limit=10,
search_params=parameter).points
zeiten.append((time.perf_counter() - beginn) * 1000)
# Gleichstände zählen mit: richtig ist jeder Treffer, der mindestens so
# ähnlich ist wie der zehntbeste echte Nachbar
grenze = min(float(bestand[i] @ vektor) for i in w["beste10"])
treffer_gesamt += sum(1 for p in punkte if float(bestand[p.id] @ vektor) >= grenze - 1e-6)
zeiten.sort()
print(f"recall@10 {treffer_gesamt / 1000:.3f} · Median {statistics.median(zeiten):.1f} ms"
f" · p95 {zeiten[94]:.1f} ms · {len(fragen)} Fragen")| Line | Meaning |
|---|---|
| 16–17 | load and normalize the vectors from Day 1 to compute similarities yourself |
grenze = min(…) |
similarity of the tenth-best real neighbor |
>= grenze - 1e-6 |
a hit counts if it is at least as similar; 1e-6 absorbs
rounding differences between Qdrant and numpy |
Step 5 – measure again.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 doku - exaktExpected:
recall@10 1.000 · Median 12.6 ms · p95 17.4 ms · 100 Fragen
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 dokuExpected:
recall@10 1.000 · Median 13.2 ms · p95 18.4 ms · 100 Fragen
What you see: 1.000 for both. The search was exact
all along – now the measurement says so too. From here on,
recall.py is your yardstick for every index setting.
Remember: Duplicate copies are normal in real document collections. A recall that only compares IDs punishes the search for ties. Count by similarity, not by inventory number.
Save your progress? Sign up for free
Drill 3: Building the index
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: an HNSW index over all 13,220 vectors.
On Day 2 you saw why doku has no index: each of the four
segments is just below the indexing_threshold of 10,000 KB.
If you lower the threshold, the optimizer builds the index.
Step 1 – note the time.
# on vdb1
date +%TExpected (your time; vdb1 shows UTC):
08:58:40
Step 2 – lower the threshold.
# on vdb1
curl -s -X PATCH http://10.43.151.237:6333/collections/doku -H 'Content-Type: application/json' -d '{"optimizers_config": {"indexing_threshold": 1000}}'"indexing_threshold": 1000 means: every segment from
1,000 KB on gets an HNSW index – that is, all four.
Expected:
{"result":true,"status":"ok","time":0.140695332}
Step 3 – watch. Query the state and repeat the two
commands until status is green. Run
date +%T first, then you see the time.
# on vdb1
curl -s http://10.43.151.237:6333/collections/doku -o doku.json# on vdb1
jq -c '.result | {status, optimizer_status, indexed_vectors_count, segments_count}' doku.jsonExpected (excerpt from several repetitions, each with the time before it):
08:58:41 {"status":"yellow","optimizer_status":"ok","indexed_vectors_count":0,"segments_count":4}
08:58:43 {"status":"yellow","optimizer_status":"ok","indexed_vectors_count":6624,"segments_count":3}
08:58:44 {"status":"yellow","optimizer_status":"ok","indexed_vectors_count":9924,"segments_count":4}
08:58:44 {"status":"green","optimizer_status":"ok","indexed_vectors_count":13220,"segments_count":4}
What you see: yellow means: the
optimizer is working. indexed_vectors_count rises segment
by segment (around 3,300 per segment), and four seconds after the PATCH,
doku is green with 13,220 indexed vectors. The
number of segments briefly jumps to 3 and back to 4: the optimizer swaps
segments for indexed ones.
Step 4 – what the index is on disk. The segments now have new names.
# on vdb1
kubectl -n qdrant exec qdrant-0 -c qdrant -- ls /qdrant/storage/collections/doku/0/segmentsExpected (different names for you):
003630a7-5077-44b2-a89f-8e47af5ef8e4
b8ee847a-607f-432f-9de9-d95cc7531371
e25559ed-046b-4e99-b4c5-04115a64d9b5
e93ce2f6-376f-48cc-97c0-f00779b5dbc3
Insert one of your names:
# on vdb1
kubectl -n qdrant exec qdrant-0 -c qdrant -- ls -la /qdrant/storage/collections/doku/0/segments/b8ee847a-607f-432f-9de9-d95cc7531371/vector_indexExpected:
total 96
drwxr-sr-x 2 1000 3000 4096 Dec 5 08:58 .
drwxr-sr-x 6 1000 3000 4096 Dec 5 08:58 ..
-rw-r--r-- 1 1000 3000 72 Dec 5 08:58 graph.bin
-rw-r--r-- 1 1000 3000 159 Dec 5 08:58 hnsw_config.json
-rw-r--r-- 1 1000 3000 79880 Dec 5 08:58 links_compressed.bin
# on vdb1
kubectl -n qdrant exec qdrant-0 -c qdrant -- du -sh /qdrant/storage/collections/doku/0/segments/b8ee847a-607f-432f-9de9-d95cc7531371/vector_index /qdrant/storage/collections/doku/0/segments/b8ee847a-607f-432f-9de9-d95cc7531371/vector_storageExpected:
92K /qdrant/storage/collections/doku/0/segments/b8ee847a-607f-432f-9de9-d95cc7531371/vector_index
9.7M /qdrant/storage/collections/doku/0/segments/b8ee847a-607f-432f-9de9-d95cc7531371/vector_storage
What you see: The graph
(links_compressed.bin, the signposts) occupies 92 K, the
vectors of the same segment 9.7 M – a hundred times more. Qdrant stores
the links compressed. So whoever plans storage plans mainly for the
vectors (Day 9).
Remember: The HNSW index is built in the background, segment by segment, and
greentells you when it is finished. The signposts are small – the vectors remain what costs space.
Save your progress? Sign up for free
Drill 4: What the index costs and what it brings
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: recall and response time with an index, measured from the outside and inside Qdrant.
Step 1 – recall with an index.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 dokuExpected (first run after building):
recall@10 0.992 · Median 33.8 ms · p95 53.7 ms · 100 Fragen
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 dokuExpected (second run):
recall@10 0.992 · Median 12.9 ms · p95 17.4 ms · 100 Fragen
What you see: The recall drops from 1.000 to 0.992: 8 of 1,000 hits are missing – that is the price of the signposts. The first run was almost three times as slow as the second; the freshly written index files were only loaded on first access. So never measure only once.
Step 2 – has it become faster? From the outside,
hardly: 12.9 ms with an index, 13.2 ms before. With 13,220 points,
comparing with all vectors is so cheap that the trip via HTTP and Python
determines the time. The search time inside Qdrant is in every
response in the time field. With
"query": 1702, Qdrant searches for the neighbors of an
existing point – for this you don’t need a vector in the command.
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/points/query -H 'Content-Type: application/json' -d '{"query": 1702, "limit": 10, "params": {"exact": true}}' -o q.json# on vdb1
jq -c '{zeit: .time, ids: [.result.points[].id]}' q.jsonExpected:
{"zeit":0.009627477,"ids":[1776,2674,3192,7114,1705,1810,1732,7105,1706,12940]}
Now the same without "params", that is, with the
index:
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/points/query -H 'Content-Type: application/json' -d '{"query": 1702, "limit": 10}' -o q.json# on vdb1
jq -c '{zeit: .time, ids: [.result.points[].id]}' q.jsonExpected:
{"zeit":0.005342894,"ids":[1776,2674,3192,7114,1705,1810,1732,7105,1706,12940]}
What you see: The same ten hits, in Qdrant 9.6 ms exact versus 5.3 ms with the index (a second pass: 7.9 versus 5.1 ms). Point 1702 itself is missing from the result – Qdrant excludes it when searching for its neighbors. With millions of vectors, the gap becomes large; Day 8 measures that.
Remember: With small corpora, an index hardly saves time but costs recall. Measure the search time in Qdrant (
time) separately from the time your program sees.
Save your progress? Sign up for free
Drill 5: The search width
hnsw_ef
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: a table that shows how much recall each level of search width brings.
You can change hnsw_ef with every request without
rebuilding the index. Measure six levels. Write down beforehand what you
expect.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 doku 4Expected:
recall@10 0.926 · Median 13.1 ms · p95 23.8 ms · 100 Fragen
Repeat the command with 8, 16,
32, 64, 100 and 128
in place of the 4.
Expected (all seven runs):
hnsw_ef |
recall@10 | Median | p95 |
|---|---|---|---|
| 4 | 0.926 | 13.1 ms | 23.8 ms |
| 8 | 0.926 | 13.1 ms | 17.9 ms |
| 16 | 0.951 | 12.0 ms | 16.0 ms |
| 32 | 0.977 | 12.5 ms | 15.8 ms |
| 64 | 0.991 | 13.3 ms | 16.7 ms |
| 100 | 0.992 | 12.9 ms | 19.1 ms |
| 128 | 0.993 | 12.3 ms | 16.7 ms |
What you see:
hnsw_ef100 delivers exactly the 0.992 from Drill 4. If not specified, Qdrant uses the value ofef_constructforhnsw_ef– and that is 100.- 4 and 8 deliver the same – both are below the ten requested hits.
- From 16 to 64 the recall rises clearly, after that hardly at all. The rest depends on the graph itself.
- The time from the outside doesn’t change – here too, the trip via HTTP determines the number.
Remember:
hnsw_efis the runtime knob: more recall for more compute time, adjustable per request. Above a certain value it brings nothing more – then the graph has to get better.
Save your progress? Sign up for free
Drill 6: The building plan m and
ef_construct
Where you are: on vdb1.
What you have afterwards: a second collection with a sparse graph and proof that a bad graph cannot be rescued at runtime.
m and ef_construct only take effect during
building. To compare them, you create a second collection with much
smaller values: m 4 instead of 16,
ef_construct 16 instead of 100.
Step 1 – create the collection.
# on vdb1
curl -s -X PUT http://10.43.151.237:6333/collections/doku_m4 -H 'Content-Type: application/json' -d '{"vectors": {"size": 768, "distance": "Cosine"}, "hnsw_config": {"m": 4, "ef_construct": 16}, "optimizers_config": {"indexing_threshold": 1000}}'| Setting | Value | Meaning |
|---|---|---|
vectors |
768, Cosine | like doku |
hnsw_config.m |
4 | four links per vector instead of 16 |
hnsw_config.ef_construct |
16 | small candidate list during building |
optimizers_config.indexing_threshold |
1000 | index immediately, like doku now |
Expected:
{"result":true,"status":"ok","time":0.546547655}
Step 2 – load the corpus. laden.py from
Day 2 takes the name of the collection as an argument.
# on vdb1
cd ~/labor/tag02# on vdb1
~/werkbank/bin/python laden.py http://10.43.151.237:6333 doku_m4Expected:
13220 Punkte in 23.4 s geladen
# on vdb1
cd ~/labor/tag04# on vdb1
curl -s http://10.43.151.237:6333/collections/doku_m4 -o m4.json# on vdb1
jq -c '.result | {status, indexed_vectors_count, segments_count}' m4.jsonExpected:
{"status":"green","indexed_vectors_count":13220,"segments_count":4}
Step 3 – measure.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 doku_m4Expected (second run):
recall@10 0.663 · Median 9.6 ms · p95 13.1 ms · 100 Fragen
Repeat with 16, 64, 128 and
256 as the third argument.
Expected:
| Collection | hnsw_ef |
recall@10 |
|---|---|---|
doku_m4 |
default (= 16) | 0.663 |
doku_m4 |
16 | 0.663 |
doku_m4 |
64 | 0.822 |
doku_m4 |
128 | 0.885 |
doku_m4 |
256 | 0.931 |
doku (m 16, ef_construct 100) |
default (= 100) | 0.992 |
What you see: With four signposts per shelf, the
search finds only two thirds of the right hits. Even with
hnsw_ef 256 – searching more than twice as widely as in
doku – it stays at 0.931 and doesn’t reach
doku. Whoever builds too sparingly cannot compensate for it
at runtime.
Step 4 – clean up.
# on vdb1
curl -s -X DELETE http://10.43.151.237:6333/collections/doku_m4Expected:
{"result":true,"status":"ok","time":0.192432321}
Remember:
mandef_constructdetermine how good the graph is;hnsw_efonly how thoroughly it is searched. The build values can only be changed by rebuilding the index.
Save your progress? Sign up for free
Drill 7: Searching with filters
Where you are: on vdb1, in
~/labor/tag04.What you have afterwards: filtered searches with measured recall, before and after a payload index.
Every point has the field bereich in its payload: which
part of the documentation it comes from. A filter restricts the search
to it – “only guides from tasks”.
Step 1 – which areas are there? Qdrant can count the values of a field (facet).
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/facet -H 'Content-Type: application/json' -d '{"key": "bereich"}'Expected:
{"status":{"error":"Wrong input: No appropriate index for faceting: `bereich`. Please create one to facet on this field. Check https://qdrant.tech/documentation/concepts/indexing/#payload-index to see which payload schemas support Match conditions"},"time":0.001570461}
What you see: No counting without a payload index. That comes in step 4. First you measure how the filtered search works without an index.
Step 2 – the measurement program for filtered searches. It computes the ground truth itself: the exact best ten within the area.
# on vdb1
nano frecall.py"""Misst recall@10 einer gefilterten Suche: nur Abschnitte eines Bereichs."""
import json
import statistics
import sys
import time
import numpy as np
from qdrant_client import QdrantClient, models
QDRANT, COLLECTION, BEREICH = sys.argv[1], sys.argv[2], sys.argv[3]
fragen = np.load("../tag01/fragen.npy")
bestand = np.load("../tag01/vektoren.npy")
bestand = bestand / np.linalg.norm(bestand, axis=1, keepdims=True)
bereiche = np.array([json.loads(z)["bereich"] for z in open("../tag01/korpus.jsonl", encoding="utf-8")])
im_bereich = np.where(bereiche == BEREICH)[0]
client = QdrantClient(url=QDRANT, timeout=60)
filter_ = models.Filter(must=[models.FieldCondition(key="bereich", match=models.MatchValue(value=BEREICH))])
treffer_gesamt, falscher_bereich, zeiten = 0, 0, []
for vektor in fragen:
beginn = time.perf_counter()
punkte = client.query_points(COLLECTION, query=vektor.tolist(), limit=10, query_filter=filter_).points
zeiten.append((time.perf_counter() - beginn) * 1000)
werte = bestand[im_bereich] @ vektor # exakte Wahrheit, nur im Bereich
grenze = np.sort(werte)[-10]
treffer_gesamt += sum(1 for p in punkte if float(bestand[p.id] @ vektor) >= grenze - 1e-6)
falscher_bereich += sum(1 for p in punkte if bereiche[p.id] != BEREICH)
zeiten.sort()
print(f"{BEREICH}: {len(im_bereich)} Abschnitte · recall@10 {treffer_gesamt / 1000:.3f}"
f" · falscher Bereich {falscher_bereich} · Median {statistics.median(zeiten):.1f} ms")| Line | Meaning |
|---|---|
im_bereich |
numbers of all sections in the selected area |
models.Filter(must=[…]) |
condition every hit must satisfy |
MatchValue(value=BEREICH) |
bereich must have exactly this value |
np.sort(werte)[-10] |
similarity of the tenth-best section in the area |
falscher_bereich |
cross-check: hits that violate the filter |
Step 3 – measure, without a payload index. Two areas: a large one and a small one.
# on vdb1
~/werkbank/bin/python frecall.py http://10.43.151.237:6333 doku tasksExpected:
tasks: 1747 Abschnitte · recall@10 1.000 · falscher Bereich 0 · Median 46.5 ms
# on vdb1
~/werkbank/bin/python frecall.py http://10.43.151.237:6333 doku setupExpected:
setup: 235 Abschnitte · recall@10 1.000 · falscher Bereich 0 · Median 47.4 ms
What you see: Correct – full recall, no hit from a wrong area. But 46 to 47 ms instead of 13 ms without a filter. Without a card catalog, Qdrant has to turn over the label for every candidate.
Step 4 – create the payload index.
# on vdb1
curl -s -X PUT http://10.43.151.237:6333/collections/doku/index -H 'Content-Type: application/json' -d '{"field_name": "bereich", "field_schema": "keyword"}'field_nameis the payload field.field_schema: keywordmeans: exact strings, suitable for “equals” filters and facets.
Expected:
{"result":{"operation_id":106,"status":"acknowledged"},"status":"ok","time":0.131403942}
# on vdb1
curl -s http://10.43.151.237:6333/collections/doku -o doku.json# on vdb1
jq -c '.result | {status, indexed_vectors_count, payload_schema}' doku.jsonExpected:
{"status":"green","indexed_vectors_count":13220,"payload_schema":{"bereich":{"data_type":"keyword","points":13220}}}
Step 5 – now count.
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/facet -H 'Content-Type: application/json' -d '{"key": "bereich"}'Expected:
{"result":{"hits":[{"value":"reference","count":8267},{"value":"concepts","count":2623},{"value":"tasks","count":1747},{"value":"tutorials","count":348},{"value":"setup","count":235}]},"status":"ok","time":0.002248898}
What you see: Five areas. Almost two thirds are reference – that is also where the duplicate copies from Drill 2 are.
Step 6 – measure again.
# on vdb1
~/werkbank/bin/python frecall.py http://10.43.151.237:6333 doku tasksExpected:
tasks: 1747 Abschnitte · recall@10 1.000 · falscher Bereich 0 · Median 12.1 ms
# on vdb1
~/werkbank/bin/python frecall.py http://10.43.151.237:6333 doku setupExpected:
setup: 235 Abschnitte · recall@10 1.000 · falscher Bereich 0 · Median 9.5 ms
What you see: Just as correct, but 12.1 instead of 46.5 ms and 9.5 instead of 47.4 ms – as fast as without a filter, for the small area even faster. A second pass gave 11.5 and 10.0 ms.
Remember: Every field you filter by needs a payload index – ideally created before loading. Without it the result is correct, but every filtered search becomes slower.
Save your progress? Sign up for free
Diagnosis task: The filter that finds nothing
A colleague builds in a search for “guides only”. It
never returns a hit and never an
error. His condition:
{"key": "bereich", "match": {"value": "Tasks"}}.
Find the cause before you read on.
Solution, step by step. Count the points the filter covers – once with his value, once with the value from the facet.
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/points/count -H 'Content-Type: application/json' -d '{"exact": true, "filter": {"must": [{"key": "bereich", "match": {"value": "Tasks"}}]}}'Expected:
{"result":{"count":0},"status":"ok","time":0.000399228}
# on vdb1
curl -s -X POST http://10.43.151.237:6333/collections/doku/points/count -H 'Content-Type: application/json' -d '{"exact": true, "filter": {"must": [{"key": "bereich", "match": {"value": "tasks"}}]}}'Expected:
{"result":{"count":1747},"status":"ok","time":0.002601695}
The cause: keyword compares character
by character – Tasks is not tasks. For Qdrant
this is not an error but a valid condition that simply matches no
point.
The fix: take the value from the facet
(tasks), and normalize the spelling of user input before it
goes into the filter. And: a search that returns zero hits is a warning
sign in operations, not a normal answer.
Remember: A wrong filter value produces no error, but silence. Check filter values against the facet and count with
points/countbefore you search.
Checkpoint
# on vdb1
curl -s http://10.43.151.237:6333/collectionsExpected: only the collection doku.
# on vdb1
curl -s http://10.43.151.237:6333/collections/doku -o doku.json# on vdb1
jq -c '.result | {status, indexed_vectors_count, payload_schema}' doku.jsonExpected: green,
indexed_vectors_count 13220, payload_schema
with bereich as keyword.
# on vdb1
~/werkbank/bin/python recall.py http://10.43.151.237:6333 dokuExpected: recall@10 around 0.99.
Test yourself
- Your recall program reports 0.74 for a collection without an index. What do you check first?
- Why is a search that returns different IDs from the ground truth in case of ties still correct?
- You increase
hnsw_effrom 128 to 512 and the recall hardly rises. What helps then? - Why was the search with an index, measured from the outside, hardly faster than without?
- What happens without a payload index when you filter by
bereich– and what happens with one? - How do you recognize a filter value that matches no point?
Answers:
- Exact search with the same program (
exact: true). If it too is below 1.0, the measurement is wrong – today because of ties caused by duplicate copies. - Because the returned sections are just as similar as the expected ones. For the question, duplicate copies are equivalent; recall is therefore counted by similarity.
- A better graph: higher
mandef_construct, that is, rebuilding the index.doku_m4reached only 0.931 even withhnsw_ef256. - With 13,220 points, comparing with all vectors is cheap; the time is
determined by the trip via HTTP and Python. In Qdrant
(
time) it was 9.6 versus 5.3 ms. - Without an index, the result is correct but slower (46 instead of 13
ms); facets don’t work at all. With a
keywordindex, the filtered search is as fast as the unfiltered one. points/countwith the filter returns 0. The facet shows the correct values.
Interview note
“How do you tune an HNSW index?” – First create a ground
truth: the exact best hits for a few hundred real questions. Then
measure recall@k against this ground truth, with ties counted by
similarity. At runtime, hnsw_ef trades recall against
latency, per request. If that’s not enough, rebuild the graph with
higher m and ef_construct – it costs build
time and some memory. Create payload indexes for filter fields before
loading. And always measure latency twice: in the server and at the
client.
Enterprise note
In production, the ground truth is a maintained test dataset of real search queries, and recall@10 runs as a regression test on every change to the model, chunking or index. Duplicate copies are detected and merged during ingestion – a third duplicates as today costs storage and pushes other hits out of the top 10. Payload indexes belong in the definition of the collection (as code, Day 15), not in a later manual step. Multi-tenant searches always filter by tenant – without an index a performance problem, with a wrong value a silent data loss.
Summary
- recall@10 measures how many of the truly best ten hits the search delivers – against an exact ground truth from Day 1.
- The first measurement (0.742) was wrong: 4,431 sections are duplicate copies, and ties were counted as errors. Counted by similarity: 1.000.
- After lowering the
indexing_threshold, Qdrant built the HNSW index in four seconds; the graph is a hundred times smaller than the vectors. - With an index: recall 0.992.
hnsw_ef16 to 128 gave 0.951 to 0.993; if not specified,ef_construct- applies.
m4 /ef_construct16 gave 0.663, and even withhnsw_ef256 only 0.931.- Filtered search: always correct, 46 ms without a payload index, 12 ms with one. A wrong filter value returns zero hits without an error.
Commands at a glance
| Command | Purpose |
|---|---|
~/werkbank/bin/python recall.py <qdrant-url> <collection> [hnsw_ef\|-] [exakt] |
measure recall@10 and response time |
~/werkbank/bin/python duplikate.py |
count duplicate copies in the corpus |
curl -s -X PATCH http://<ip>:6333/collections/doku -H 'Content-Type: application/json' -d '{"optimizers_config": {"indexing_threshold": 1000}}' |
trigger the HNSW index |
curl -s -X POST http://<ip>:6333/collections/doku/points/query -H 'Content-Type: application/json' -d '{"query": 1702, "limit": 10}' -o q.json |
neighbors of a point, time in Qdrant |
curl -s -X PUT http://<ip>:6333/collections/<name> -H 'Content-Type: application/json' -d '{… "hnsw_config": {"m": 4, "ef_construct": 16} …}' |
collection with its own building plan |
curl -s -X PUT http://<ip>:6333/collections/doku/index -H 'Content-Type: application/json' -d '{"field_name": "bereich", "field_schema": "keyword"}' |
create a payload index |
curl -s -X POST http://<ip>:6333/collections/doku/facet -H 'Content-Type: application/json' -d '{"key": "bereich"}' |
count the values of a field |
~/werkbank/bin/python frecall.py <qdrant-url> <collection> <area> |
recall of a filtered search |
curl -s -X POST http://<ip>:6333/collections/doku/points/count -H 'Content-Type: application/json' -d '{"exact": true, "filter": {…}}' |
count the hits of a filter |