pgshrink 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pgshrink-0.1.0/.github/workflows/ci.yml +32 -0
- pgshrink-0.1.0/.github/workflows/release.yml +19 -0
- pgshrink-0.1.0/.gitignore +7 -0
- pgshrink-0.1.0/LICENSE +202 -0
- pgshrink-0.1.0/PKG-INFO +206 -0
- pgshrink-0.1.0/README.md +194 -0
- pgshrink-0.1.0/docs/demo.gif +0 -0
- pgshrink-0.1.0/docs/demo.tape +20 -0
- pgshrink-0.1.0/docs/validation.md +51 -0
- pgshrink-0.1.0/pyproject.toml +25 -0
- pgshrink-0.1.0/src/pgshrink/__init__.py +3 -0
- pgshrink-0.1.0/src/pgshrink/cli.py +120 -0
- pgshrink-0.1.0/src/pgshrink/db.py +131 -0
- pgshrink-0.1.0/src/pgshrink/measure.py +144 -0
- pgshrink-0.1.0/src/pgshrink/sql.py +47 -0
- pgshrink-0.1.0/tests/test_measure.py +78 -0
- pgshrink-0.1.0/tests/test_pg.py +72 -0
- pgshrink-0.1.0/uv.lock +552 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main, dev]
|
|
6
|
+
pull_request:
|
|
7
|
+
workflow_dispatch:
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
strategy:
|
|
13
|
+
matrix:
|
|
14
|
+
python: ["3.10", "3.13"]
|
|
15
|
+
services:
|
|
16
|
+
postgres:
|
|
17
|
+
image: pgvector/pgvector:pg17
|
|
18
|
+
env:
|
|
19
|
+
POSTGRES_PASSWORD: pg
|
|
20
|
+
ports: ["5432:5432"]
|
|
21
|
+
options: >-
|
|
22
|
+
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
|
|
23
|
+
env:
|
|
24
|
+
PGSHRINK_TEST_DSN: postgresql://postgres:pg@localhost:5432/postgres
|
|
25
|
+
steps:
|
|
26
|
+
- uses: actions/checkout@v4
|
|
27
|
+
- uses: astral-sh/setup-uv@v6
|
|
28
|
+
with:
|
|
29
|
+
python-version: ${{ matrix.python }}
|
|
30
|
+
- run: uv sync
|
|
31
|
+
- run: uv run ruff check src tests
|
|
32
|
+
- run: uv run pytest -q
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags: ["v*"]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
pypi:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
environment: pypi
|
|
11
|
+
permissions:
|
|
12
|
+
id-token: write # PyPI trusted publishing: no API token stored anywhere
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: astral-sh/setup-uv@v6
|
|
16
|
+
- name: Check the tag matches the package version
|
|
17
|
+
run: test "${GITHUB_REF_NAME#v}" = "$(uv version --short)"
|
|
18
|
+
- run: uv build
|
|
19
|
+
- run: uv publish --trusted-publishing always
|
pgshrink-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
pgshrink-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pgshrink
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Measure how much smaller your pgvector embeddings can get on your own data, and get the SQL to do it.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: numpy>=1.26
|
|
9
|
+
Requires-Dist: pgvector>=0.4
|
|
10
|
+
Requires-Dist: psycopg[binary]>=3.2
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# pgshrink
|
|
14
|
+
|
|
15
|
+
**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.**
|
|
16
|
+
|
|
17
|
+
[](https://github.com/alessandroamormino/pgshrink/actions/workflows/ci.yml)
|
|
18
|
+
[](LICENSE)
|
|
19
|
+

|
|
20
|
+

|
|
21
|
+
|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
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.
|
|
25
|
+
|
|
26
|
+
`pgshrink` reads your vector column and tries every layout pgvector supports. For each one it tells you:
|
|
27
|
+
|
|
28
|
+
- **fidelity**: how often you get the same top-k results as today, with a 95% confidence interval;
|
|
29
|
+
- **index size**: how large the HNSW index would be, from a model fitted on real pgvector indexes;
|
|
30
|
+
- **the SQL**: the index and the query to switch to the smallest layout that keeps your results.
|
|
31
|
+
|
|
32
|
+
It needs no labels and no test queries, and it **never writes to your database**.
|
|
33
|
+
|
|
34
|
+
## Example: 171k documents, 1024-dim embeddings
|
|
35
|
+
|
|
36
|
+
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](docs/validation.md)):
|
|
37
|
+
|
|
38
|
+
| layout | HNSW index | pgshrink fidelity (predicted) | real HNSW fidelity | p50 query |
|
|
39
|
+
|---|---|---|---|---|
|
|
40
|
+
| `vector` (today) | 1338 MB | 100% | 100% | 324 ms\* |
|
|
41
|
+
| `halfvec` | **446 MB** | 100.0% | 98.1% | 2.2 ms |
|
|
42
|
+
| `binary_quantize` + rerank ×10 | **70 MB** | 98.9% | 97.6% | 2.0 ms |
|
|
43
|
+
|
|
44
|
+
\* 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.
|
|
45
|
+
|
|
46
|
+
Two things people usually don't expect:
|
|
47
|
+
- **`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.
|
|
48
|
+
- **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.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install pgshrink # or: uv tool install pgshrink
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
You need Python 3.10+ and network access to your Postgres. Nothing is installed in the database.
|
|
57
|
+
|
|
58
|
+
## Quick start
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pgshrink analyze "postgresql://user@host:5432/db" --table documents --column embedding
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
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`.
|
|
65
|
+
|
|
66
|
+
To get the full report as JSON (for CI, dashboards or scripts):
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pgshrink analyze "$DATABASE_URL" --table documents --column embedding --json > pgshrink.json
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## How it works
|
|
73
|
+
|
|
74
|
+
```mermaid
|
|
75
|
+
flowchart LR
|
|
76
|
+
A[(your table)] -->|"200 random rows<br/>as queries"| Q[queries]
|
|
77
|
+
A -->|"COPY ... BINARY<br/>whole column, streamed"| S[exact search<br/>on current vectors]
|
|
78
|
+
Q --> S
|
|
79
|
+
S --> T[true top-k<br/>per query]
|
|
80
|
+
A --> L["each layout:<br/>halfvec · subvector · binary_quantize<br/>± rerank"]
|
|
81
|
+
Q --> L
|
|
82
|
+
L --> C{same top-k<br/>as today?}
|
|
83
|
+
T --> C
|
|
84
|
+
C --> R[report + SQL]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
1. **Queries.** About 200 random rows from your table serve as queries, and each one is excluded from its own results.
|
|
88
|
+
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.
|
|
89
|
+
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.
|
|
90
|
+
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.
|
|
91
|
+
5. **Recommendation.** It recommends the smallest index whose *lower* CI bound reaches `--target` (default 95%).
|
|
92
|
+
|
|
93
|
+
## Applying the recommendation
|
|
94
|
+
|
|
95
|
+
pgshrink prints the SQL but never runs it. **Try it on a copy or a replica first.**
|
|
96
|
+
|
|
97
|
+
**1. Build the new index next to the old one.** `CONCURRENTLY` doesn't block writes.
|
|
98
|
+
|
|
99
|
+
```sql
|
|
100
|
+
CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_embedding_binary1024_idx
|
|
101
|
+
ON documents USING hnsw ((binary_quantize(embedding)::bit(1024)) bit_hamming_ops);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**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:
|
|
105
|
+
|
|
106
|
+
```sql
|
|
107
|
+
SET hnsw.ef_search = 100; -- must be >= the number of candidates
|
|
108
|
+
SELECT * FROM (
|
|
109
|
+
SELECT * FROM documents
|
|
110
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
111
|
+
LIMIT 100
|
|
112
|
+
) candidates
|
|
113
|
+
ORDER BY embedding <=> $1::vector(1024)
|
|
114
|
+
LIMIT 10;
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
In Python (psycopg 3 + pgvector):
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from pgvector.psycopg import register_vector
|
|
121
|
+
|
|
122
|
+
SEARCH = """
|
|
123
|
+
SELECT id, title FROM (
|
|
124
|
+
SELECT id, title, embedding FROM documents
|
|
125
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize(%(q)s::vector(1024))::bit(1024)
|
|
126
|
+
LIMIT 100
|
|
127
|
+
) c ORDER BY embedding <=> %(q)s::vector(1024) LIMIT 10
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
register_vector(conn)
|
|
131
|
+
with conn.transaction():
|
|
132
|
+
conn.execute("SET LOCAL hnsw.ef_search = 100")
|
|
133
|
+
rows = conn.execute(SEARCH, {"q": query_embedding}).fetchall()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
In Node.js (`pg` + `pgvector`):
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
import pgvector from 'pgvector/pg';
|
|
140
|
+
|
|
141
|
+
const SEARCH = `
|
|
142
|
+
SELECT id, title FROM (
|
|
143
|
+
SELECT id, title, embedding FROM documents
|
|
144
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
145
|
+
LIMIT 100
|
|
146
|
+
) c ORDER BY embedding <=> $1::vector(1024) LIMIT 10`;
|
|
147
|
+
|
|
148
|
+
await client.query('BEGIN');
|
|
149
|
+
await client.query('SET LOCAL hnsw.ef_search = 100');
|
|
150
|
+
const { rows } = await client.query(SEARCH, [pgvector.toSql(queryEmbedding)]);
|
|
151
|
+
await client.query('COMMIT');
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**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.
|
|
155
|
+
|
|
156
|
+
**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.
|
|
157
|
+
|
|
158
|
+
## Options
|
|
159
|
+
|
|
160
|
+
| option | default | meaning |
|
|
161
|
+
|---|---|---|
|
|
162
|
+
| `--table` | required | table name, optionally `schema.table` |
|
|
163
|
+
| `--column` | required | a `vector(n)` column |
|
|
164
|
+
| `--metric` | from the index | `cosine`, `ip` or `l2` |
|
|
165
|
+
| `--k` | 10 | top-k to compare |
|
|
166
|
+
| `--queries` | 200 | random rows used as queries |
|
|
167
|
+
| `--target` | 0.95 | minimum lower 95% bound of fidelity for a recommendation |
|
|
168
|
+
| `--max-rows` | 2,000,000 | rows scanned; above this a random subset is used (reported) |
|
|
169
|
+
| `--seed` | 0 | same seed, same queries and same results |
|
|
170
|
+
| `--json` | off | machine-readable report |
|
|
171
|
+
|
|
172
|
+
## Safety
|
|
173
|
+
|
|
174
|
+
- Every transaction is opened with `default_transaction_read_only = on`, and a test checks that writes fail.
|
|
175
|
+
- It reads the vector column and `ctid`, plus catalog metadata: column type, row estimate, index names and sizes. It reads no other columns.
|
|
176
|
+
- It writes nothing to disk and never logs the connection string.
|
|
177
|
+
- `statement_timeout` defaults to 5 minutes.
|
|
178
|
+
- On a managed database, scanning the column costs one sequential read of it. Run it against a replica if you can.
|
|
179
|
+
|
|
180
|
+
## What it does not tell you
|
|
181
|
+
|
|
182
|
+
- **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.
|
|
183
|
+
- **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.
|
|
184
|
+
- **HNSW adds its own approximation** on top of compression: about −1 to −2 points in our validation. Raise `hnsw.ef_search` if you need it back.
|
|
185
|
+
- **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.
|
|
186
|
+
- **The index size is an estimate** from a page-packing model fitted on real pgvector HNSW indexes (`m = 16`, within 3%). Other `m` values or index types (IVFFlat) are less precise.
|
|
187
|
+
- For now it supports `vector(n)` columns on pgvector 0.7+ (needed for `halfvec` and `binary_quantize`).
|
|
188
|
+
|
|
189
|
+
## Development
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
git clone https://github.com/alessandroamormino/pgshrink && cd pgshrink
|
|
193
|
+
uv sync
|
|
194
|
+
uv run pytest # unit tests
|
|
195
|
+
|
|
196
|
+
docker run -d --name pgshrink-test -e POSTGRES_PASSWORD=pg -p 55432:5432 pgvector/pgvector:pg17
|
|
197
|
+
PGSHRINK_TEST_DSN=postgresql://postgres:pg@localhost:55432/postgres uv run pytest # + integration tests
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
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.
|
|
201
|
+
|
|
202
|
+
Issues and pull requests are welcome, especially reports of how the numbers compare with your production results.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
[Apache-2.0](LICENSE)
|
pgshrink-0.1.0/README.md
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# pgshrink
|
|
2
|
+
|
|
3
|
+
**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.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/alessandroamormino/pgshrink/actions/workflows/ci.yml)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+

|
|
8
|
+

|
|
9
|
+
|
|
10
|
+

|
|
11
|
+
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
`pgshrink` reads your vector column and tries every layout pgvector supports. For each one it tells you:
|
|
15
|
+
|
|
16
|
+
- **fidelity**: how often you get the same top-k results as today, with a 95% confidence interval;
|
|
17
|
+
- **index size**: how large the HNSW index would be, from a model fitted on real pgvector indexes;
|
|
18
|
+
- **the SQL**: the index and the query to switch to the smallest layout that keeps your results.
|
|
19
|
+
|
|
20
|
+
It needs no labels and no test queries, and it **never writes to your database**.
|
|
21
|
+
|
|
22
|
+
## Example: 171k documents, 1024-dim embeddings
|
|
23
|
+
|
|
24
|
+
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](docs/validation.md)):
|
|
25
|
+
|
|
26
|
+
| layout | HNSW index | pgshrink fidelity (predicted) | real HNSW fidelity | p50 query |
|
|
27
|
+
|---|---|---|---|---|
|
|
28
|
+
| `vector` (today) | 1338 MB | 100% | 100% | 324 ms\* |
|
|
29
|
+
| `halfvec` | **446 MB** | 100.0% | 98.1% | 2.2 ms |
|
|
30
|
+
| `binary_quantize` + rerank ×10 | **70 MB** | 98.9% | 97.6% | 2.0 ms |
|
|
31
|
+
|
|
32
|
+
\* 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.
|
|
33
|
+
|
|
34
|
+
Two things people usually don't expect:
|
|
35
|
+
- **`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.
|
|
36
|
+
- **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.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install pgshrink # or: uv tool install pgshrink
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
You need Python 3.10+ and network access to your Postgres. Nothing is installed in the database.
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pgshrink analyze "postgresql://user@host:5432/db" --table documents --column embedding
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
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`.
|
|
53
|
+
|
|
54
|
+
To get the full report as JSON (for CI, dashboards or scripts):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pgshrink analyze "$DATABASE_URL" --table documents --column embedding --json > pgshrink.json
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## How it works
|
|
61
|
+
|
|
62
|
+
```mermaid
|
|
63
|
+
flowchart LR
|
|
64
|
+
A[(your table)] -->|"200 random rows<br/>as queries"| Q[queries]
|
|
65
|
+
A -->|"COPY ... BINARY<br/>whole column, streamed"| S[exact search<br/>on current vectors]
|
|
66
|
+
Q --> S
|
|
67
|
+
S --> T[true top-k<br/>per query]
|
|
68
|
+
A --> L["each layout:<br/>halfvec · subvector · binary_quantize<br/>± rerank"]
|
|
69
|
+
Q --> L
|
|
70
|
+
L --> C{same top-k<br/>as today?}
|
|
71
|
+
T --> C
|
|
72
|
+
C --> R[report + SQL]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
1. **Queries.** About 200 random rows from your table serve as queries, and each one is excluded from its own results.
|
|
76
|
+
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.
|
|
77
|
+
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.
|
|
78
|
+
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.
|
|
79
|
+
5. **Recommendation.** It recommends the smallest index whose *lower* CI bound reaches `--target` (default 95%).
|
|
80
|
+
|
|
81
|
+
## Applying the recommendation
|
|
82
|
+
|
|
83
|
+
pgshrink prints the SQL but never runs it. **Try it on a copy or a replica first.**
|
|
84
|
+
|
|
85
|
+
**1. Build the new index next to the old one.** `CONCURRENTLY` doesn't block writes.
|
|
86
|
+
|
|
87
|
+
```sql
|
|
88
|
+
CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_embedding_binary1024_idx
|
|
89
|
+
ON documents USING hnsw ((binary_quantize(embedding)::bit(1024)) bit_hamming_ops);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**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:
|
|
93
|
+
|
|
94
|
+
```sql
|
|
95
|
+
SET hnsw.ef_search = 100; -- must be >= the number of candidates
|
|
96
|
+
SELECT * FROM (
|
|
97
|
+
SELECT * FROM documents
|
|
98
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
99
|
+
LIMIT 100
|
|
100
|
+
) candidates
|
|
101
|
+
ORDER BY embedding <=> $1::vector(1024)
|
|
102
|
+
LIMIT 10;
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
In Python (psycopg 3 + pgvector):
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from pgvector.psycopg import register_vector
|
|
109
|
+
|
|
110
|
+
SEARCH = """
|
|
111
|
+
SELECT id, title FROM (
|
|
112
|
+
SELECT id, title, embedding FROM documents
|
|
113
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize(%(q)s::vector(1024))::bit(1024)
|
|
114
|
+
LIMIT 100
|
|
115
|
+
) c ORDER BY embedding <=> %(q)s::vector(1024) LIMIT 10
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
register_vector(conn)
|
|
119
|
+
with conn.transaction():
|
|
120
|
+
conn.execute("SET LOCAL hnsw.ef_search = 100")
|
|
121
|
+
rows = conn.execute(SEARCH, {"q": query_embedding}).fetchall()
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
In Node.js (`pg` + `pgvector`):
|
|
125
|
+
|
|
126
|
+
```js
|
|
127
|
+
import pgvector from 'pgvector/pg';
|
|
128
|
+
|
|
129
|
+
const SEARCH = `
|
|
130
|
+
SELECT id, title FROM (
|
|
131
|
+
SELECT id, title, embedding FROM documents
|
|
132
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
133
|
+
LIMIT 100
|
|
134
|
+
) c ORDER BY embedding <=> $1::vector(1024) LIMIT 10`;
|
|
135
|
+
|
|
136
|
+
await client.query('BEGIN');
|
|
137
|
+
await client.query('SET LOCAL hnsw.ef_search = 100');
|
|
138
|
+
const { rows } = await client.query(SEARCH, [pgvector.toSql(queryEmbedding)]);
|
|
139
|
+
await client.query('COMMIT');
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
**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.
|
|
143
|
+
|
|
144
|
+
**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.
|
|
145
|
+
|
|
146
|
+
## Options
|
|
147
|
+
|
|
148
|
+
| option | default | meaning |
|
|
149
|
+
|---|---|---|
|
|
150
|
+
| `--table` | required | table name, optionally `schema.table` |
|
|
151
|
+
| `--column` | required | a `vector(n)` column |
|
|
152
|
+
| `--metric` | from the index | `cosine`, `ip` or `l2` |
|
|
153
|
+
| `--k` | 10 | top-k to compare |
|
|
154
|
+
| `--queries` | 200 | random rows used as queries |
|
|
155
|
+
| `--target` | 0.95 | minimum lower 95% bound of fidelity for a recommendation |
|
|
156
|
+
| `--max-rows` | 2,000,000 | rows scanned; above this a random subset is used (reported) |
|
|
157
|
+
| `--seed` | 0 | same seed, same queries and same results |
|
|
158
|
+
| `--json` | off | machine-readable report |
|
|
159
|
+
|
|
160
|
+
## Safety
|
|
161
|
+
|
|
162
|
+
- Every transaction is opened with `default_transaction_read_only = on`, and a test checks that writes fail.
|
|
163
|
+
- It reads the vector column and `ctid`, plus catalog metadata: column type, row estimate, index names and sizes. It reads no other columns.
|
|
164
|
+
- It writes nothing to disk and never logs the connection string.
|
|
165
|
+
- `statement_timeout` defaults to 5 minutes.
|
|
166
|
+
- On a managed database, scanning the column costs one sequential read of it. Run it against a replica if you can.
|
|
167
|
+
|
|
168
|
+
## What it does not tell you
|
|
169
|
+
|
|
170
|
+
- **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.
|
|
171
|
+
- **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.
|
|
172
|
+
- **HNSW adds its own approximation** on top of compression: about −1 to −2 points in our validation. Raise `hnsw.ef_search` if you need it back.
|
|
173
|
+
- **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.
|
|
174
|
+
- **The index size is an estimate** from a page-packing model fitted on real pgvector HNSW indexes (`m = 16`, within 3%). Other `m` values or index types (IVFFlat) are less precise.
|
|
175
|
+
- For now it supports `vector(n)` columns on pgvector 0.7+ (needed for `halfvec` and `binary_quantize`).
|
|
176
|
+
|
|
177
|
+
## Development
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
git clone https://github.com/alessandroamormino/pgshrink && cd pgshrink
|
|
181
|
+
uv sync
|
|
182
|
+
uv run pytest # unit tests
|
|
183
|
+
|
|
184
|
+
docker run -d --name pgshrink-test -e POSTGRES_PASSWORD=pg -p 55432:5432 pgvector/pgvector:pg17
|
|
185
|
+
PGSHRINK_TEST_DSN=postgresql://postgres:pg@localhost:55432/postgres uv run pytest # + integration tests
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
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.
|
|
189
|
+
|
|
190
|
+
Issues and pull requests are welcome, especially reports of how the numbers compare with your production results.
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
[Apache-2.0](LICENSE)
|
|
Binary file
|