Day 13: pgvector – the branch in the city archive
Goal: run PostgreSQL with pgvector via CloudNativePG, load the same data as in Qdrant, build and measure HNSW and IVFFlat, recognize the filter trap and compare both systems with real numbers · Duration: about 150 min · Prerequisite: Day 0 to Day 12
State before this chapter
Three Qdrant pods are running with TLS, API keys, NetworkPolicies and
Pod Security restricted; the monitoring from Day 11 and the
off-site store from Day 12 are in place on vdb1.
# on vdb1
kubectl -n qdrant get pods -o wideExpected (your IPs, nodes and ages will differ):
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
qdrant-0 1/1 Running 0 24m 10.42.1.61 vdb2 <none> <none>
qdrant-1 1/1 Running 0 25m 10.42.3.8 vdb4 <none> <none>
qdrant-2 1/1 Running 0 26m 10.42.2.18 vdb3 <none> <none>
Today you need two sets of files from earlier days that are on vdb1:
texts and vectors of doku from Day 1
(~/labor/tag01/korpus.jsonl,
~/labor/tag01/vektoren.npy, 13,220 × 768) and glove-100
from Day 8 (~/labor/tag08/glove-bestand.npy,
glove-fragen.npy, glove-wahrheit.npy). All
commands run on vdb1 in the folder ~/labor/tag13:
# on vdb1
mkdir -p ~/labor/tag13
cd ~/labor/tag13Introduction
So far every book has stood in a library built only for books. Many teams ask a different question first: “We already have PostgreSQL. Isn’t that enough?” With the extension pgvector, PostgreSQL can store vectors, compute distances and build the same index types you know from Qdrant.
Today you put that to the test – not with opinions, but with the same
data on the same hardware: doku with 13,220 sections and
glove-100 with 1,183,514 vectors. PostgreSQL runs the way you operate it
on Kubernetes: with the operator CloudNativePG.
Three real stumbling blocks await you along the way: an index build that takes eighteen minutes instead of a few, a filtered search that returns three hits instead of ten, and an index that PostgreSQL simply does not use.
Today you will learn:
- to install CloudNativePG and create a PostgreSQL cluster with pgvector,
- to load vectors quickly with
COPYand see where PostgreSQL stores them, - to build HNSW and IVFFlat indexes and measure their build time, size and effect in the query plan,
- to use
maintenance_work_mem,hnsw.ef_search,ivfflat.probesandhnsw.iterative_scandeliberately, - to measure recall@10 and p50/p95/p99 for pgvector and compare them with Qdrant,
- to recognize when PostgreSQL does not use a vector index.
Background
The picture of the day: the branch in the city archive
The city archive in the town hall has long managed everything else: registration files, invoices, contracts. It has safe-deposit boxes, an accession register that never loses anything, and strict rules about who may see which file. Instead of building a new library, the city sets up a branch there: a room with shelves in which books stand by shelf mark.
The advantage: one building, one bunch of keys, one accession
register – a book and its lending card are entered in the same booking.
The price: the archivists are not librarians. Very thick books do not
fit on the shelf and go into a side room (TOAST). To
build the signpost system they have a worktable
(maintenance_work_mem); if the plan is bigger than the
table, they have to walk to the storeroom for every step. And if you
only want books from one department, they show you the best 40 hits and
sort them out only afterwards – in the worst case three
are left.
There is also a second kind of order: topic boxes
(IVFFlat). Every book goes into the box whose topic is closest to it.
Whoever searches opens the one box or the few boxes that match the
question (probes).
The terms
| Term | Meaning | In the picture |
|---|---|---|
| pgvector | extension for PostgreSQL: data type vector, distance
operators, HNSW and IVFFlat |
branch in the archive |
| CloudNativePG (CNPG) | Kubernetes operator that creates, monitors and fails over PostgreSQL clusters | property management of the archive |
Cluster |
CNPG resource: instances, image, storage, parameters, initial database | building plan of the archive |
<=>, <->,
<#> |
cosine distance, Euclidean distance, negative inner product | ways of measuring “similar” |
| operator class | defines which distance an index is built for,
e.g. vector_cosine_ops |
signposts for one way of measuring |
| TOAST | storage for large values outside the table page (from about 2 KB) | side room for thick books |
maintenance_work_mem |
memory for maintenance work such as CREATE INDEX |
worktable |
hnsw.ef_search |
candidate list during HNSW search (default 40) | remembered aisles |
IVFFlat, lists, probes |
index made of clusters, number of clusters, clusters searched | topic boxes, number of boxes, boxes opened |
hnsw.iterative_scan |
keeps searching when a filter discards too many candidates (since pgvector 0.8) | archivist keeps going until enough are left |
EXPLAIN ANALYZE |
shows the query plan with real times | the archivist’s routing slip |
Remember: pgvector turns PostgreSQL into a vector database in the same building as the rest of the data. Whether that is enough is decided by measurements with your data – not by the list of features.
Drill 1: Setting up the archive – CloudNativePG
A PostgreSQL pod by hand would be started quickly. But operating
means: creating instances, renewing certificates, failing over during an
outage, planning backups. An operator takes care of that. CloudNativePG
is a CNCF project and stores everything that belongs to the cluster in
its own resource Cluster.
Step 1 – install the operator. The manifest creates
the namespace cnpg-system, the CustomResourceDefinitions,
the permissions and the controller.
# on vdb1
kubectl apply --server-side -f https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.2.yaml--server-side– the API server merges the fields; the CNPG CRDs are too large for the annotation that a client-sideapplywould write.-f <url>– the release manifest of version 1.30.2.
Expected (excerpt, 26 lines):
namespace/cnpg-system serverside-applied
customresourcedefinition.apiextensions.k8s.io/backups.postgresql.cnpg.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/clusterimagecatalogs.postgresql.cnpg.io serverside-applied
customresourcedefinition.apiextensions.k8s.io/clusters.postgresql.cnpg.io serverside-applied
…
deployment.apps/cnpg-controller-manager serverside-applied
mutatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-mutating-webhook-configuration serverside-applied
validatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-validating-webhook-configuration serverside-applied
Step 2 – wait for the controller.
# on vdb1
kubectl -n cnpg-system rollout status deployment/cnpg-controller-manager --timeout=180sExpected:
Waiting for deployment "cnpg-controller-manager" rollout to finish: 0 of 1 updated replicas are available...
deployment "cnpg-controller-manager" successfully rolled out
Step 3 – write the building plan.
# on vdb1
nano archiv.yamlapiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: archiv
namespace: archiv
spec:
instances: 1
imageName: ghcr.io/cloudnative-pg/postgresql:18-standard-trixie
storage:
size: 8Gi
storageClass: longhorn
resources:
requests:
cpu: "2"
memory: 6Gi
limits:
cpu: "6"
memory: 6Gi
postgresql:
parameters:
shared_buffers: 1GB
maintenance_work_mem: 512MB
max_parallel_maintenance_workers: "4"
effective_cache_size: 3GB
affinity:
nodeSelector:
kubernetes.io/hostname: vdb2
bootstrap:
initdb:
database: bibliothek
owner: bibliothekar
postInitApplicationSQL:
- CREATE EXTENSION vector| Setting | Value | Meaning |
|---|---|---|
instances |
1 |
one instance; today is about index and query, not failover (HA with CNPG: three instances, one line) |
imageName |
…:18-standard-trixie |
PostgreSQL 18 in CNPG’s “standard” image, which already contains pgvector |
storage |
8Gi, longhorn |
own Longhorn volume for data and WAL |
resources |
2–6 CPU, 6 Gi | same request and limit for memory: no surprises from the OOM killer |
shared_buffers |
1GB |
PostgreSQL’s own page cache |
maintenance_work_mem |
512MB |
worktable for CREATE INDEX – deliberately tight, see
Drill 5 |
max_parallel_maintenance_workers |
4 |
helpers during the index build |
effective_cache_size |
3GB |
estimate for the planner of how much is in the cache overall |
nodeSelector |
vdb2 |
the node with 8 vCPU and 16 GB; vdb3 and vdb4 have only 2 vCPU |
bootstrap.initdb |
bibliothek, bibliothekar |
initial database and its owner |
postInitApplicationSQL |
CREATE EXTENSION vector |
activates pgvector in the new database |
Step 4 – create the namespace and start the cluster.
# on vdb1
kubectl create namespace archiv# on vdb1
kubectl apply -f archiv.yamlExpected:
namespace/archiv created
cluster.postgresql.cnpg.io/archiv created
Step 5 – wait until the cluster is ready.
# on vdb1
kubectl -n archiv wait --for=condition=Ready cluster/archiv --timeout=600sExpected (for me after 1 min 21 s; the image was pulled for the first time):
cluster.postgresql.cnpg.io/archiv condition met
# on vdb1
kubectl -n archiv get pods,pvc,svc -o wideExpected (columns on the right shortened):
NAME READY STATUS RESTARTS AGE IP NODE
pod/archiv-1 1/1 Running 0 23s 10.42.1.66 vdb2
NAME STATUS VOLUME CAPACITY
persistentvolumeclaim/archiv-1 Bound pvc-c43490b8-e37f-4413-8c66-016675e56a11 8Gi
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S)
service/archiv-r ClusterIP 10.43.88.240 <none> 5432/TCP
service/archiv-ro ClusterIP 10.43.189.82 <none> 5432/TCP
service/archiv-rw ClusterIP 10.43.128.28 <none> 5432/TCP
What you see: CNPG creates three services:
-rw always points to the primary (writing),
-ro to the replicas (with one instance, to nobody),
-r to all instances. Note the IP of archiv-rw;
you need it for the Python scripts.
Step 6 – check the versions.
kubectl exec starts psql in the pod as the
superuser postgres via the local socket – no password is
needed for that.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\dx"-c postgres– the container with the database (CNPG also has init containers).psql bibliothek– connect to the databasebibliothek.-c "\dx"– list installed extensions.
Expected:
List of installed extensions
Name | Version | Default version | Schema | Description
---------+---------+-----------------+------------+------------------------------------------------------
plpgsql | 1.0 | 1.0 | pg_catalog | PL/pgSQL procedural language
vector | 0.8.7 | 0.8.7 | public | vector data type and ivfflat and hnsw access methods
(2 rows)
With SELECT version(); the pod reports
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+5).
Step 7 – get the application’s password. CNPG has
stored a random password for bibliothekar in the Secret
archiv-app. The Go template decodes it and writes it to a
file without a line break – so the trap from Day 11 does not occur
here.
# on vdb1
kubectl -n archiv get secret archiv-app -o go-template="{{.data.password | base64decode}}" > pg-passwort# on vdb1
chmod 600 pg-passwort# on vdb1
wc -c pg-passwortExpected:
64 pg-passwort
Remember: The operator is the property management: you describe the archive in the
Cluster, CNPG builds the instance, volume, services and credentials. You get the password from the Secret, never from the book.
Save your progress? Sign up for free
Drill 2: Shelving the books
The same data as in Qdrant: doku with text, section area
and 768 dimensions, glove with 100 dimensions. The application should
own the tables, not the superuser – otherwise bibliothekar
will not be allowed to write to them later.
Step 1 – create the tables.
# on vdb1
nano schema.sql-- Tabellen gehören der Anwendung, nicht dem Superuser
SET ROLE bibliothekar;
CREATE TABLE doku (
id bigint PRIMARY KEY,
bereich text NOT NULL,
pfad text NOT NULL,
titel text NOT NULL,
text text NOT NULL,
embedding vector(768) NOT NULL
);
CREATE TABLE glove (
id integer PRIMARY KEY,
embedding vector(100) NOT NULL
);SET ROLE bibliothekar– everything that follows runs with the application’s permissions; it becomes the owner.vector(768)– pgvector data type with a fixed dimension; a vector of a different length is rejected.
# on vdb1
kubectl -n archiv exec -i archiv-1 -c postgres -- psql bibliothek < schema.sql-i– standard input is passed on topsqlin the pod;< schema.sqlsupplies the file.
Expected:
SET
CREATE TABLE
CREATE TABLE
Step 2 – drivers into the workbench.
psycopg is the PostgreSQL driver for Python;
pgvector provides the conversion between numpy arrays and
the type vector.
# on vdb1
~/werkbank/bin/pip install --quiet "psycopg[binary]==3.3.*" pgvectorAfterwards ~/werkbank/bin/pip list reports
psycopg 3.3.9 and pgvector 0.5.1.
Step 3 – the load script. COPY is the
fastest way into a PostgreSQL table: one data stream instead of
individual INSERTs, here in binary format.
# on vdb1
nano laden.py"""Lädt doku (Tag 1) und glove-100 (Tag 8) per COPY in PostgreSQL."""
import json
import sys
import time
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
HOST, TABELLE = sys.argv[1], sys.argv[2] # z. B. 10.43.128.28 doku
passwort = open("pg-passwort").read()
with psycopg.connect(host=HOST, dbname="bibliothek", user="bibliothekar",
password=passwort, sslmode="require") as verbindung:
register_vector(verbindung)
beginn = time.time()
with verbindung.cursor() as cur:
if TABELLE == "doku":
eintraege = [json.loads(z) for z in open("../tag01/korpus.jsonl", encoding="utf-8")]
vektoren = np.load("../tag01/vektoren.npy")
with cur.copy("COPY doku (id, bereich, pfad, titel, text, embedding)"
" FROM STDIN WITH (FORMAT BINARY)") as copy:
copy.set_types(["int8", "text", "text", "text", "text", "vector"])
for e, v in zip(eintraege, vektoren):
copy.write_row((e["id"], e["bereich"], e["pfad"], e["titel"], e["text"], v))
anzahl = len(eintraege)
else:
vektoren = np.load("../tag08/glove-bestand.npy")
with cur.copy("COPY glove (id, embedding) FROM STDIN WITH (FORMAT BINARY)") as copy:
copy.set_types(["int4", "vector"])
for i, v in enumerate(vektoren):
copy.write_row((i, v))
anzahl = len(vektoren)
print(f"{anzahl} Zeilen in {time.time() - beginn:.1f} s nach {TABELLE} geladen")sslmode="require"– CNPG does not enforce TLS, but offers it with its own certificate; this way nothing goes over the network in plain text.register_vector– makes the typevectorknown to psycopg.set_types– column types for the binary format ofCOPY.- The glove IDs are the row numbers – just as in Qdrant (Day 8), so that the ground truth matches.
Step 4 – load doku. The IP is that of
archiv-rw.
# on vdb1
~/werkbank/bin/python laden.py 10.43.128.28 dokuExpected:
13220 Zeilen in 4.3 s nach doku geladen
Step 5 – load glove.
# on vdb1
~/werkbank/bin/python laden.py 10.43.128.28 gloveExpected:
1183514 Zeilen in 44.3 s nach glove geladen
What you see: 44 s for 1.18 million vectors – Qdrant needed 197 s on Day 8. That is not a fair win: PostgreSQL only writes rows; there is no vector index yet. Qdrant had already optimized segments and built the HNSW graph while loading. The bill for the index comes in Drill 5.
Step 6 – look at the sizes.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT relname, n_live_tup, pg_size_pretty(pg_total_relation_size(relid)) AS gesamt FROM pg_stat_user_tables ORDER BY relname;"n_live_tup– estimated number of live rows.pg_total_relation_size– table including TOAST and indexes.
Expected:
relname | n_live_tup | gesamt
---------+------------+--------
doku | 13220 | 65 MB
glove | 1183514 | 539 MB
(2 rows)
Remember:
COPYfills the branch quickly because nobody is putting up signposts yet. You only compare load times with the same index state.
Save your progress? Sign up for free
Drill 3: Walking every shelf – and then with signposts
Without an index, PostgreSQL computes the distance for every row and sorts – the exact search from Day 1. As the question you take the vector of an existing section (ID 1), so you do not need an embedding model.
Step 1 – exact search.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT id, bereich, round((embedding <=> (SELECT embedding FROM doku WHERE id = 1))::numeric, 4) AS abstand, left(text, 50) AS anfang FROM doku ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 1) LIMIT 5;"<=>– cosine distance (0 = same direction);dokualso uses cosine in Qdrant.(SELECT embedding FROM doku WHERE id = 1)– the query vector.ORDER BY … LIMIT 5– the five nearest neighbors.
Expected:
id | bereich | abstand | anfang
-------+-----------+---------+----------------------------------------------------
1 | concepts | 0.0000 | A Kubernetes cluster consists of a control plane p
88 | concepts | 0.0539 | Kubernetes runs your workload by placing container
10951 | setup | 0.0680 | In a production-quality Kubernetes cluster, the co
10952 | setup | 0.0720 | The simplest Kubernetes cluster has the entire con
13016 | tutorials | 0.0816 | A Pod always runs on a **Node**. A Node is a worke
(5 rows)
Step 2 – the routing slip.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM doku ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 1) LIMIT 10;"ANALYZE– actually run the query and measure times.COSTS OFF– omit the planner’s estimates; this makes the output shorter.
Expected:
QUERY PLAN
------------------------------------------------------------------------------------------------
Limit (actual time=273.569..273.575 rows=10.00 loops=1)
Buffers: shared hit=80893
InitPlan 1
-> Index Scan using doku_pkey on doku doku_1 (actual time=0.111..0.114 rows=1.00 loops=1)
Index Cond: (id = 1)
Index Searches: 1
Buffers: shared hit=6
-> Sort (actual time=273.566..273.568 rows=10.00 loops=1)
Sort Key: ((doku.embedding <=> (InitPlan 1).col1))
Sort Method: top-N heapsort Memory: 25kB
Buffers: shared hit=80893
-> Seq Scan on doku (actual time=0.481..264.259 rows=13220.00 loops=1)
Buffers: shared hit=80890
Planning:
Buffers: shared hit=88
Planning Time: 1.331 ms
Execution Time: 275.304 ms
(17 rows)
| Line | Value | Meaning |
|---|---|---|
Seq Scan on doku |
rows=13220 |
every row read – every shelf walked |
Buffers: shared hit |
80890 |
80,890 pages of 8 KB from the cache, a good 630 MB read |
Sort Method |
top-N heapsort |
only the best 10 are kept |
Execution Time |
275 ms |
for 13,220 rows |
What you see: 80,890 pages for a table of 65 MB – that is more than the size of the table. A vector with 768 dimensions is 3 KB, more than the roughly 2 KB from which PostgreSQL moves values out into the TOAST side room. Every distance fetches its vector from there, across several pages. With glove (100 dimensions, 400 bytes) this does not happen.
Step 3 – build the HNSW index. The same parameters
as in Qdrant (Day 4): m 16, ef_construction
100. The operator class must match the distance you search with.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\timing on" -c "SET ROLE bibliothekar;" -c "CREATE INDEX doku_hnsw ON doku USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 100);"| Setting | Value | Meaning |
|---|---|---|
\timing on |
– | psql shows the duration after every command |
SET ROLE |
bibliothekar |
like the table, the index belongs to the application |
USING hnsw |
– | pgvector’s HNSW index type |
vector_cosine_ops |
– | operator class: the index only speeds up <=> |
m, ef_construction |
16, 100 |
signposts per intersection, search width during the build |
Expected:
Timing is on.
SET
Time: 0.550 ms
CREATE INDEX
Time: 7246.011 ms (00:07.246)
pg_stat_user_indexes shows the size:
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS groesse FROM pg_stat_user_indexes WHERE relname = 'doku';"Expected:
indexrelname | groesse
--------------+---------
doku_pkey | 312 kB
doku_hnsw | 36 MB
(2 rows)
Step 4 – the same routing slip with an index. Repeat the command from Step 2.
Expected (excerpt – the lines after
InitPlan 1):
-> Index Scan using doku_hnsw on doku (actual time=10.549..10.981 rows=10.00 loops=1)
Order By: (embedding <=> (InitPlan 1).col1)
Index Searches: 1
Buffers: shared hit=823
Planning:
Buffers: shared hit=114 read=1 dirtied=1
Planning Time: 2.600 ms
Execution Time: 11.162 ms
What you see:
Index Scan using doku_hnsw instead of
Seq Scan, 823 instead of 80,890 pages, 11 ms instead of 275
ms. The index contains the vectors themselves; the side room stays
closed.
Remember: An HNSW index in pgvector belongs to exactly one way of measuring.
vector_cosine_opsspeeds up<=>– and only that.
Save your progress? Sign up for free
Drill 4: Only the “concepts” department – the filter trap
In Qdrant (Day 4), the filter is applied during the
graph search. pgvector works differently: the HNSW index returns the
hnsw.ef_search best candidates, and
afterwards PostgreSQL checks the WHERE
condition. Whatever is left is the result.
Step 1 – look at the defaults. pgvector’s settings
only exist once the library has been loaded in the session – so
LOAD first.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "LOAD 'vector';" -c "SHOW hnsw.ef_search;" -c "SHOW hnsw.max_scan_tuples;" -c "SHOW ivfflat.probes;"Expected:
LOAD
hnsw.ef_search
----------------
40
(1 row)
hnsw.max_scan_tuples
----------------------
20000
(1 row)
ivfflat.probes
----------------
1
(1 row)
Without LOAD, SHOW hnsw.ef_search answers
with unrecognized configuration parameter.
Step 2 – a question from the reference, filtered to
“concepts”. Section 3500 comes from the area
reference (it describes
EncryptionConfiguration). Its nearest neighbors are almost
all reference as well. But what you are looking for is ten sections from
concepts.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT id, round((embedding <=> (SELECT embedding FROM doku WHERE id = 3500))::numeric, 4) AS abstand FROM doku WHERE bereich = 'concepts' ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 3500) LIMIT 10;"Expected:
id | abstand
------+---------
796 | 0.2062
1214 | 0.2121
1362 | 0.2133
(3 rows)
What you see: LIMIT 10, but three rows
– no error, no warning. The area concepts has 2623
sections; there is no shortage of hits.
Step 3 – the routing slip.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM doku WHERE bereich = 'concepts' ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 3500) LIMIT 10;"Expected (excerpt – the lines after
InitPlan 1):
-> Index Scan using doku_hnsw on doku (actual time=4.338..4.559 rows=3.00 loops=1)
Order By: (embedding <=> (InitPlan 1).col1)
Filter: (bereich = 'concepts'::text)
Rows Removed by Filter: 37
Index Searches: 1
Buffers: shared hit=582
Planning:
Buffers: shared hit=126
Planning Time: 3.209 ms
Execution Time: 4.761 ms
What you see: 3 kept + 37 discarded = 40 – exactly
hnsw.ef_search. The index delivered its 40 candidates and
was done. In the picture: the archivist shows the 40 best books, sorts
them out afterwards and brings whatever is left.
Step 4 – let it keep searching. Since pgvector 0.8
there is hnsw.iterative_scan. With
relaxed_order, the index fetches more candidates until
enough rows pass the filter (or hnsw.max_scan_tuples is
reached).
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SET hnsw.iterative_scan = relaxed_order;" -c "SELECT id, round((embedding <=> (SELECT embedding FROM doku WHERE id = 3500))::numeric, 4) AS abstand FROM doku WHERE bereich = 'concepts' ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 3500) LIMIT 10;"SETapplies only to this session. For an application you set it per connection or withALTER ROLE … SET.relaxed_order– the order may differ minimally from the exact one;strict_ordersorts strictly.
Expected:
SET
id | abstand
------+---------
796 | 0.2062
1214 | 0.2121
1362 | 0.2133
1176 | 0.2362
1321 | 0.2384
210 | 0.2404
1374 | 0.2420
619 | 0.2438
1209 | 0.2459
1329 | 0.2477
(10 rows)
With strict_order instead of relaxed_order,
I get the same ten rows in the same order.
Step 5 – check against the ground truth.
enable_indexscan = off forbids the planner to use the
index; it walks all the shelves.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SET enable_indexscan = off;" -c "SELECT id, round((embedding <=> (SELECT embedding FROM doku WHERE id = 3500))::numeric, 4) AS abstand FROM doku WHERE bereich = 'concepts' ORDER BY embedding <=> (SELECT embedding FROM doku WHERE id = 3500) LIMIT 10;"Expected: the same ten IDs with the same distances as in Step 4 (796 to 1329).
What you see: Here the iterative search hits the
exact answer. One more finding from my run: for the rare area
setup (235 of 13,220 rows), the planner did not choose the
HNSW index at all, but a Seq Scan with a filter
(Rows Removed by Filter: 12985) – exact and in 14 ms.
Whether the index is used is decided by the planner based on its
estimate of how many rows the filter leaves.
Remember: In pgvector, PostgreSQL filters after the index search. With filters, always switch on
hnsw.iterative_scanand check whetherLIMITis really reached.
Save your progress? Sign up for free
Drill 5: The worktable is too small
Now the million: glove with 1,183,514 vectors, again m
16 and ef_construction 100. pgvector builds the graph in
memory; the table is maintenance_work_mem – 512 MB in the
building plan.
Step 1 – build with 512 MB. Note the time beforehand.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\timing on" -c "SET ROLE bibliothekar;" -c "CREATE INDEX glove_hnsw ON glove USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 100);"Expected:
Timing is on.
SET
Time: 0.931 ms
NOTICE: hnsw graph no longer fits into maintenance_work_mem after 492286 tuples
DETAIL: Building will take significantly more time.
HINT: Increase maintenance_work_mem to speed up builds.
CREATE INDEX
Time: 1106173.083 ms (18:26.173)
What you see: After 492,286 of 1,183,514 vectors the table was full. From then on, pgvector continues building directly on the index pages – considerably slower. 18 minutes 26 seconds for the whole index.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS groesse FROM pg_stat_user_indexes WHERE relname = 'glove';"Expected:
indexrelname | groesse
--------------+---------
glove_pkey | 25 MB
glove_hnsw | 841 MB
(2 rows)
The finished index is 841 MB – the graph could never have fit on a table of 512 MB.
Step 2 – a bigger table, only for this session. Drop
the index and rebuild it with 2 GB. The pod has 6 Gi, of which 1 GB is
shared_buffers – 2 GB for the build fit in.
log_min_duration_statement = 0 writes the duration of every
command to the server log; you will need that in a moment.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SET ROLE bibliothekar;" -c "DROP INDEX glove_hnsw;"Expected:
SET
DROP INDEX
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\timing on" -c "SET log_min_duration_statement = 0;" -c "SET ROLE bibliothekar;" -c "SET maintenance_work_mem = '2GB';" -c "CREATE INDEX glove_hnsw ON glove USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 100);"| Setting | Value | Meaning |
|---|---|---|
log_min_duration_statement |
0 |
log every command with its duration (superuser only, hence before
SET ROLE) |
maintenance_work_mem |
'2GB' |
enlarge the worktable for this session only |
What happened for me: The command did not return –
no output, not even after half an hour. A second session showed: no
CREATE INDEX active any more, \di lists
glove_hnsw. The index was finished; only the response got
lost on its way through kubectl exec. That is why the
duration is in the server log:
# on vdb1
kubectl -n archiv logs archiv-1 -c postgres | grep -o "duration: [0-9.]* ms statement: CREATE INDEX[^,]*"- CNPG writes the PostgreSQL log as JSON to the pod’s standard output.
grep -o– output only the matching part of the long JSON line;[^,]*ends at the next comma.
Expected:
duration: 493077.430 ms statement: CREATE INDEX glove_hnsw ON glove USING hnsw (embedding vector_cosine_ops) WITH (m = 16
What you see: 8 minutes 13 seconds instead of 18 minutes 26 seconds – the same index, just a bigger table. For comparison: Qdrant had glove fully indexed a little over four minutes after loading (Day 8), spread across three nodes.
Remember: To build an HNSW index, pgvector needs as much
maintenance_work_memas the graph grows – roughly the final index size. You start long index builds with logging, not by trusting an open terminal session.
Save your progress? Sign up for free
Drill 6: How well does pgvector find? recall@10
The same question as on Day 8: how many of the ten true neighbors
does the search return? The ground truth comes from glove-100 itself
(glove-wahrheit.npy, 1000 queries).
Step 1 – the measurement script.
# on vdb1
nano recall.py"""Misst recall@10 von pgvector auf glove-100 gegen die mitgelieferte Wahrheit (1000 Fragen)."""
import sys
import time
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
HOST, EINSTELLUNG, WERT = sys.argv[1], sys.argv[2], int(sys.argv[3]) # z. B. hnsw.ef_search 40
fragen = np.load("../tag08/glove-fragen.npy")
wahrheit = np.load("../tag08/glove-wahrheit.npy")
passwort = open("pg-passwort").read()
with psycopg.connect(host=HOST, dbname="bibliothek", user="bibliothekar",
password=passwort, sslmode="require") as verbindung:
register_vector(verbindung)
verbindung.execute(f"SET {EINSTELLUNG} = {WERT}")
treffer, beginn = 0, time.perf_counter()
for vektor, beste10 in zip(fragen, wahrheit):
zeilen = verbindung.execute(
"SELECT id FROM glove ORDER BY embedding <=> %s LIMIT 10", (vektor,)).fetchall()
treffer += len({z[0] for z in zeilen} & set(beste10.tolist()))
dauer = time.perf_counter() - beginn
print(f"{EINSTELLUNG} {WERT} · recall@10 {treffer / (len(fragen) * 10):.3f}"
f" · {len(fragen)} Fragen in {dauer:.1f} s")| Setting | Value | Meaning |
|---|---|---|
sys.argv[1] |
IP of archiv-rw |
where to connect |
sys.argv[2] |
hnsw.ef_search or ivfflat.probes |
which setting |
sys.argv[3] |
number | its value for this session |
| Output | recall@10, duration | duration = 1000 queries one after another over one connection |
Step 2 – measure with ef_search 10.
# on vdb1
~/werkbank/bin/python recall.py 10.43.128.28 hnsw.ef_search 10Expected:
hnsw.ef_search 10 · recall@10 0.500 · 1000 Fragen in 6.4 s
Repeat the command with 40, 100 and
256 instead of 10.
Expected (all four runs, m 16,
ef_construction 100, raw output in the log):
hnsw.ef_search |
recall@10 pgvector | 1000 queries one after another | Qdrant hnsw_ef (Day 8) |
|---|---|---|---|
| 10 | 0.500 | 6.4 s | 0.595 |
| 40 (default) | 0.716 | 7.1 s | – (32: 0.777) |
| 100 | 0.825 | 10.4 s | – (128: 0.899) |
| 256 | 0.891 | 19.0 s | 0.942 |
What you see: With the same m and the
same build width, pgvector finds fewer true neighbors than Qdrant at the
same search width. The default of 40 only delivers 0.716 – anyone who
uses pgvector with default values loses almost every third hit. Part of
the gap fits a difference in setup: in Qdrant, glove is spread across
three shards; each shard searches with hnsw_ef and returns
its best ten, which are then merged – so more candidates are looked at
there. I did not prove this share here; Day 14 measures it on Milvus:
with five segments (five graphs) recall is 0.585 at ef 10,
with a single one 0.473 – close to pgvector (0.500).
Remember:
hnsw.ef_searchis pgvector’s most important knob. The default of 40 is too small for a million vectors – measure recall with your data and set the value deliberately.
Save your progress? Sign up for free
Drill 7: Under load – 16 readers against both systems
Same setup as on Day 8: 16 processes, each with its own connection, 8000 queries from glove.
Step 1 – the load generator for PostgreSQL.
# on vdb1
nano last-pg.py"""Lastgenerator für pgvector: jeder Prozess ist ein Leser mit eigener Verbindung."""
import sys
import time
from multiprocessing import Pool
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
HOST, FRAGEN = sys.argv[1], sys.argv[2]
PARALLEL, ANZAHL, EF = int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
def leser(nummer):
"""Ein Prozess: schickt seine Anfragen nacheinander und gibt die Zeiten zurück."""
fragen = np.load(FRAGEN)
passwort = open("pg-passwort").read()
zeiten, fehler = [], 0
with psycopg.connect(host=HOST, dbname="bibliothek", user="bibliothekar",
password=passwort, sslmode="require") as verbindung:
register_vector(verbindung)
verbindung.execute(f"SET hnsw.ef_search = {EF}")
for i in range(nummer, ANZAHL, PARALLEL):
beginn = time.perf_counter()
try:
verbindung.execute("SELECT id FROM glove ORDER BY embedding <=> %s LIMIT 10",
(fragen[i % len(fragen)],)).fetchall()
except psycopg.Error:
fehler += 1
zeiten.append((time.perf_counter() - beginn) * 1000)
return zeiten, fehler
if __name__ == "__main__":
start = time.perf_counter()
with Pool(PARALLEL) as pool:
ergebnisse = pool.map(leser, range(PARALLEL))
dauer = time.perf_counter() - start
zeiten = np.concatenate([z for z, f in ergebnisse])
fehler = sum(f for z, f in ergebnisse)
p50, p95, p99 = np.percentile(zeiten, [50, 95, 99])
print(f"parallel {PARALLEL} (Prozesse) · {ANZAHL} Anfragen in {dauer:.1f} s"
f" · {ANZAHL / dauer:.0f} Anfragen/s · p50 {p50:.1f} ms · p95 {p95:.1f} ms"
f" · p99 {p99:.1f} ms · max {zeiten.max():.1f} ms · Fehler {fehler}")Built like last-prozesse.py from Day 8; what is new is
the connection via psycopg and SET hnsw.ef_search per
connection (sys.argv[5]).
Step 2 – warm up, then measure. A short run with 2000 queries pulls the index into the cache:
# on vdb1
~/werkbank/bin/python last-pg.py 10.43.128.28 ../tag08/glove-fragen.npy 16 2000 40Expected:
parallel 16 (Prozesse) · 2000 Anfragen in 2.6 s · 777 Anfragen/s · p50 13.0 ms · p95 37.5 ms · p99 61.1 ms · max 103.6 ms · Fehler 0
# on vdb1
~/werkbank/bin/python last-pg.py 10.43.128.28 ../tag08/glove-fragen.npy 16 8000 40Expected:
parallel 16 (Prozesse) · 8000 Anfragen in 7.0 s · 1150 Anfragen/s · p50 10.2 ms · p95 29.3 ms · p99 51.7 ms · max 124.4 ms · Fehler 0
Repeat the run with 256 as the last value – that is the
search width with recall 0.891.
Step 3 – Qdrant at the same hour. The load generator
from Day 11 already speaks TLS and keys; it reads
../tag10/lese-key and ../tag10/ca.crt, which
also works from ~/labor/tag13.
# on vdb1
~/werkbank/bin/python ../tag11/last-prozesse.py https://10.43.151.237:6333 glove ../tag08/glove-fragen.npy 16 8000 128Expected (the version check warning from Day 10 omitted):
parallel 16 (Prozesse) · 8000 Anfragen in 20.9 s · 384 Anfragen/s · p50 34.7 ms · p95 68.2 ms · p99 86.4 ms · max 153.6 ms · Fehler 0
Expected – all runs with 8000 queries, 16 readers, workbench on vdb1, raw output in the log:
| System | Search width | recall@10 | Run | Requests/s | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|
| pgvector | ef_search 40 |
0.716 | 1 | 1150 | 10.2 ms | 29.3 ms | 51.7 ms |
| pgvector | ef_search 256 |
0.891 | 1 | 335 | 42.9 ms | 80.9 ms | 105.3 ms |
| pgvector | ef_search 256 |
0.891 | 2 | 343 | 42.2 ms | 78.8 ms | 100.2 ms |
| Qdrant | default | 0.882 (Day 8) | 1 | 400 | 31.5 ms | 63.6 ms | 86.5 ms |
| Qdrant | hnsw_ef 128 |
0.901 (Day 8, int8 + rescore) | 1 | 384 | 34.7 ms | 68.2 ms | 86.4 ms |
| Qdrant | hnsw_ef 128 |
0.901 | 2 | 346 | 35.3 ms | 73.0 ms | 98.3 ms |
The conditions without which the table is worthless:
| pgvector | Qdrant | |
|---|---|---|
| Data | glove-100, 1,183,514 × 100, cosine | the same |
| Index | HNSW m 16, ef_construction 100 |
HNSW m 16, ef_construct 100, int8
quantization with rescore |
| Distribution | 1 instance on vdb2, limit 6 CPU, 6 Gi | 3 shards without a second copy on vdb2 (8 vCPU), vdb3 and vdb4 (2 vCPU each), limit 2 Gi per pod |
| Connection | TLS (sslmode=require), password |
TLS, API key |
What you see: At a comparable recall of around 0.89, both are in the same order of magnitude – Qdrant slightly ahead here at p50; the repetitions vary by around 10 %, as on Day 8. With the default of 40, pgvector is three times as fast – but only because it leaves out almost every third hit. A comparison in which recall is not in the same row is no comparison.
Remember: You only compare throughput at the same recall, with the same data and on named hardware. Fast and inaccurate is not an advantage.
Save your progress? Sign up for free
Drill 8: Topic boxes – IVFFlat
During the build, IVFFlat divides the vectors into lists
groups, each around a centroid. The search only looks in the
ivfflat.probes groups whose centroid is closest to the
question. The pgvector documentation recommends lists =
square root of the row count for more than a million rows: √1,183,514 ≈
1088. The boxes are formed from the data that is in the table at build
time – that is why you build IVFFlat only after loading.
Step 1 – remove HNSW. Otherwise the planner decides which of the two indexes is used, and you may end up measuring the wrong one.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SET ROLE bibliothekar;" -c "DROP INDEX glove_hnsw;"Expected:
SET
DROP INDEX
Step 2 – build IVFFlat.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\timing on" -c "SET log_min_duration_statement = 0;" -c "SET ROLE bibliothekar;" -c "SET maintenance_work_mem = '2GB';" -c "CREATE INDEX glove_ivf ON glove USING ivfflat (embedding vector_cosine_ops) WITH (lists = 1088);"USING ivfflat– index type IVFFlat.lists = 1088– number of boxes.
Expected (excerpt – the last two lines):
CREATE INDEX
Time: 103971.479 ms (01:43.971)
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS groesse FROM pg_stat_user_indexes WHERE relname = 'glove';"Expected:
indexrelname | groesse
--------------+---------
glove_pkey | 25 MB
glove_ivf | 491 MB
(2 rows)
Step 3 – recall with one box opened.
# on vdb1
~/werkbank/bin/python recall.py 10.43.128.28 ivfflat.probes 1Expected:
ivfflat.probes 1 · recall@10 0.389 · 1000 Fragen in 5.5 s
Repeat the command with 10 and 32 instead
of 1.
Expected (raw output in the log):
| Index | Build time | Size | Setting | recall@10 | 1000 queries one after another |
|---|---|---|---|---|---|
IVFFlat, lists 1088 |
1:44 min | 491 MB | probes 1 (default) |
0.389 | 5.5 s |
probes 10 |
0.760 | 21.0 s | |||
probes 32 |
0.879 | 58.4 s | |||
HNSW, m 16 |
8:13 min (2 GB) | 841 MB | ef_search 256 |
0.891 | 19.0 s |
What you see: IVFFlat builds four times as fast and
is smaller. When searching, this is reversed: for recall 0.88, 32 boxes
have to be opened, and each query takes 58 ms on average instead of 19
ms with HNSW. And the default probes 1 does not even find
four out of ten neighbors.
Remember: IVFFlat saves build time and space, HNSW saves search time. With IVFFlat,
listsandprobesbelong together – with the defaultprobes1, the index is hardly usable for a million vectors.
Save your progress? Sign up for free
Diagnosis task: The index is not used
A colleague reports: “Since the rework, the search in
doku takes a quarter of a second; before, it was 11 ms. The
index is there, after all.” Her query:
SELECT id FROM doku ORDER BY embedding <-> (SELECT embedding FROM doku WHERE id = 1) LIMIT 10;Find the cause before you read on. Tools:
EXPLAIN (ANALYZE, COSTS OFF) and \d doku.
Solution path.
Step 1 – read the routing slip.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM doku ORDER BY embedding <-> (SELECT embedding FROM doku WHERE id = 1) LIMIT 10;"Expected (excerpt):
-> Sort (actual time=274.031..274.033 rows=10.00 loops=1)
Sort Key: ((doku.embedding <-> (InitPlan 1).col1))
Sort Method: top-N heapsort Memory: 25kB
Buffers: shared hit=80893
-> Seq Scan on doku (actual time=0.409..264.295 rows=13220.00 loops=1)
Buffers: shared hit=80890
Planning Time: 3.066 ms
Execution Time: 274.200 ms
Step 2 – look at the index.
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\d doku"Expected (excerpt – the last three lines):
Indexes:
"doku_pkey" PRIMARY KEY, btree (id)
"doku_hnsw" hnsw (embedding vector_cosine_ops) WITH (m='16', ef_construction='100')
Cause: The query sorts by <->,
the Euclidean distance. The index is built with
vector_cosine_ops and only speeds up
<=>. PostgreSQL does not report this as an error – it
simply walks all the shelves. The answer is even correct, just slow.
Solution: Use <=> in the query if
the data is to be compared with cosine (as in Qdrant). If the Euclidean
distance is really needed, build a second index with
vector_l2_ops – that costs build time and space. The proof
is always EXPLAIN:
Index Scan using doku_hnsw.
Checkpoint
# on vdb1
kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "SELECT (SELECT count(*) FROM doku) AS doku, (SELECT count(*) FROM glove) AS glove;" -c "\di"Expected:
doku | glove
-------+---------
13220 | 1183514
(1 row)
List of indexes
Schema | Name | Type | Owner | Table
--------+------------+-------+--------------+-------
public | doku_hnsw | index | bibliothekar | doku
public | doku_pkey | index | bibliothekar | doku
public | glove_ivf | index | bibliothekar | glove
public | glove_pkey | index | bibliothekar | glove
(4 rows)
# on vdb1
kubectl -n archiv get cluster archivExpected:
NAME AGE INSTANCES READY STATUS PRIMARY
archiv 3h3m 1 1 Cluster in healthy state archiv-1
Day 14 needs vdb2 for Milvus. That is why you take the branch down again. Together with the cluster, CNPG also deletes its volume.
# on vdb1
kubectl delete -f archiv.yaml# on vdb1
kubectl delete namespace archiv# on vdb1
kubectl delete -f https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.2.yamlExpected (excerpt – the first two and the last line):
cluster.postgresql.cnpg.io "archiv" deleted from archiv namespace
namespace "archiv" deleted
validatingwebhookconfiguration.admissionregistration.k8s.io "cnpg-validating-webhook-configuration" deleted
# on vdb1
kubectl -n longhorn-system get volumes.longhorn.io -o custom-columns=NAME:.metadata.name,STATE:.status.state,ROBUST:.status.robustnessExpected: the four volumes from before again (Ollama
and three Qdrant pods), all attached and
healthy – the volume of archiv-1 is gone.
NAME STATE ROBUST
pvc-1be489ab-3891-4c08-b4b4-b3d91dac36d9 attached healthy
pvc-37095780-0d56-4966-a719-884783ff8977 attached healthy
pvc-c6c96e89-073d-4b27-baae-13ed36b72ef8 attached healthy
pvc-e760fa38-f3f3-446d-9edc-6453b63e6b61 attached healthy
Test yourself
- A filtered search with
LIMIT 10returns three rows, without an error. What happened, and what do you set? - Why does the exact search in
dokuread 80,890 pages even though the table is only 65 MB? - Building an HNSW index reports
hnsw graph no longer fits into maintenance_work_mem. What does that mean for the build time, and how do you determine the right value? - Someone reports “pgvector manages 1150 requests per second, Qdrant only 400”. What question do you ask first?
EXPLAINshowsSeq Scan on dokueven though an HNSW index exists. Name two possible reasons.- When would you choose IVFFlat instead of HNSW?
Answers:
- pgvector filters after the index search: the index delivered
hnsw.ef_search(40) candidates, 37 failed the filter. Remedy:SET hnsw.iterative_scan = relaxed_order(orstrict_order); then the index keeps searching untilLIMITis reached; check withEXPLAIN ANALYZEandRows Removed by Filter. - A vector with 768 dimensions is 3 KB and lives in the TOAST side room. For every row, PostgreSQL fetches it from there, across several pages. With an index, the search reads only 823 pages.
- From this point on, pgvector continues building on the index pages instead of in memory – for glove 18:26 min instead of 8:13 min. The guideline is the final size of the index (here 841 MB), set only in the session of the build.
- At what recall? 1150 requests/s were achieved with
ef_search40 and recall 0.716. At recall 0.89, both were at 335 to 400 requests/s. Also: same data, same hardware, same number of readers? - The distance operator does not match the operator class
(
<->versusvector_cosine_ops), or the planner considers a Seq Scan cheaper, for example because a filter leaves only a few rows (as withsetup). - When build time and memory are scarce and the data hardly changes: IVFFlat built in 1:44 min instead of 8:13 min and is 491 instead of 841 MB. For fast search at high recall, HNSW is better (19 instead of 58 s for 1000 queries at recall ≈ 0.88).
Interview note
“Why not just pgvector, since we have PostgreSQL anyway?” –
Often that is the right answer: one system less, transactions across
vectors and business data, existing backups and permissions. But I would
measure it. In my lab with glove-100 (1.18 million vectors), pgvector
and Qdrant were in the same order of magnitude at the same recall of
around 0.89, roughly 340 to 400 requests per second with 16 readers. The
differences lie in operations: the HNSW build needs as much
maintenance_work_mem as the index grows, the default
ef_search 40 costs almost a third of the hits, and filters
only take effect after the index search – without
iterative_scan too few rows come back. Distributing across
several nodes is something you have to solve yourself in PostgreSQL;
Qdrant comes with shards and replicas.
Enterprise note
In production, the CNPG cluster runs with three instances
(instances: 3), synchronous replication for the data that
must not be lost, and backups via plugin to S3 – the same idea as the
off-site store from Day 12. Read-only vector searches can be distributed
across the replicas via the -ro service; indexes are
replicated there too, so they cost space on every instance and WAL
during the build.
You build large indexes with CREATE INDEX CONCURRENTLY
so that writes continue, and with a large
maintenance_work_mem for that session only – on nodes whose
memory limit can carry it. hnsw.ef_search and
hnsw.iterative_scan are set per role
(ALTER ROLE … SET) so that every application gets the same
values. For storage there is halfvec (16 bits) and binary
quantization – the counterpart to the paperback edition from Day 8, with
the same measurement obligations. And anyone who needs more than one
machine for the vectors ends up with partitioning or extensions such as
Citus – or with a dedicated vector database.
Summary
- CloudNativePG 1.30.2 with PostgreSQL 18.7 and pgvector 0.8.7 (image
18-standard-trixie), one instance on vdb2, 6 Gi, 8 Gi Longhorn; password from the Secretarchiv-app. COPYin binary format: doku in 4.3 s, glove in 44.3 s – without a vector index. Tables 65 MB and 539 MB.- 768-dimensional vectors live in TOAST: exact search 275 ms and 80,890 pages; with HNSW (7 s build, 36 MB) 11 ms and 823 pages.
- Filters take effect after the index search: 3 instead of 10 hits (37
discarded =
ef_search40);hnsw.iterative_scanreturns the right ten. - glove HNSW (
m16,ef_construction100): 841 MB; with 512 MBmaintenance_work_mem18:26 min including the notice, with 2 GB 8:13 min. The response fromkubectl execdid not come back – duration from the log. - recall@10: 0.500 / 0.716 / 0.825 / 0.891 at
ef_search10 / 40 / 100 / 256 – below Qdrant at the same search width (Day 8). - 16 readers: pgvector 1150 requests/s at recall 0.716, 335–343 at 0.891; Qdrant 346–400 at 0.88–0.90.
- IVFFlat (
lists1088): 1:44 min, 491 MB, recall 0.389 / 0.760 / 0.879 atprobes1 / 10 / 32. - Wrong operator (
<->versusvector_cosine_ops): Seq Scan without an error message. - Branch taken down again: cluster, namespace and operator deleted, four Longhorn volumes healthy.
Commands at a glance
| Command | Purpose |
|---|---|
kubectl apply --server-side -f <cnpg-manifest> |
install CloudNativePG |
kubectl -n <ns> wait --for=condition=Ready cluster/<name> |
wait for a PostgreSQL cluster |
kubectl -n <ns> exec <pod> -c postgres -- psql <db> -c "<sql>" |
SQL as superuser in the pod |
kubectl -n <ns> get secret <cluster>-app -o go-template="{{.data.password \| base64decode}}" |
the application’s password |
CREATE EXTENSION vector |
activate pgvector in a database |
COPY … FROM STDIN WITH (FORMAT BINARY) |
load quickly |
CREATE INDEX … USING hnsw (embedding vector_cosine_ops) WITH (m = …, ef_construction = …) |
HNSW index for cosine |
CREATE INDEX … USING ivfflat (embedding vector_cosine_ops) WITH (lists = …) |
IVFFlat index |
SET maintenance_work_mem = '2GB' |
memory for the index build in this session |
SET hnsw.ef_search = … /
SET ivfflat.probes = … |
search width |
SET hnsw.iterative_scan = relaxed_order |
keep searching with filters |
LOAD 'vector'; SHOW hnsw.ef_search; |
show pgvector’s settings |
EXPLAIN (ANALYZE, COSTS OFF) <query> |
query plan with real times |
\d <table>, \di, \dx,
\timing on |
table, indexes, extensions, timing in psql |
pg_stat_user_tables, pg_stat_user_indexes,
pg_relation_size() |
rows and sizes |
kubectl -n <ns> logs <pod> -c postgres |
PostgreSQL log (JSON) |