Skip to content
RAG infrastructure on Kubernetes · Chapter 6 of 20 Day 5: pgvector in Comparison – the Same Cabinet in PostgreSQL

Day 5: pgvector in Comparison – the Same Cabinet in PostgreSQL

Goal: Run PostgreSQL with CloudNativePG, switch on pgvector, store the same four cards and run the same searches as in Qdrant – hits, filters and index compared directly · Duration: approx. 75 min · Prerequisite: Day 4

State before this chapter

# on rag1
kubectl -n rag get statefulset qdrant

Expected: READY 1/1.

# on rag1
ls ~/kurs/04/punkte.json ~/kurs/01/frage1-embed.json ~/kurs/01/frage4-embed.json

Expected: the three files from Day 1 and Day 4.

Introduction

Many teams already have a database they have been running for years: PostgreSQL. With the extension pgvector, it can store vectors and search by similarity. Whether you need a second database like Qdrant for that is one of the first architecture questions of every RAG project.

Today you answer it not with opinions but with the same test: the same cards, the same questions, the same filter. You run PostgreSQL the way it is done on Kubernetes today – with the operator CloudNativePG, which turns a short manifest into a complete database cluster.

Today you learn:

  • to install the CloudNativePG operator with Helm,
  • to create a PostgreSQL cluster with a manifest,
  • to check whether the image includes pgvector, and to switch on the extension,
  • to store vectors in a table and search with <=>,
  • to create an HNSW index and see in the query plan when PostgreSQL uses it.

Background

The picture for today: a second cabinet in the existing archive

Qdrant is a special cabinet, built only for index cards with a floor plan. pgvector is an insert for the big archive cabinet that the house has anyway: PostgreSQL. The cards lie there in a drawer (table) next to everything else the company archives. Whoever already maintains the archive cabinet – backups, permissions, monitoring – gets the cards without a new cabinet. The caretaker who sets up, moves and repairs the archive cabinet is CloudNativePG.

The terms

Term Meaning in the picture
CloudNativePG operator: manages PostgreSQL clusters on Kubernetes caretaker of the archive
Cluster CloudNativePG’s own resource: instances, storage, bootstrap work order for the cabinet
pgvector PostgreSQL extension with the data type vector and indexes insert for index cards
vector(1024) column type for a vector with 1024 numbers compartment of the right size
<=> cosine distance (1 − similarity) how far apart two places are
HNSW index as in Qdrant: signposts for fast search floor plan
Query plan (EXPLAIN) how PostgreSQL executes a query the route the archivist chooses

Remember: pgvector computes distance, not similarity: <=> is 0 for identical vectors. The similarity from Day 1 is 1 - (a <=> b).

Drill 1: The caretaker – CloudNativePG

Where you are: on rag1.

What you have afterwards: the CloudNativePG operator in the namespace cnpg-system.

Step 1 – today’s folder.

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

Step 2 – the chart.

# on rag1
helm repo add cnpg https://cloudnative-pg.github.io/charts
# on rag1
helm repo update
# on rag1
helm search repo cnpg/cloudnative-pg --versions

Expected (excerpt, the first lines):

NAME                CHART VERSION   APP VERSION DESCRIPTION
cnpg/cloudnative-pg 0.29.2          1.30.2      CloudNativePG Operator Helm Chart
cnpg/cloudnative-pg 0.29.1          1.30.1      CloudNativePG Operator Helm Chart

Chart 0.29.2 brings operator 1.30.2.

Step 3 – install.

# on rag1
helm install cnpg cnpg/cloudnative-pg --namespace cnpg-system --create-namespace --version 0.29.2

Expected (excerpt):

NAME: cnpg
NAMESPACE: cnpg-system
STATUS: deployed
REVISION: 1
# on rag1
kubectl -n cnpg-system rollout status deploy/cnpg-cloudnative-pg --timeout=300s

Expected:

deployment "cnpg-cloudnative-pg" successfully rolled out

Step 4 – what the operator brings.

# on rag1
kubectl get crd clusters.postgresql.cnpg.io

crd are the custom resource types that the operator registers in Kubernetes. From now on, Kubernetes understands kind: Cluster from the group postgresql.cnpg.io.

Remember: An operator extends Kubernetes with new resources. You describe what you want (a cluster); the operator builds and maintains the pods, volumes and services for it.

Save your progress? Sign up for free

Drill 2: The archive cabinet – a PostgreSQL cluster

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

What you have afterwards: PostgreSQL 18 with one instance and the database rag.

Step 1 – the manifest.

# on rag1
nano pg.yaml
~/kurs/05/pg.yaml new file
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: pg
  namespace: rag
spec:
  instances: 1
  imageName: ghcr.io/cloudnative-pg/postgresql:18-standard-trixie
  storage:
    size: 2Gi
    storageClass: local-path
  bootstrap:
    initdb:
      database: rag
      owner: rag
  resources:
    requests:
      cpu: 250m
      memory: 512Mi
    limits:
      memory: 1Gi
Setting Meaning
instances: 1 one instance; several would give a primary and replicas
imageName: …:18-standard-trixie PostgreSQL 18 in the “standard” variant with additional extensions, on Debian trixie
storage.size, storageClass its own 2 GiB volume from local-path
bootstrap.initdb on first start, create the database rag owned by rag
resources as with Qdrant: little guaranteed, memory limited, CPU not

Step 2 – create and wait.

# on rag1
kubectl apply -f pg.yaml

Expected:

cluster.postgresql.cnpg.io/pg created
# on rag1
kubectl -n rag wait --for=condition=Ready cluster/pg --timeout=600s

Expected (in the lab after 70 seconds):

cluster.postgresql.cnpg.io/pg condition met

Step 3 – what has been created.

# on rag1
kubectl -n rag get cluster pg

Expected:

NAME   AGE   INSTANCES   READY   STATUS                     PRIMARY
pg     69s   1           1       Cluster in healthy state   pg-1
# on rag1
kubectl -n rag get svc

Expected (excerpt, the lines with pg):

pg-r              ClusterIP   10.43.238.69    <none>        5432/TCP                     70s
pg-ro             ClusterIP   10.43.98.44     <none>        5432/TCP                     70s
pg-rw             ClusterIP   10.43.66.233    <none>        5432/TCP                     69s
Service leads to
pg-rw the primary – reading and writing
pg-ro only the replicas – reading
pg-r all instances – reading

With one instance there are no replicas; the difference matters as soon as you have more instances.

Remember: Applications always write through pg-rw. Which pod is currently the primary is known to the operator, not to the application.

Save your progress? Sign up for free

Drill 3: Switching on pgvector

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

What you have afterwards: the extension vector in the database rag.

Step 1 – is it in the image?

# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "SELECT name, default_version FROM pg_available_extensions WHERE name = 'vector';"
Option Meaning
exec pg-1 -c postgres command in the container postgres of the pod pg-1
psql -d rag -c "…" run one SQL statement in the database rag; inside the container, psql logs in as the superuser postgres
pg_available_extensions list of the extensions that can be installed

Expected:

  name  | default_version
--------+-----------------
 vector | 0.8.7
(1 row)

Step 2 – switch it on.

# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "CREATE EXTENSION vector;"

Expected:

CREATE EXTENSION
# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "\dx vector"

Expected:

                                    List of installed extensions
  Name  | Version | Default version | Schema |                     Description
--------+---------+-----------------+--------+------------------------------------------------------
 vector | 0.8.7   | 0.8.7           | public | vector data type and ivfflat and hnsw access methods
(1 row)

What you see: pgvector 0.8.7 with two index types: ivfflat and hnsw.

Remember: Extensions only exist if they are in the image. Check pg_available_extensions before you choose an image – not only once you are in operation.

Save your progress? Sign up for free

Drill 4: The cards into the drawer

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

What you have afterwards: the table karten (cards) with the same four cards as in Qdrant.

Step 1 – build the SQL from the points. The same punkte.json as yesterday becomes an SQL script:

# on rag1
jq -r '"CREATE TABLE karten (id int PRIMARY KEY, abteilung text, text text, embedding vector(1024));", (.points[] | "INSERT INTO karten VALUES (\(.id), $q$\(.payload.abteilung)$q$, $q$\(.payload.text)$q$, $q$\(.vector | tojson)$q$);")' ../04/punkte.json > karten.sql
Part Meaning
-r output text, not as a JSON string
first string the table: ID, department, text and a column vector(1024)
.points[] \| "INSERT …" one INSERT line per point
$q$…$q$ PostgreSQL dollar quoting: everything in between is text, including the colons and quotes of the cards
.vector \| tojson the vector as […] – exactly the format pgvector reads
# on rag1
head -c 300 karten.sql

Expected (beginning):

CREATE TABLE karten (id int PRIMARY KEY, abteilung text, text text, embedding vector(1024));
INSERT INTO karten VALUES (1, $q$IT$q$, $q$Druckdienst neu starten: Melde dich am Druckserver druck01 an und führe sudo systemctl restart cups aus. Prüfe danach mit lpstat -r, ob der Dienst läuft. Hängen

Step 2 – execute. psql reads the script from standard input:

# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < karten.sql

-i passes your input through to the command in the pod; < karten.sql is that input.

Expected:

CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1

Step 3 – check.

# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "SELECT id, abteilung, left(text, 40) AS anfang, vector_dims(embedding) AS dims FROM karten ORDER BY id;"

Expected:

 id | abteilung |                  anfang                  | dims
----+-----------+------------------------------------------+------
  1 | IT        | Druckdienst neu starten: Melde dich am D | 1024
  2 | IT        | VPN-Zugang einrichten: Lade das Profil f | 1024
  3 | Personal  | Urlaub beantragen: Trage den Urlaub im P | 1024
  4 | IT        | Backup wiederherstellen: Die Sicherungen | 1024
(4 rows)
# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "SELECT pg_size_pretty(pg_total_relation_size('karten'));"

Expected:

 pg_size_pretty
----------------
 88 kB
(1 row)

Remember: In pgvector a card is a perfectly ordinary row. Text, stamp and vector sit side by side in columns – and everything PostgreSQL can do applies to them too.

Save your progress? Sign up for free

Drill 5: Searching and filtering

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

What you have afterwards: the same searches as in Qdrant, as SQL.

Step 1 – build the query.

# on rag1
jq -r '"WITH frage AS (SELECT $q$\(.embeddings[0] | tojson)$q$::vector AS v) SELECT id, abteilung, 1 - (embedding <=> frage.v) AS aehnlichkeit FROM karten, frage ORDER BY embedding <=> frage.v LIMIT 3;"' ../01/frage1-embed.json > suche1.sql
Part Meaning
WITH frage AS (SELECT …::vector AS v) the question vector once as a table frage (question) with the column v
1 - (embedding <=> frage.v) similarity from the cosine distance
ORDER BY embedding <=> frage.v sort by distance – smallest first
LIMIT 3 the three nearest

Step 2 – search.

# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < suche1.sql

Expected:

 id | abteilung |    aehnlichkeit
----+-----------+--------------------
  1 | IT        | 0.7544954993746498
  4 | IT        | 0.4635016322137111
  2 | IT        | 0.4392352989982258
(3 rows)

What you see: the same three cards in the same order as in Qdrant (aehnlichkeit is the similarity). The values differ from the seventh decimal place on: like Qdrant, pgvector stores the numbers with 32 bits and then computes with 64 bits.

Tool Print card
jq (Day 1) 0.7544958303555799
Qdrant (Day 4) 0.75449586
pgvector 0.7544954993746498

Step 3 – with a filter. The laptop question, only IT cards:

# on rag1
jq -r '"WITH frage AS (SELECT $q$\(.embeddings[0] | tojson)$q$::vector AS v) SELECT id, abteilung, 1 - (embedding <=> frage.v) AS aehnlichkeit FROM karten, frage WHERE abteilung = $q$IT$q$ ORDER BY embedding <=> frage.v LIMIT 3;"' ../01/frage4-embed.json > suche4-it.sql
# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < suche4-it.sql

Expected:

 id | abteilung |    aehnlichkeit
----+-----------+---------------------
  2 | IT        | 0.43197934461132415
  1 | IT        |  0.4279991559984312
  4 | IT        |   0.380781324096085
(3 rows)

The filter is a perfectly ordinary WHERE – and the result matches Qdrant’s from Day 4.

Remember: In pgvector the filter is SQL. What is a payload condition in Qdrant is a column in the WHERE here – with everything SQL can do: joins, permissions, transactions.

Save your progress? Sign up for free

Drill 6: The index and the query plan

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

What you have afterwards: an HNSW index – and the insight that PostgreSQL does not use it with four rows.

Step 1 – the plan without an index. EXPLAIN (ANALYZE, COSTS OFF) in front of a query executes it and shows how PostgreSQL executed it. You build the same query as in Drill 5, just with this prefix:

# on rag1
jq -r '"EXPLAIN (ANALYZE, COSTS OFF) WITH frage AS (SELECT $q$\(.embeddings[0] | tojson)$q$::vector AS v) SELECT id, abteilung, 1 - (embedding <=> frage.v) AS aehnlichkeit FROM karten, frage ORDER BY embedding <=> frage.v LIMIT 3;"' ../01/frage1-embed.json > plan1.sql

ANALYZE really executes the query and measures the times, COSTS OFF leaves out the planner’s estimates.

# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < plan1.sql

Expected (excerpt – the Sort Key line is several thousand characters long in the original because it contains the whole question vector):

 Limit (actual time=0.444..0.448 rows=3.00 loops=1)
   ->  Sort (actual time=0.442..0.444 rows=3.00 loops=1)
         Sort Method: quicksort  Memory: 25kB
         ->  Seq Scan on karten (actual time=0.241..0.334 rows=4.00 loops=1)
 Planning Time: 1.352 ms
 Execution Time: 0.563 ms

What you see: Seq Scan – PostgreSQL reads all four rows, computes every distance and sorts. Exactly what you did with jq on Day 1.

Step 2 – create the index.

# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "CREATE INDEX karten_hnsw ON karten USING hnsw (embedding vector_cosine_ops);"
Part Meaning
USING hnsw index type HNSW, as in Qdrant
vector_cosine_ops the index applies to the cosine distance <=>; other distance measures have other classes

Expected:

CREATE INDEX
# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "\di+ karten_hnsw"

Expected (excerpt – columns name, type, size):

 karten_hnsw | index | postgres | karten | permanent | hnsw | 40 kB |

Step 3 – the plan with the index.

# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < plan1.sql

Expected (excerpt):

         ->  Seq Scan on karten (actual time=0.666..0.803 rows=4.00 loops=1)
 Execution Time: 1.099 ms

What you see: still Seq Scan. The planner estimates that four rows are read faster directly than through the index – the same decision Qdrant makes with its threshold.

Step 4 – force the index. Just to look at it, you forbid the seq scan for this one session. psql executes several -c and -f one after another in the same session:

# on rag1
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag -c "SET enable_seqscan = off;" -f - < plan1.sql
Option Meaning
-c "SET enable_seqscan = off;" first: forbid the seq scan for this session
-f - then: read statements from standard input – here plan1.sql

Expected (excerpt):

SET
   ->  Index Scan using karten_hnsw on karten (actual time=0.742..0.826 rows=3.00 loops=1)
 Planning Time: 1.445 ms
 Execution Time: 1.049 ms

Now the search runs over the floor plan. With four rows that is no gain – with millions it is.

Remember: An index is not used because it exists, but when the planner considers it faster. EXPLAIN shows what it decided.

Save your progress? Sign up for free

Drill 7: The comparison

Where you are: on rag1.

What you have afterwards: a table with which you can answer the architecture question for this lab.

Step 1 – memory and CPU.

# on rag1
kubectl top pod -n rag

Expected (excerpt):

NAME                     CPU(cores)   MEMORY(bytes)
pg-1                     80m          52Mi
qdrant-0                 7m           49Mi

Step 2 – bring it together.

Qdrant (Day 4) pgvector
Installation one Helm chart operator plus Cluster manifest
Memory when idle 49 MiB 52 MiB
Hits and order as on Day 1 as on Day 1
Filter payload condition in JSON WHERE in SQL
Index with 4 cards none (below the threshold) created, but not used by the planner
Search 3 ms (REST) 0.6 ms in the plan

For four cards both are equally good. The differences show with large volumes, with replication and backup – topics of Days 10 to 12, on which you run both systems side by side again.

Remember: If your team has PostgreSQL under control anyway, pgvector is a serious option. A dedicated vector database pays off when volume, filters or operations really demand it – and that is something you measure.

Save your progress? Sign up for free

Diagnosis task

A colleague creates an HNSW index and is puzzled: “The query is not one bit faster, the index is never used.” He has 200 rows. You have ten minutes.

Solution: Put EXPLAIN (ANALYZE) in front of the query (Drill 6). If it says Seq Scan, the planner discarded the index – rightly so with few rows. To check, set SET enable_seqscan = off; in a session: if Index Scan using … then appears, the index is fine, it just does not pay off yet. Also check whether the query uses the same operator as the index: an index with vector_cosine_ops only helps with <=>.

Challenge

Create the table karten_nomic with vector(768) and store the cards with the nomic-embed-text vectors from Day 2. Ask the paraphrased question from Day 1. Do you get the same wrong result as on Day 2?

Save your progress? Sign up for free

Checkpoint

# on rag1
kubectl -n rag get cluster pg

Expected: Cluster in healthy state.

# on rag1
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "SELECT count(*) FROM karten;"

Expected: 4.

Test yourself

  1. Why does the query say 1 - (embedding <=> frage.v) and not just embedding <=> frage.v?
  2. What is the service pg-rw for?
  3. How did you recognise that pgvector is included in the image?
  4. Why does PostgreSQL not use the HNSW index with four rows?
  5. When would you prefer pgvector to Qdrant?

Answers:

  1. <=> is the cosine distance. The similarity from Day 1 is 1 minus the distance.
  2. It always points to the primary; applications write through it, no matter which pod is currently the primary.
  3. vector was listed in pg_available_extensions.
  4. The planner considers the seq scan cheaper. When forced with enable_seqscan = off, the index is used.
  5. When the team already runs PostgreSQL and the volumes are manageable – backup, permissions and monitoring then already exist. Whether it is enough is shown by a test with your own data.

Interview note

“pgvector or a dedicated vector database?” – Answer with a test instead of a preference: same data, same questions, same filters; then volume, latency, operations. Mention that pgvector has the advantage of existing tools (backup, permissions, joins) and that you check with EXPLAIN whether an index takes effect at all. A number like “with four rows the planner does not use the index” shows that you have looked inside.

Enterprise note

In companies, PostgreSQL is often already run centrally, with backup, monitoring and an access concept. A RAG project that docks onto it saves an operations component – but needs agreements on storage, indexes and load, because HNSW indexes are large and building them costs CPU. CloudNativePG brings replicas, failover and backups to S3; you use them on Day 12.

Summary

You installed CloudNativePG 1.30.2 and created a PostgreSQL 18 cluster with a short manifest. The “standard” image brought pgvector 0.8.7. The four cards are rows in the table karten, 88 kB in size. The search with <=> returned the same cards as Qdrant and jq; the filter is a WHERE. The planner ignored an HNSW index with four rows; when forced, the search ran over it. When idle, PostgreSQL and Qdrant need the same amount of memory here.

Commands at a glance

Command What it does Parameters
helm install cnpg cnpg/cloudnative-pg -n cnpg-system --create-namespace --version 0.29.2 install the operator –
kubectl -n rag wait --for=condition=Ready cluster/pg wait for the cluster --timeout
kubectl -n rag get cluster pg state and primary –
kubectl -n rag exec pg-1 -c postgres -- psql -d rag -c "<sql>" run SQL in the pod -c container or statement
kubectl -n rag exec -i pg-1 -c postgres -- psql -d rag < datei.sql run an SQL file -i pass input through
CREATE EXTENSION vector; switch on pgvector –
… ORDER BY embedding <=> v LIMIT 3 nearest neighbours <=> cosine distance
CREATE INDEX … USING hnsw (embedding vector_cosine_ops) HNSW index operator class matching the distance
EXPLAIN (ANALYZE, COSTS OFF) … query plan with real times –
SET enable_seqscan = off; forbid the seq scan for the session for testing only
kubectl top pod -n rag CPU and memory –

Contents

More