Skip to main content

pgshrink

How much smaller can your pgvector index get without changing your search results? Measure it on your own data in seconds, then get the SQL.

CI PyPI License: Apache-2.0 Python pgvector

pgshrink demo

pgvector can store and index vectors as halfvec (16-bit), as bit via binary_quantize(), or truncated with subvector(). The docs say to quantize at scale, but they can't tell you how much quality your embeddings lose. That depends on your model and your data.

pgshrink reads your vector column and tries every layout pgvector supports. For each one it tells you:

  • fidelity: how often you get the same top-k results as today, with a 95% confidence interval;
  • index size: how large the HNSW index would be, from a model fitted on real pgvector indexes;
  • a verdict: whether shrinking is worth doing now, based on whether today's index already fits in the memory Postgres uses, plus how much smaller the index could get;
  • the SQL: the index and the query to switch to the recommended layout.

It needs no labels and no test queries, and it never writes to your database.

Example: 171k documents, 1024-dim embeddings

The demo above runs on TREC-COVID embedded with Qwen3-Embedding-0.6B. We then built every recommended index and queried it through real pgvector HNSW to check the predictions (full method):

layout HNSW index pgshrink fidelity (predicted) real HNSW fidelity p50 query
vector (today) 1338 MB 100% 100% 324 ms*
halfvec 446 MB 100.0% 98.1% 2.2 ms
binary_quantize + rerank ×10 70 MB 98.9% 97.6% 2.0 ms

* The 1.3 GB index did not fit in this server's memory and the compressed ones did. The speedup depends on your hardware and settings, so measure it on yours. The index sizes and fidelity numbers are what pgshrink predicts.

Two things people usually don't expect:

  • halfvec makes the index ~3× smaller, not 2×. pgvector packs whole rows into 8 KB pages, so a 4 KB vector fills a page alone, while three halfvec rows fit in one.
  • Binary + rerank shrinks the index ~19× and keeps ~98% of results. The rerank reads the original column, so the table stays the same size. Only the index, which is what needs to stay in RAM, shrinks.

Install

pip install pgshrink        # or: uv tool install pgshrink

You need Python 3.10+ and network access to your Postgres. Nothing is installed in the database.

Quick start

pgshrink analyze "postgresql://user@host:5432/db" --table documents --column embedding

Pass the password via PGPASSWORD or ~/.pgpass rather than in the URL. pgshrink reads the distance (cosine, inner product or L2) from your existing vector index; if there is none, add --metric cosine.

To get the full report as JSON (for CI, dashboards or scripts):

pgshrink analyze "$DATABASE_URL" --table documents --column embedding --json > pgshrink.json

How it works

flowchart LR
    A[(your table)] -->|"200 random rows<br/>as queries"| Q[queries]
    A -->|"COPY ... BINARY<br/>whole column, streamed"| S[exact search<br/>on current vectors]
    Q --> S
    S --> T[true top-k<br/>per query]
    A --> L["each layout:<br/>halfvec · subvector · binary_quantize<br/>± rerank"]
    Q --> L
    L --> C{same top-k<br/>as today?}
    T --> C
    C --> R[report + SQL]
  1. Queries. About 200 random rows from your table serve as queries, and each one is excluded from its own results.
  2. Ground truth. pgshrink streams the whole column with COPY ... (FORMAT BINARY) (about 700 MB for 171k × 1024 dims, read in ~6 s locally) and computes the exact top-k for every query. It compares against the full table on purpose: a sample would make reranking look better than it is, because 100 candidates cover far more of 5,000 rows than of 1,000,000.
  3. Layouts. It reproduces in numpy exactly what pgvector computes (halfvec rounding, subvector truncation, binary_quantize signs, Hamming ranking, reranking on the original vectors). The integration tests check this against a real pgvector.
  4. Fidelity. For each layout, it reports the share of the true top-k found in the layout's top-k, averaged over queries, with a bootstrap 95% CI.
  5. Recommendation. Among the layouts whose lower CI bound reaches --target (default 95%), sizes within 25% of the smallest count as equal, and the one with the least rerank work wins. This avoids trading fidelity and twice the rerank cost for a few MB.
  6. Verdict. It compares today's index with the server's shared_buffers and effective_cache_size:
verdict when what it means
NOT NEEDED NOW index ≤ shared_buffers searches already run from memory; a smaller index saves RAM but won't make them noticeably faster. The SQL is printed for later.
OPTIONAL index ≤ effective_cache_size the OS may already cache it; shrinking frees memory and keeps searches fast as the table grows
RECOMMENDED index > effective_cache_size searches likely read from disk; an index that fits in memory can make them much faster

effective_cache_size is a setting your admin chose, not measured RAM, so read the verdict together with what you know about your server.

The verdict also says how many rows each index can grow to before it outgrows shared_buffers and effective_cache_size. For TREC-COVID, today's index stops fitting in effective_cache_size at ~524k rows, while the binary one fits up to ~10M. This counts index size only: rerank fidelity drops as the table grows, so re-run pgshrink when you get close.

Applying the recommendation

pgshrink prints the SQL but never runs it. Try it on a copy or a replica first.

1. Build the new index next to the old one. CONCURRENTLY doesn't block writes.

CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_embedding_binary1024_idx
  ON documents USING hnsw ((binary_quantize(embedding)::bit(1024)) bit_hamming_ops);

2. Change your search query to use the same expression. The planner only uses an expression index when the query matches it exactly. With reranking, fetch k × rerank candidates from the small index, then order them with the original vectors:

SET hnsw.ef_search = 200;                -- 2x the candidates: the graph misses fewer of them
SET hnsw.iterative_scan = relaxed_order; -- pgvector 0.8+: keeps 100 candidates under a WHERE filter
SELECT * FROM (
  SELECT * FROM documents                -- put any WHERE filter here, inside the subquery
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
  LIMIT 100
) candidates
ORDER BY embedding <=> $1::vector(1024)
LIMIT 10;

In Python (psycopg 3 + pgvector):

from pgvector.psycopg import register_vector

SEARCH = """
SELECT id, title FROM (
  SELECT id, title, embedding FROM documents
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize(%(q)s::vector(1024))::bit(1024)
  LIMIT 100
) c ORDER BY embedding <=> %(q)s::vector(1024) LIMIT 10
"""

register_vector(conn)
with conn.transaction():
    conn.execute("SET LOCAL hnsw.ef_search = 200")
    conn.execute("SET LOCAL hnsw.iterative_scan = relaxed_order")  # pgvector 0.8+
    rows = conn.execute(SEARCH, {"q": query_embedding}).fetchall()

In Node.js (pg + pgvector):

import pgvector from 'pgvector/pg';

const SEARCH = `
SELECT id, title FROM (
  SELECT id, title, embedding FROM documents
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
  LIMIT 100
) c ORDER BY embedding <=> $1::vector(1024) LIMIT 10`;

await client.query('BEGIN');
await client.query('SET LOCAL hnsw.ef_search = 200');
await client.query('SET LOCAL hnsw.iterative_scan = relaxed_order'); // pgvector 0.8+
const { rows } = await client.query(SEARCH, [pgvector.toSql(queryEmbedding)]);
await client.query('COMMIT');

Filters. HNSW applies a WHERE filter after searching. With a selective filter (one tenant, one category), the subquery can get far fewer than 100 candidates and fidelity drops, which pgshrink can't see because it simulates exact search. Put the filter inside the subquery and, on pgvector 0.8+, set hnsw.iterative_scan = relaxed_order (pgshrink prints it when your server supports it): the scan keeps going until it has enough candidates, and the outer ORDER BY restores the exact order. The new index keeps your current index's m, which the size estimate assumes.

3. Check it on your traffic. Run EXPLAIN on the new query and look for the new index. Then compare results against the old query for a sample of real searches.

4. Drop the old index once the new queries are live, to free its memory. To roll back, switch the query back; the old index is untouched until you drop it.

Options

option default meaning
--table required table name, optionally schema.table
--column required a vector(n) column
--metric from the index cosine, ip or l2
--k 10 top-k to compare
--queries 200 random rows used as queries
--target 0.95 minimum lower 95% bound of fidelity for a recommendation
--max-rows 2,000,000 rows scanned; above this a random subset is used (reported). Raise it for bigger tables
--rerank 4,10 rerank oversampling factors to try, e.g. --rerank 10,20,40 on millions of rows
--seed 0 same seed, same queries and same results
--json off machine-readable report

Safety

  • Every transaction is opened with default_transaction_read_only = on, and a test checks that writes fail.
  • It reads the vector column and ctid, plus catalog metadata: column type, row estimate, index names and sizes. It reads no other columns.
  • It writes nothing to disk and never logs the connection string.
  • statement_timeout defaults to 5 minutes.
  • On a managed database, scanning the column costs one sequential read of it. Run it against a replica if you can.

What it does not tell you

  • Rerank gets harder as the table grows. The same number of candidates covers a smaller share of the rows, so re-run pgshrink when the table has grown a few times.
  • Fidelity is not retrieval quality. It measures "same results as today". If today's results are wrong, they stay wrong. That is also why it needs no labels.
  • The queries are your stored rows. If your model embeds queries differently from documents (e5's query: prefix, instruction prompts), real queries may behave a little differently.
  • HNSW adds its own approximation on top of compression, and it grows with the table: about −1 point at 171k rows and −3 to −4 at 1M rows in our validation (details). The printed SQL sets hnsw.ef_search to 2× the candidates, which recovers about a point. On millions of rows, raise --target (e.g. --target 0.99) so pgshrink picks a bigger rerank: ×20 kept 97.5% at 1M rows.
  • Truncation (subvector) only makes sense for Matryoshka-trained models. pgshrink measures it either way, and a large drop is the signal that your model isn't one.
  • The index size is an estimate from a page-packing model fitted on real pgvector HNSW indexes: within 3% at m = 16, and within 2% from m = 8 to m = 32 (validation). m matters a lot for binary indexes (about 2× from m = 8 to m = 32), and not at all for 1024-dim halfvec (3 rows per page either way).
  • It doesn't measure write cost. In our test the binary index took about 6× more inserts and updates per second than vector and vacuumed 7× faster, while halfvec was only about 1.3× faster (validation). VACUUM on HNSW stays slow with every layout, so if your table changes a lot, check it under your real write rate.
  • It sizes HNSW indexes only. For 1024-dim halfvec, an IVFFlat index came out the same size as HNSW in our tests, so it doesn't save memory there.
  • For now it supports vector(n) columns on pgvector 0.7+ (needed for halfvec and binary_quantize).

Development

git clone https://github.com/alessandroamormino/pgshrink && cd pgshrink
uv sync
uv run pytest                                  # unit tests

docker run -d --name pgshrink-test -e POSTGRES_PASSWORD=pg -p 55432:5432 pgvector/pgvector:pg17
PGSHRINK_TEST_DSN=postgresql://postgres:pg@localhost:55432/postgres uv run pytest   # + integration tests

The integration tests run every printed SQL statement against a real pgvector. They check that it returns the neighbors that pgshrink's numpy model predicts, and that the connection really is read-only.

Issues and pull requests are welcome, especially reports of how the numbers compare with your production results.

License

Apache-2.0

Metadata

Release files for pgshrink 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pgshrink 0.4.0
File Size Uploaded Provenance Actions
pgshrink-0.4.0.tar.gz 355.7 kB Without provenance Details for pgshrink-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pgshrink 0.4.0
File Interpreter ABI Platform Actions
pgshrink-0.4.0-py3-none-any.whl Python 3 none any Details for pgshrink-0.4.0-py3-none-any.whl

Total release size: 378.1 kB

Release files / pgshrink-0.4.0.tar.gz

Download URL pgshrink-0.4.0.tar.gz
Size 355.7 kB
Tags Source
SHA-256 checksum
How to use checksums
171f793fe5e9d58771a8c0d5b88aafc01160981e949e9aaa5643108c57ab81ee
BLAKE2b-256 checksum
How to use checksums
7159610886d65539950c530c9913a5827f65d00748efd8699434c2b40f29bf29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pgshrink-0.4.0-py3-none-any.whl

Download URL pgshrink-0.4.0-py3-none-any.whl
Size 22.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8afb06bcae49628535ddee42a7f37d64debdc2fa24b4ce711bfad8f44978a3dc
BLAKE2b-256 checksum
How to use checksums
54ed6caaf4e26c42e8700b42f42114c4386c4fd8b7655b421cb11696b880cce2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pgshrink 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page