Inside vector indexes

Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:15 on Monday. Adding ticket history grew SwiftKart's index to 10 million chunks, and three things went wrong at once. The new CREATE INDEX ran for nine hours over the weekend and printed a NOTICE nobody read. A Northwind search returns one chunk for LIMIT 5. And Dana says the database server suddenly needs twice its memory. Nora: "None of this is the model. Open up the index."

You'll learn to

  • Explain how flat search, IVF and HNSW find the nearest vectors
  • Tune probes and ef_search from recall measured on your own data
  • Work out what an index costs in memory, and shrink it
  • Plan index builds, deletes and filtered searches

Learn

Three complaints, one index

A vector index answers one question: which k stored vectors are nearest to this one?

With no index, the database measures the question against every stored vector. This is called flat search. It never misses, and it is fine for one tenant's 5,000 rows.

An index looks at a small part of the data and accepts that it may miss a true neighbour now and then. The share of true neighbours it does find is its recall (Lesson 16.2). There are two families. IVF sorts the vectors into groups and opens a few of them. HNSW links the vectors into a graph and walks it.

Both trade recall for work, and each has one knob that sets the trade. All three of Monday's complaints come from how these two are built.

IVF: sort into lists, open a few

IVF, short for inverted file, works like a library. Books are sorted onto shelves by subject once. To find a book you walk to the right shelf and read only that shelf.

Build. The index groups similar vectors with an algorithm called k-means. The middle of each group is its centroid, and every row is filed in the list of its nearest centroid. The setting lists says how many groups to make.

Query. Compare the question with every centroid. Open the nearest few lists and measure every row in them exactly. The setting ivfflat.probes says how many lists to open: 1 by default.

The risk. A true neighbour filed in a list you did not open is invisible.

An IVF search by hand, with one probe

Four steps over twelve chunks filed in four lists: the lists as built, the question compared with the four centroids with list 2 nearest, list 2 opened and its three chunks measured with chunk 11 best at 0.875, and chunk 4 in the unopened list 3, the true best match at 0.983, never measured.

  1. The build: four lists. k-means found four centroids, one per topic, and every one of the 12 help chunks was filed under its nearest centroid.

  2. The query meets the centroids. "Is my refund for the failed payment coming?" is compared with 4 centroids, not 12 chunks. List 2, returns, is nearest at 0.860. List 3, payments, is second at 0.770.

  3. One probe: open list 2 only. Its 3 chunks are measured exactly. Chunk 11 is the best of them, at 0.875. The other 9 chunks are never looked at.

  4. What one probe missed. Chunk 4, about refunds to the original payment method, scores 0.983. It was filed in list 3, one list too far.

Each box is one list with the chunks filed in it. The question is about a refund and a payment, so it sits near the border between two lists. Borders are where IVF misses.

An IVF index by hand, in Postgres arrays

-- "Is my refund for the failed payment coming?" = {0.2,0.7,0.6,0}
WITH probed AS (
  SELECT list_id
  FROM ivf_lists
  ORDER BY cosine_sim(centroid, '{0.2,0.7,0.6,0}') DESC, list_id
  LIMIT 1                                   -- ivfflat.probes = 1
)
SELECT c.chunk_id,
       c.list_id,
       ROUND(cosine_sim(c.embedding, '{0.2,0.7,0.6,0}')::numeric, 3) AS similarity
FROM chunks AS c
JOIN probed AS p ON p.list_id = c.list_id
ORDER BY similarity DESC, c.chunk_id
LIMIT 3;

The same search in SQL. The setup stores the 4 centroids in ivf_lists and files each chunk under its nearest one, as a build does. With one probe, 3 of 12 chunks are scanned and chunk 4 is missed. Change LIMIT 1 to LIMIT 2 in probed and chunk 4 comes first.

One IVF query over a million rows

Four steps: compare the question with 1,000 centroids, keep the 32 nearest lists, scan about 32,000 vectors in them exactly, and sort to keep the top 10: about 33,000 distances instead of a million.

The same four moves at real size, read left to right. The work is about lists + probes × rows / lists. k-means does not make equal lists, so the real number varies from query to query.

Two more things about IVF before you pick it.

The centroids come from the data, so create the index after the table has rows. And the centroids never move. New rows join the nearest existing list, so after a lot of change the lists grow lopsided and recall drifts. Rebuild the index on a schedule.

IVF in NumPy: recall against vectors scanned

import numpy as np

rng = np.random.default_rng(7)
centres = rng.standard_normal((40, 32))                 # 40 topics in 32 dimensions
docs = centres[rng.integers(0, 40, 4000)] + 0.7 * rng.standard_normal((4000, 32))
docs /= np.linalg.norm(docs, axis=1, keepdims=True)
queries = docs[rng.integers(0, 4000, 100)] + 0.2 * rng.standard_normal((100, 32))
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
exact = np.argsort(-(queries @ docs.T), axis=1, kind="stable")[:, :10]

# Build: k-means finds the centroids (the index's training step), then rows are filed
lists = 64
cent = docs[rng.choice(4000, lists, replace=False)]
for _ in range(10):
    assign = np.argmax(docs @ cent.T, axis=1)            # nearest centroid by cosine
    for j in range(lists):
        members = docs[assign == j]
        if len(members):
            c = members.mean(axis=0)
            cent[j] = c / np.linalg.norm(c)
sizes = np.bincount(assign, minlength=lists)
print("list sizes: min", sizes.min(), "max", sizes.max())

def ivf_search(q, probes, k=10):
    near = np.argsort(-(cent @ q), kind="stable")[:probes]   # the probes nearest lists
    cand = np.flatnonzero(np.isin(assign, near))            # every row filed under them
    best = cand[np.argsort(-(docs[cand] @ q), kind="stable")[:k]]
    return best, len(cand)

for probes in [1, 2, 4, 8, 16, 64]:
    rec, scanned = [], []
    for q, e in zip(queries, exact):
        found, n = ivf_search(q, probes)
        rec.append(len(set(found) & set(e)) / 10)
        scanned.append(n)
    print(f"probes {probes:2}: recall@10 {np.mean(rec):.2f}, vectors scanned {np.mean(scanned):6.0f} of 4000")

Each line is one setting of probes: the recall it buys and the vectors it scans. At probes = 8, which is sqrt(64), recall@10 is 0.98 for about 13% of the work. The data is seeded, so the numbers never change. 64 lists for 4,000 vectors is far more than rows / 1,000, to show the effect on small data, and the lists are not equal: they run from 6 to 119 rows.

HNSW: a graph with express lanes

The other family is a graph. HNSW stands for Hierarchical Navigable Small World. Think of driving to a house in a city you do not know: motorway to the right city, main roads to the right district, then small streets.

Links. Every vector is linked to a few of its nearest neighbours: up to m of them per layer, and 2 × m on the bottom layer.

Layers. The bottom layer, layer 0, holds every vector. Each vector also draws a random level. With m = 16, about 1 vector in 16 also appears on layer 1, 1 in 256 on layer 2, and so on. The upper layers are sparse: they are the motorways.

Search. Start at the top and walk towards the question, layer by layer.

A search walks down the layers

Four steps down the six layers of an HNSW index over 10 million vectors with m of 16: the search starts on layer 5 with about 10 points, hops greedily through layers 4 to 1, then on layer 0 keeps a list of the ef_search best points and expands the nearest until none can improve it; that list is the answer.

  1. Start at the top. Layer 5 has about 10 points. The search begins at a fixed entry point, looks at its links and moves to whichever is nearer the question. When no link is nearer, it stops.

  2. Drop a layer and walk again. The point it stopped on exists on the layer below too. Each layer has 16 times more points, so each hop there is shorter. A handful of hops per layer.

  3. Layer 0: widen the search. One nearest point is no longer enough. The search keeps a list of the ef_search best points found so far, 40 by default, and keeps following the links of the nearest one it has not followed yet.

  4. The list is the answer. When no candidate can improve the list, the search stops. LIMIT takes the top of that list, so a scan returns at most ef_search rows.

Read it top to bottom. The sizes are what you would expect for 10 million vectors with m = 16: each layer keeps about 1 point in 16 of the layer below, which gives about 6 layers. The search measures a few hundred vectors, not 10 million.

Step through a real HNSW search

An HNSW index over 48 toy help chunks drawn as layers of points and links: the search starts at the entry point on the top layer, walks greedily down, then widens on layer 0 with an ef_search list; sliders for ef_search, m and ef_construction show recall against the exact answer and the points measured, and a calculator shows the memory of a pgvector index for N vectors of D dimensions.

Press Next step to follow the walk on 48 points. Then play with the sliders. Query A at ef_search = 3 misses one of the true top 3, and at 5 it finds all three. After that try m = 2, or ef_construction = 4 on Query B, and watch recall fall.

HNSW in NumPy: build it, then search at five ef_search values

import heapq
import numpy as np

rng = np.random.default_rng(7)
centres = rng.standard_normal((40, 32))
docs = centres[rng.integers(0, 40, 2000)] + 1.0 * rng.standard_normal((2000, 32))
docs /= np.linalg.norm(docs, axis=1, keepdims=True)
queries = docs[rng.integers(0, 2000, 50)] + 0.2 * rng.standard_normal((50, 32))
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
exact = np.argsort(-(queries @ docs.T), axis=1, kind="stable")[:, :10]

M, EF_CONSTRUCTION = 8, 32
levels = np.floor(-np.log(1 - rng.random(len(docs))) / np.log(M)).astype(int)   # mL = 1 / ln(M)
graph = [dict() for _ in range(levels.max() + 1)]      # layer -> {point: [linked points]}
counter = [0]

def dist(ids, q):
    counter[0] += len(ids)
    return 1 - docs[ids] @ q                            # cosine distance

def search_layer(q, entry, ef, layer):
    """Beam search on one layer: up to ef (distance, point) pairs, nearest first."""
    d0 = dist(np.array(entry), q)
    seen = set(entry)
    cand = list(zip(d0, entry))
    best = [(-d, e) for d, e in cand]
    heapq.heapify(cand); heapq.heapify(best)
    while cand:
        d, c = heapq.heappop(cand)
        if d > -best[0][0] and len(best) >= ef:
            break                                       # nothing left can improve the list
        nbrs = [n for n in graph[layer].get(c, []) if n not in seen]
        seen.update(nbrs)
        if not nbrs:
            continue
        for dn, n in zip(dist(np.array(nbrs), q), nbrs):
            if len(best) < ef or dn < -best[0][0]:
                heapq.heappush(cand, (dn, n)); heapq.heappush(best, (-dn, n))
                if len(best) > ef:
                    heapq.heappop(best)
    return sorted((-d, n) for d, n in best)

def select(base, cands, cap):
    """The paper's heuristic: nearest first, skip one that is nearer to a kept link than to base."""
    kept = []
    for c in sorted(cands, key=lambda n: (1 - docs[n] @ docs[base], n)):
        if len(kept) == cap:
            break
        if not kept or 1 - docs[c] @ docs[base] < (1 - docs[kept] @ docs[c]).min():
            kept.append(c)
    return kept

entry, top = 0, levels[0]
for l in range(top + 1):
    graph[l][0] = []
for i in range(1, len(docs)):                           # insert every point
    q, ep = docs[i], [entry]
    for l in range(top, levels[i], -1):                 # greedy walk above its level
        ep = [search_layer(q, ep, 1, l)[0][1]]
    for l in range(min(top, levels[i]), -1, -1):        # link it on each of its layers
        found = search_layer(q, ep, EF_CONSTRUCTION, l)
        cap = 2 * M if l == 0 else M
        graph[l][i] = select(i, [n for _, n in found], M)
        for n in graph[l][i]:
            graph[l][n].append(i)
            if len(graph[l][n]) > cap:
                graph[l][n] = select(n, graph[l][n], cap)
        ep = [n for _, n in found]
    for l in range(top + 1, levels[i] + 1):
        graph[l][i] = []
    if levels[i] > top:
        entry, top = i, levels[i]
print("points per layer:", [len(g) for g in graph], "| distances measured while building:", counter[0])

def hnsw_search(q, ef, k=10):
    ep = [entry]
    for l in range(top, 0, -1):                         # express lanes: one candidate
        ep = [search_layer(q, ep, 1, l)[0][1]]
    return [n for _, n in search_layer(q, ep, max(ef, k), 0)[:k]]

for ef in [10, 20, 40, 80, 160]:
    counter[0] = 0
    rec = [len(set(hnsw_search(q, ef)) & set(e)) / 10 for q, e in zip(queries, exact)]
    print(f"ef_search {ef:3}: recall@10 {np.mean(rec):.3f}, distances per query {counter[0] / len(queries):4.0f} (flat: 2000)")

A whole HNSW index in about 80 lines: random levels, inserting each point with an ef_construction search, the rule that picks neighbours in different directions, and 2 × M links on layer 0. At the default ef_search of 40, recall@10 is 0.94 for about 300 of 2,000 distances. Going to 80 costs 1.7 times the work for the last few points of recall. The build takes a couple of seconds.

Three knobs, and only one is free

HNSW has three settings, and it matters which is which.

  • m (default 16): links per point. More links make the graph easier to cross, so recall rises. Each point also costs more memory, and builds slow down.
  • ef_construction (default 64): how many candidates the index weighs up when it inserts a point. Bigger means better neighbours and a slower build.
  • hnsw.ef_search (default 40): the length of the candidate list at query time. Bigger means higher recall and more distances measured.

The first two are fixed when the index is built. Changing them means a rebuild. Only ef_search can be turned per query: SET LOCAL hnsw.ef_search = 100. Choose it from a curve like the one you just printed: recall against time, on your own questions.

Flat, IVFFlat and HNSW in pgvector

Flat (no index)IVFFlatHNSW
Buildnothingk-means, then file every row: fast, needs data firstinsert every row into a graph: slow, memory-hungry, can start empty
Work per queryall N vectorslists centroids + probes / lists × N rowsabout efsearch expansions on layer 0, after a few greedy hops
Recall knobalways 1.0ivfflat.probes (default 1)hnsw.efsearch (default 40)
Build knobsnonelistsm (16), efconstruction (64)
New rowsnothing to dojoin the nearest existing list; centroids never movea search per row, then links rewritten
Use it forsmall or heavily filtered setslarge, mostly static tables, tight memorythe usual default: best speed for a given recall

Read across each row to compare the three. IVFFlat is pgvector's name for its IVF index. An "expansion" is one point whose links the search follows.

Why the server needs twice the memory

Now Dana's complaint. An HNSW index is not a small helper next to the table. Every entry holds its own copy of the vector, plus room for its links:

  • the vector: 4 × 1,536 + 8 = 6,152 bytes;
  • the links on layer 0: 2 × 16 links × 6 bytes = 192 bytes;
  • together 6,344 bytes per chunk.

Ten million chunks make a 63 GB index next to a 62 GB table. That is the doubling.

The index need not fit in memory, but every hop reads a page somewhere in the graph, so it is far faster when it does. And look at the sum again: the vector copy is almost all of it. Storing fewer bytes per number saves far more than lowering m.

One HNSW entry at 1,536 numbers, m = 16

Three bars on one scale: a float32 entry of 6,152 bytes of vector and 192 bytes of links, a halfvec expression-index entry of 3,080 plus 192, and a bit expression-index entry of 200 plus 192.

Three bars on one scale: the same index entry, stored three ways. For 10 million chunks that is 63.4 GB, 32.7 GB and 3.9 GB, plus headers. The trick is to quantize the index and keep the full vectors in the table. A halfvec index barely moves the ranking. A bit index keeps one sign bit per number and is much less accurate, so its query fetches several times more candidates than it needs and rescores them with the full vectors (Lesson 16.2 measured what that wins back).

An index changes your answers, and can silently not be used. Before you switch one on, run the evaluation set with exact search and with the index at the ef_search you plan to use. Compare recall@k and rows returned, for small and large tenants. Then read EXPLAIN: pgvector uses the index only for ORDER BY a distance operator, ascending, with a LIMIT. ORDER BY 1 - (embedding <=> q) DESC is an expression, and so is an operator that does not match the operator class. Both fall back to a full scan and a sort: the right answers, slowly.

pgvector index recipes

Runs on your laptop:

-- 1. Half precision in the index, full precision in the table (0.7.0+)
CREATE INDEX chunks_half_hnsw ON chunks
  USING hnsw ((embedding::halfvec(1536)) halfvec_cosine_ops);
SELECT chunk_id FROM chunks
ORDER BY embedding::halfvec(1536) <=> $1::halfvec(1536)
LIMIT 10;

-- 2. Binary quantization: search the bits, rescore with the real vectors
CREATE INDEX chunks_bits_hnsw ON chunks
  USING hnsw ((binary_quantize(embedding)::bit(1536)) bit_hamming_ops);
SELECT chunk_id
FROM (
  SELECT chunk_id, embedding
  FROM chunks
  ORDER BY binary_quantize(embedding)::bit(1536) <~> binary_quantize($1)
  LIMIT 40
) AS shortlist
ORDER BY embedding <=> $1
LIMIT 10;

-- 3. Filtered search: keep walking until enough rows pass (0.8.0+)
SET hnsw.iterative_scan = relaxed_order;
SET hnsw.max_scan_tuples = 20000;          -- the default

-- 4. One big tenant gets its own partial index
CREATE INDEX chunks_northwind_hnsw ON chunks
  USING hnsw (embedding vector_cosine_ops)
  WHERE tenant = 'northwind';

Recipes 1 and 2 follow pgvector's README. <~> is Hamming distance: the number of bits that differ. An expression index is used only when the ORDER BY repeats the same expression and operator. Recipes 3 and 4 belong to filtered search, further down.

Nine hours, and a NOTICE nobody read

Building HNSW means inserting every row: one search per vector, then rewriting the link lists of its new neighbours. It is fast while the whole graph fits in maintenance_work_mem, the memory a session may use for maintenance. The default is 64 MB. A 10-million-row index needs tens of GB.

When the graph stops fitting, pgvector prints hnsw graph no longer fits into maintenance_work_mem after N tuples, adds Building will take significantly more time, and carries on slowly. That was the NOTICE.

So raise the setting for the build session only, add parallel workers, and build CONCURRENTLY so writes can continue.

Writes cost more afterwards too. Every insert is a small search plus writes to the neighbours' pages. A delete only marks the entry, and VACUUM must later repair the links around it.

A build that fits, and how to watch it

Runs on your laptop:

SET maintenance_work_mem = '8GB';               -- this session only
SET max_parallel_maintenance_workers = 7;       -- plus the leader
CREATE INDEX CONCURRENTLY chunks_embedding_hnsw
  ON chunks USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

-- From a second session
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%"
FROM pg_stat_progress_create_index;
phase              |  %
--------------------------------+------
 building index: loading tuples | 41.3
(1 row)

A snapshot part-way through the build. The memory must really be free: 8 GB is a little more than the 6.3 GB that a million 1,536-number entries take by this lesson's sum.

One chunk for LIMIT 5

The third complaint is Lesson 16.4's sum, seen from the inside. On layer 0 the search keeps its ef_search best candidates, 40 by default, and that list is all the scan can hand back. A WHERE the index cannot use runs afterwards. Northwind owns 3% of the chunks, so about 1.2 of the 40 survive.

Pick the fix by the size of the tenant:

  • Iterative scans (pgvector 0.8.0 and later): the walk resumes until enough rows pass, up to hnsw.max_scan_tuples.
  • A partial index for a few large tenants, or partitions when there are many, so each graph only holds rows that pass.
  • No vector index for small slices: a B-tree on the filter and an exact scan, with perfect recall.

Remember: an HNSW scan returns at most ef_search rows, before any filter. Keep ef_search at least as large as your LIMIT, and larger when a filter will remove rows.

Numbers to remember

Setting or sumValueGood to know
lists (IVFFlat)Rows / 1,000 up to a million rows, sqrt(rows) aboveThe README's starting point. The build reports the phases performing k-means, assigning tuples and loading tuples
ivfflat.probesDefault 1. Start at sqrt(lists)Work per query is about lists + probes × rows / lists
A vector's level (HNSW)Level l or higher with probability 1 / m^lpgvector uses mL = 1 / ln(m). With m = 16, 10 million vectors need about 6 layers
mDefault 16, allowed 2 to 1002 × m links of 6 bytes on layer 0: 192 bytes at 16, 384 at 32
efconstructionDefault 64, allowed 4 to 1,000Fixed at build time, like m
hnsw.efsearchDefault 40, allowed 1 to 1,000Also the most rows a scan returns. Pick it from recall at the k you return against p95 latency
Bytes per HNSW entry4 × D + 8 + 2 × m × 6On layer 0, before page and tuple headers: 6,344 at 1,536 numbers and m = 16. The few points on upper layers add a little
Most dimensions an index takesvector 2,000, halfvec 4,000, bit 64,000Each is about 8,000 bytes, just under one 8 kB page. A 3,072-number model can only be indexed as halfvec or bit. Expression indexes on halfvec need pgvector 0.7.0 or later
maintenanceworkmemDefault 64 MBRaise it for the build session only. maxparallelmaintenanceworkers is 2 by default
Iterative scans (pgvector 0.8.0 and later)hnsw.iterativescan = strictorder or relaxedorderUp to hnsw.maxscantuples (20,000 by default) and a memory cap of hnsw.scanmemmultiplier × workmem. IVFFlat has ivfflat.iterativescan, capped by ivfflat.maxprobes
After mass deletesReindex firstThe README's advice, because VACUUM repairs the links slowly. IVFFlat inserts are cheap (one list), but its centroids go stale

Outside Postgres the names change and the trade-offs do not. Meta's FAISS library offers flat, IVF and HNSW indexes plus product quantization (PQ): each vector split into sub-vectors, one byte per sub-vector. Qdrant, Weaviate and Milvus build HNSW with scalar, binary or product quantization and rescoring. For indexes larger than memory, SSD-based graphs (the DiskANN family) keep compressed vectors in RAM and full ones on disk.

What changed at SwiftKart

On Tuesday night the index is built again, this time as a halfvec index, with maintenance_work_mem raised for that one session. No NOTICE, and it is done by morning. The index is 33 GB, not 63. Northwind gets a partial index of its own, and its searches fill their LIMIT again.

That closes the module. The assistant has what Lesson 16.1 promised: context it can find, tools it can use safely, a memory, a state, and numbers that say how well it all works.

Module 17 steps away from the keyboard. In a design interview nobody hands you a table. Lesson 17.1 starts with a way to answer: the requirements, the sketch, the trade-offs.

In one line

Flat search measures everything, IVF opens the nearest few lists, and HNSW walks layered links with an ef_search list that also caps the rows returned. Size an index before you build it: about N × (4D + 8 + 12m) bytes.

Interview corner

Walk me through an HNSW search. Why is it fast?

Every vector gets a random level, with about 1 in m reaching each next level, so the top layers are small and the graph has about log base m of N layers. The search starts at the entry point on the top layer, walks greedily to the nearest neighbour on each layer, drops down, and on layer 0 keeps the ef_search best candidates, expanding the nearest until none can improve the list. It measures a few hundred vectors instead of millions: in a small model, 300 of 2,000 at recall@10 of 0.94 with ef_search 40. The price is memory for the links, slow inserts, and results capped at ef_search rows.

IVFFlat or HNSW for 20 million chunks in Postgres?

HNSW by default: the better speed-recall trade-off, and it can be built before the data arrives. But at 1,536 dimensions it is about 20M × 6,344 bytes = 127 GB, which I would cut with a halfvec expression index to about 65 GB. IVFFlat uses less memory and builds much faster, with lists = sqrt(20M) ≈ 4,472 and probes starting near 67, which scans about 300,000 rows per query; its centroids never move, so it suits a mostly static table rebuilt on a schedule. I would decide on a recall-against-latency curve from our evaluation set.

Searches for small tenants return fewer rows than the LIMIT. Diagnose and fix.

EXPLAIN ANALYZE will show the index scan with the tenant filter and Rows Removed by Filter adding up to about ef_search: the index returned its 40 candidates and the filter ran after. For small tenants, exact search on a B-tree-filtered set is both fast and perfect; for large ones, a partition or partial index; otherwise iterative scans in pgvector 0.8, bounded by hnsw.max_scan_tuples. Then I add a metric for rows returned below the LIMIT, by tenant size.

What do inserts, updates and deletes do to a vector index?

An HNSW insert runs a search with ef_construction candidates and rewrites neighbours' link lists, so heavy write loads are much slower than with a B-tree. Deletes and updates leave entries marked dead; VACUUM has to repair the graph around them, which is slow, so after mass deletes I would REINDEX CONCURRENTLY. IVFFlat inserts are cheap, but new rows join the nearest existing centroid, which never moves, so recall drifts as the data changes and the index needs a scheduled rebuild.