Vectors and semantic search
Store embeddings next to your data and search them with one SDK call. Row Level Security applies, so each caller only retrieves rows they may read. Generate the table, the HNSW index and the match_<table> function with vectorTableSql(table, dims, metric) from @potalab/base; the dimension must match your embedding model (HNSW supports at most 2000 dimensions). Turn on the vector extension first (see Extensions).
Bulk loading and HNSW tuning
Section titled “Bulk loading and HNSW tuning”Most of the cost of writing vectors is inserting into the HNSW graph, not the row itself. Measured on a 64-dimension table of 2000 rows, upserting 50 rows, measured on the dev stack:
| index | 50-row upsert |
|---|---|
| none | 0.5 ms |
HNSW default (m = 16, ef_construction = 64) |
44.5 ms |
ef_construction = 32 |
37.5 ms |
m = 8, ef_construction = 32 |
14.2 ms |
More than 98 % of the default time is graph insertion. Over HTTP the same upsert also pays for the GIN index on metadata,
RLS and audit triggers (about 119 ms in the same test). So for a big import:
- Create the table without the vector index (take the SQL from
vectorTableSql, leave out theCREATE INDEX ... hnswline). - Load the rows in batches (
base.vectors.upserttakes many rows per call). - Build the index once at the end. It is much faster than maintaining the graph row by row, and it uses
maintenance_work_mem(256 MB on the dev stack; raise it for a large table, and addmax_parallel_maintenance_workers):
SET maintenance_work_mem = '1GB';CREATE INDEX CONCURRENTLY kb_embedding_hnsw ON public.kb USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);Until the index exists, searches do a sequential scan: exact, but slow on a large table. Build it before you go live.
Choosing m and ef_construction. Lower values make writes faster and the index smaller, but cost recall (fewer
true nearest neighbours are returned):
- Read-mostly or bulk-loaded data: keep the defaults, or go higher (
m = 24,ef_construction = 128) if recall matters more than build time. Build once, so the cost does not repeat. - Continuous writes (chat history, event streams): accept
m = 8..12andef_construction = 32..40for roughly 3x cheaper writes. Compensate at query time withSET hnsw.ef_search = 100(default 40); a higher value raises recall and latency per search. - We have not measured recall for these settings on your data. Compare against an exact scan (
SET enable_indexscan = off) on a sample of real queries before lowering the defaults.vectorTableSqlkeeps the defaults for that reason.
maintenance_work_mem only affects index builds, not individual inserts.