mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
81 Commits
hnsw-read-
...
ivfflat-qu
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c599017441 | ||
|
|
f341cea329 | ||
|
|
73356ecfa7 | ||
|
|
0e557b1d18 | ||
|
|
769a60884c | ||
|
|
8711840058 | ||
|
|
159b79aaad | ||
|
|
c5a277a975 | ||
|
|
124f6c61a4 | ||
|
|
5ca52d12b6 | ||
|
|
1f61d1111b | ||
|
|
fb1b8966eb | ||
|
|
71ce9d3311 | ||
|
|
d19cc0d371 | ||
|
|
89fda3e100 | ||
|
|
30d8654b47 | ||
|
|
a846385cc7 | ||
|
|
98d7c4124e | ||
|
|
2a2b4a0b58 | ||
|
|
f15a50387f | ||
|
|
971b7d7fd6 | ||
|
|
f51d8ed989 | ||
|
|
a76a18d526 | ||
|
|
b383e4d191 | ||
|
|
1d458ad5d7 | ||
|
|
9fa17c10b8 | ||
|
|
14149b19f5 | ||
|
|
34d796fbab | ||
|
|
53341bb6c7 | ||
|
|
0d9720f440 | ||
|
|
cb246cb72d | ||
|
|
d053de2d94 | ||
|
|
83bac90869 | ||
|
|
4eca5024df | ||
|
|
a31771bc45 | ||
|
|
ecddde963a | ||
|
|
ecd413d0fe | ||
|
|
497db7976c | ||
|
|
f1dd4e3b03 | ||
|
|
7d067d7b83 | ||
|
|
d4dd73d970 | ||
|
|
ffe28bb954 | ||
|
|
0dbc1a27c0 | ||
|
|
08c4e7ff10 | ||
|
|
6731c49811 | ||
|
|
f2617f02d1 | ||
|
|
bdf19077db | ||
|
|
90cd2b4ee5 | ||
|
|
b44d1b4c5f | ||
|
|
cc5b865c33 | ||
|
|
4895021088 | ||
|
|
eda77b3492 | ||
|
|
a2364b1793 | ||
|
|
a0eaf70d17 | ||
|
|
586e7515ba | ||
|
|
a619d0b34d | ||
|
|
ad222abf48 | ||
|
|
8a81a3fe3a | ||
|
|
fc804925a4 | ||
|
|
98dc4aa6d0 | ||
|
|
7b72aeeff3 | ||
|
|
4682d51e5d | ||
|
|
91fe2e62e7 | ||
|
|
eedba7ee14 | ||
|
|
32284ba28a | ||
|
|
1f68c73c96 | ||
|
|
f15bc0904f | ||
|
|
2b7ad083dc | ||
|
|
421a35fcdc | ||
|
|
12368bd79c | ||
|
|
88a0085459 | ||
|
|
ea23884efd | ||
|
|
3351f3d43e | ||
|
|
d238409bec | ||
|
|
529f37175b | ||
|
|
bce3946392 | ||
|
|
13cb253d30 | ||
|
|
41b3cdc011 | ||
|
|
ec02a96239 | ||
|
|
610d95b8d2 | ||
|
|
609d01f4c6 |
16
.github/workflows/build.yml
vendored
16
.github/workflows/build.yml
vendored
@@ -8,10 +8,12 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
|
- postgres: 20
|
||||||
|
os: ubuntu-26.04
|
||||||
- postgres: 19
|
- postgres: 19
|
||||||
os: ubuntu-24.04
|
os: ubuntu-26.04
|
||||||
- postgres: 18
|
- postgres: 18
|
||||||
os: ubuntu-24.04
|
os: ubuntu-26.04-arm
|
||||||
- postgres: 17
|
- postgres: 17
|
||||||
os: ubuntu-24.04
|
os: ubuntu-24.04
|
||||||
- postgres: 16
|
- postgres: 16
|
||||||
@@ -23,7 +25,7 @@ jobs:
|
|||||||
- postgres: 13
|
- postgres: 13
|
||||||
os: ubuntu-22.04
|
os: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v7
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: ${{ matrix.postgres }}
|
postgres-version: ${{ matrix.postgres }}
|
||||||
@@ -53,7 +55,7 @@ jobs:
|
|||||||
- postgres: 14
|
- postgres: 14
|
||||||
os: macos-15-intel
|
os: macos-15-intel
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v7
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: ${{ matrix.postgres }}
|
postgres-version: ${{ matrix.postgres }}
|
||||||
@@ -92,12 +94,12 @@ jobs:
|
|||||||
- postgres: 14
|
- postgres: 14
|
||||||
os: windows-2022
|
os: windows-2022
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v7
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: ${{ matrix.postgres }}
|
postgres-version: ${{ matrix.postgres }}
|
||||||
- run: |
|
- run: |
|
||||||
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
|
call "C:\Program Files\Microsoft Visual Studio\${{ matrix.os == 'windows-2025' && 18 || 2022 }}\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
|
||||||
nmake /NOLOGO /F Makefile.win && ^
|
nmake /NOLOGO /F Makefile.win && ^
|
||||||
nmake /NOLOGO /F Makefile.win install && ^
|
nmake /NOLOGO /F Makefile.win install && ^
|
||||||
nmake /NOLOGO /F Makefile.win installcheck ${{ matrix.postgres != 17 && 'PG_REGRESS=$(PGROOT)\bin\pg_regress' || '' }} && ^
|
nmake /NOLOGO /F Makefile.win installcheck ${{ matrix.postgres != 17 && 'PG_REGRESS=$(PGROOT)\bin\pg_regress' || '' }} && ^
|
||||||
@@ -133,7 +135,7 @@ jobs:
|
|||||||
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
|
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v7
|
||||||
- uses: ankane/setup-postgres-valgrind@v1
|
- uses: ankane/setup-postgres-valgrind@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: 18
|
postgres-version: 18
|
||||||
|
|||||||
15
CHANGELOG.md
15
CHANGELOG.md
@@ -1,3 +1,18 @@
|
|||||||
|
## 0.8.5 (2026-07-08)
|
||||||
|
|
||||||
|
- Reduced memory usage for small tables for IVFFlat index builds
|
||||||
|
|
||||||
|
## 0.8.4 (2026-06-30)
|
||||||
|
|
||||||
|
- Fixed `hnsw graph not repaired` error with HNSW vacuuming
|
||||||
|
- Fixed possible error with inserts during HNSW vacuuming
|
||||||
|
- Fixed memory exceeding `maintenance_work_mem` with IVFFlat index builds
|
||||||
|
|
||||||
|
## 0.8.3 (2026-06-17)
|
||||||
|
|
||||||
|
- Fixed possible index corruption with HNSW vacuuming
|
||||||
|
- Fixed performance regression with Hamming distance and Jaccard distance with Postgres 18
|
||||||
|
|
||||||
## 0.8.2 (2026-02-25)
|
## 0.8.2 (2026-02-25)
|
||||||
|
|
||||||
- Fixed buffer overflow with parallel HNSW index build - [more info](https://github.com/pgvector/pgvector/issues/959)
|
- Fixed buffer overflow with parallel HNSW index build - [more info](https://github.com/pgvector/pgvector/issues/959)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ ARG DEBIAN_CODENAME=bookworm
|
|||||||
FROM postgres:$PG_MAJOR-$DEBIAN_CODENAME
|
FROM postgres:$PG_MAJOR-$DEBIAN_CODENAME
|
||||||
ARG PG_MAJOR
|
ARG PG_MAJOR
|
||||||
|
|
||||||
ADD https://github.com/pgvector/pgvector.git#v0.8.2 /tmp/pgvector
|
ADD https://github.com/pgvector/pgvector.git#v0.8.5 /tmp/pgvector
|
||||||
|
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-mark hold locales && \
|
apt-mark hold locales && \
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
"name": "vector",
|
"name": "vector",
|
||||||
"abstract": "Open-source vector similarity search for Postgres",
|
"abstract": "Open-source vector similarity search for Postgres",
|
||||||
"description": "Supports L2 distance, inner product, and cosine distance",
|
"description": "Supports L2 distance, inner product, and cosine distance",
|
||||||
"version": "0.8.2",
|
"version": "0.8.5",
|
||||||
"maintainer": [
|
"maintainer": [
|
||||||
"Andrew Kane <andrew@ankane.org>"
|
"Andrew Kane <andrew@ankane.org>"
|
||||||
],
|
],
|
||||||
"license": {
|
"license": {
|
||||||
"PostgreSQL": "http://www.postgresql.org/about/licence"
|
"PostgreSQL": "https://www.postgresql.org/about/licence"
|
||||||
},
|
},
|
||||||
"prereqs": {
|
"prereqs": {
|
||||||
"runtime": {
|
"runtime": {
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"vector": {
|
"vector": {
|
||||||
"file": "sql/vector.sql",
|
"file": "sql/vector.sql",
|
||||||
"docfile": "README.md",
|
"docfile": "README.md",
|
||||||
"version": "0.8.2",
|
"version": "0.8.5",
|
||||||
"abstract": "Open-source vector similarity search for Postgres"
|
"abstract": "Open-source vector similarity search for Postgres"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -38,7 +38,7 @@
|
|||||||
"generated_by": "Andrew Kane",
|
"generated_by": "Andrew Kane",
|
||||||
"meta-spec": {
|
"meta-spec": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"url": "http://pgxn.org/meta/spec.txt"
|
"url": "https://pgxn.org/meta/spec.txt"
|
||||||
},
|
},
|
||||||
"tags": [
|
"tags": [
|
||||||
"vectors",
|
"vectors",
|
||||||
|
|||||||
2
Makefile
2
Makefile
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.8.2
|
EXTVERSION = 0.8.5
|
||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*--*.sql)
|
DATA = $(wildcard sql/*--*--*.sql)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.8.2
|
EXTVERSION = 0.8.5
|
||||||
|
|
||||||
DATA_built = sql\$(EXTENSION)--$(EXTVERSION).sql
|
DATA_built = sql\$(EXTENSION)--$(EXTVERSION).sql
|
||||||
OBJS = src\bitutils.obj src\bitvec.obj src\halfutils.obj src\halfvec.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\sparsevec.obj src\vector.obj
|
OBJS = src\bitutils.obj src\bitvec.obj src\halfutils.obj src\halfvec.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\sparsevec.obj src\vector.obj
|
||||||
|
|||||||
97
README.md
97
README.md
@@ -11,6 +11,8 @@ Store your vectors with the rest of your data. Supports:
|
|||||||
|
|
||||||
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
||||||
|
|
||||||
|
Have a lot of vectors? Use [quantization](#scaling) to scale
|
||||||
|
|
||||||
[](https://github.com/pgvector/pgvector/actions)
|
[](https://github.com/pgvector/pgvector/actions)
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
@@ -21,7 +23,7 @@ Compile and install the extension (supports Postgres 13+)
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.8.5 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
make
|
make
|
||||||
make install # may need sudo
|
make install # may need sudo
|
||||||
@@ -38,7 +40,7 @@ Ensure [C++ support in Visual Studio](https://learn.microsoft.com/en-us/cpp/buil
|
|||||||
```cmd
|
```cmd
|
||||||
set "PGROOT=C:\Program Files\PostgreSQL\18"
|
set "PGROOT=C:\Program Files\PostgreSQL\18"
|
||||||
cd %TEMP%
|
cd %TEMP%
|
||||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.8.5 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
nmake /F Makefile.win
|
nmake /F Makefile.win
|
||||||
nmake /F Makefile.win install
|
nmake /F Makefile.win install
|
||||||
@@ -314,6 +316,8 @@ For a large number of workers, you may need to increase `max_parallel_workers` (
|
|||||||
|
|
||||||
The [index options](#index-options) also have a significant impact on build time (use the defaults unless seeing low recall)
|
The [index options](#index-options) also have a significant impact on build time (use the defaults unless seeing low recall)
|
||||||
|
|
||||||
|
Use [binary quantization](#binary-quantization) for faster build times at scale
|
||||||
|
|
||||||
### Indexing Progress
|
### Indexing Progress
|
||||||
|
|
||||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING)
|
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING)
|
||||||
@@ -443,13 +447,7 @@ Exact indexes work well for conditions that match a low percentage of rows. Othe
|
|||||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);
|
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);
|
||||||
```
|
```
|
||||||
|
|
||||||
With approximate indexes, filtering is applied *after* the index is scanned. If a condition matches 10% of rows, with HNSW and the default `hnsw.ef_search` of 40, only 4 rows will match on average. For more rows, increase `hnsw.ef_search`.
|
With approximate indexes, filtering is applied *after* the index is scanned. If a condition matches 10% of rows, with HNSW and the default `hnsw.ef_search` of 40, only 4 rows will match on average. For more rows, enable [iterative index scans](#iterative-index-scans), which will automatically scan more of the index when needed.
|
||||||
|
|
||||||
```sql
|
|
||||||
SET hnsw.ef_search = 200;
|
|
||||||
```
|
|
||||||
|
|
||||||
Starting with 0.8.0, you can enable [iterative index scans](#iterative-index-scans), which will automatically scan more of the index when needed.
|
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
SET hnsw.iterative_scan = strict_order;
|
SET hnsw.iterative_scan = strict_order;
|
||||||
@@ -467,6 +465,16 @@ If filtering by many different values, consider [partitioning](https://www.postg
|
|||||||
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
|
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Multitenancy
|
||||||
|
|
||||||
|
For applications with multiple tenants, sharing an approximate index between tenants means vectors from one tenant can affect recall (and speed) for other tenants.
|
||||||
|
|
||||||
|
For tenant isolation, use [list partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) or separate tables.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE items (customer_id int, embedding vector(3)) PARTITION BY LIST(customer_id);
|
||||||
|
```
|
||||||
|
|
||||||
## Iterative Index Scans
|
## Iterative Index Scans
|
||||||
|
|
||||||
With approximate indexes, queries with filtering can return less results since filtering is applied *after* the index is scanned. Starting with 0.8.0, you can enable iterative index scans, which will automatically scan more of the index until enough results are found (or it reaches `hnsw.max_scan_tuples` or `ivfflat.max_probes`).
|
With approximate indexes, queries with filtering can return less results since filtering is applied *after* the index is scanned. Starting with 0.8.0, you can enable iterative index scans, which will automatically scan more of the index until enough results are found (or it reaches `hnsw.max_scan_tuples` or `ivfflat.max_probes`).
|
||||||
@@ -673,6 +681,10 @@ SHOW shared_buffers;
|
|||||||
|
|
||||||
Be sure to restart Postgres for changes to take effect.
|
Be sure to restart Postgres for changes to take effect.
|
||||||
|
|
||||||
|
### Storing
|
||||||
|
|
||||||
|
Use the `halfvec` type instead of `vector` for a smaller working set.
|
||||||
|
|
||||||
### Loading
|
### Loading
|
||||||
|
|
||||||
Use `COPY` for bulk loading data ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/loading/example.py)).
|
Use `COPY` for bulk loading data ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/loading/example.py)).
|
||||||
@@ -687,6 +699,8 @@ Add any indexes *after* loading the initial data for best performance.
|
|||||||
|
|
||||||
See index build time for [HNSW](#index-build-time) and [IVFFlat](#index-build-time-1).
|
See index build time for [HNSW](#index-build-time) and [IVFFlat](#index-build-time-1).
|
||||||
|
|
||||||
|
Use [binary quantization](#binary-quantization) for smaller indexes and faster build times at scale.
|
||||||
|
|
||||||
In production environments, create indexes concurrently to avoid blocking writes.
|
In production environments, create indexes concurrently to avoid blocking writes.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -717,6 +731,8 @@ SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
|
|||||||
|
|
||||||
#### Approximate Search
|
#### Approximate Search
|
||||||
|
|
||||||
|
Use [binary quantization](#binary-quantization) with re-ranking to keep indexes in-memory at scale.
|
||||||
|
|
||||||
To speed up queries with an IVFFlat index, increase the number of inverted lists (at the expense of recall).
|
To speed up queries with an IVFFlat index, increase the number of inverted lists (at the expense of recall).
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -732,21 +748,20 @@ REINDEX INDEX CONCURRENTLY index_name;
|
|||||||
VACUUM table_name;
|
VACUUM table_name;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Scaling
|
||||||
|
|
||||||
|
For a smaller working set:
|
||||||
|
|
||||||
|
1. Use the `halfvec` type instead of `vector` for tables
|
||||||
|
2. Use [binary quantization](#binary-quantization) for indexes (with re-ranking for search)
|
||||||
|
|
||||||
|
Scale vertically by increasing memory, CPU, and storage on a single instance. Use existing tools to [tune parameters](#tuning) and [monitor performance](#monitoring).
|
||||||
|
|
||||||
|
Scale horizontally with [replicas](https://www.postgresql.org/docs/current/hot-standby.html), or use [Citus](https://github.com/citusdata/citus), [PgDog](https://github.com/pgdogdev/pgdog), or another approach for sharding ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/citus/example.py)).
|
||||||
|
|
||||||
## Monitoring
|
## Monitoring
|
||||||
|
|
||||||
Monitor performance with [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) (be sure to add it to `shared_preload_libraries`).
|
Use existing tools like [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) or [PgHero](https://github.com/ankane/pghero) to monitor performance.
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE EXTENSION pg_stat_statements;
|
|
||||||
```
|
|
||||||
|
|
||||||
Get the most time-consuming queries with:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT query, calls, ROUND((total_plan_time + total_exec_time) / calls) AS avg_time_ms,
|
|
||||||
ROUND((total_plan_time + total_exec_time) / 60000) AS total_time_min
|
|
||||||
FROM pg_stat_statements ORDER BY total_plan_time + total_exec_time DESC LIMIT 20;
|
|
||||||
```
|
|
||||||
|
|
||||||
Monitor recall by comparing results from approximate search with exact search.
|
Monitor recall by comparing results from approximate search with exact search.
|
||||||
|
|
||||||
@@ -757,14 +772,6 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Scaling
|
|
||||||
|
|
||||||
Scale pgvector the same way you scale Postgres.
|
|
||||||
|
|
||||||
Scale vertically by increasing memory, CPU, and storage on a single instance. Use existing tools to [tune parameters](#tuning) and [monitor performance](#monitoring).
|
|
||||||
|
|
||||||
Scale horizontally with [replicas](https://www.postgresql.org/docs/current/hot-standby.html), or use [Citus](https://github.com/citusdata/citus) or another approach for sharding ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/citus/example.py)).
|
|
||||||
|
|
||||||
## Languages
|
## Languages
|
||||||
|
|
||||||
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
|
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
|
||||||
@@ -878,6 +885,8 @@ No, but like other index types, you’ll likely see better performance if they d
|
|||||||
SELECT pg_size_pretty(pg_relation_size('index_name'));
|
SELECT pg_size_pretty(pg_relation_size('index_name'));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Use [half-precision indexing](#half-precision-indexing) or [binary quantization](#binary-quantization) for smaller indexes.
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
#### Why isn’t a query using an index?
|
#### Why isn’t a query using an index?
|
||||||
@@ -1152,23 +1161,23 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
|||||||
|
|
||||||
Supported tags are:
|
Supported tags are:
|
||||||
|
|
||||||
- `pg18-trixie`, `0.8.2-pg18-trixie`
|
- `pg18-trixie`, `0.8.5-pg18-trixie`
|
||||||
- `pg18-bookworm`, `0.8.2-pg18-bookworm`, `pg18`, `0.8.2-pg18`
|
- `pg18-bookworm`, `0.8.5-pg18-bookworm`, `pg18`, `0.8.5-pg18`
|
||||||
- `pg17-trixie`, `0.8.2-pg17-trixie`
|
- `pg17-trixie`, `0.8.5-pg17-trixie`
|
||||||
- `pg17-bookworm`, `0.8.2-pg17-bookworm`, `pg17`, `0.8.2-pg17`
|
- `pg17-bookworm`, `0.8.5-pg17-bookworm`, `pg17`, `0.8.5-pg17`
|
||||||
- `pg16-trixie`, `0.8.2-pg16-trixie`
|
- `pg16-trixie`, `0.8.5-pg16-trixie`
|
||||||
- `pg16-bookworm`, `0.8.2-pg16-bookworm`, `pg16`, `0.8.2-pg16`
|
- `pg16-bookworm`, `0.8.5-pg16-bookworm`, `pg16`, `0.8.5-pg16`
|
||||||
- `pg15-trixie`, `0.8.2-pg15-trixie`
|
- `pg15-trixie`, `0.8.5-pg15-trixie`
|
||||||
- `pg15-bookworm`, `0.8.2-pg15-bookworm`, `pg15`, `0.8.2-pg15`
|
- `pg15-bookworm`, `0.8.5-pg15-bookworm`, `pg15`, `0.8.5-pg15`
|
||||||
- `pg14-trixie`, `0.8.2-pg14-trixie`
|
- `pg14-trixie`, `0.8.5-pg14-trixie`
|
||||||
- `pg14-bookworm`, `0.8.2-pg14-bookworm`, `pg14`, `0.8.2-pg14`
|
- `pg14-bookworm`, `0.8.5-pg14-bookworm`, `pg14`, `0.8.5-pg14`
|
||||||
- `pg13-trixie`, `0.8.2-pg13-trixie`
|
- `pg13-trixie`, `0.8.5-pg13-trixie`
|
||||||
- `pg13-bookworm`, `0.8.2-pg13-bookworm`, `pg13`, `0.8.2-pg13`
|
- `pg13-bookworm`, `0.8.5-pg13-bookworm`, `pg13`, `0.8.5-pg13`
|
||||||
|
|
||||||
You can also build the image manually:
|
You can also build the image manually:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.8.5 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
docker build --pull --build-arg PG_MAJOR=18 -t myuser/pgvector .
|
docker build --pull --build-arg PG_MAJOR=18 -t myuser/pgvector .
|
||||||
```
|
```
|
||||||
@@ -1330,7 +1339,7 @@ make clean && PG_CFLAGS="-DUSE_ASSERT_CHECKING" make && make install
|
|||||||
To enable benchmarking:
|
To enable benchmarking:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make clean && PG_CFLAGS="-DIVFFLAT_BENCH" make && make install
|
make clean && PG_CFLAGS="-DHNSW_BENCH -DIVFFLAT_BENCH" make && make install
|
||||||
```
|
```
|
||||||
|
|
||||||
To show memory usage:
|
To show memory usage:
|
||||||
|
|||||||
2
sql/vector--0.8.2--0.8.3.sql
Normal file
2
sql/vector--0.8.2--0.8.3.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.8.3'" to load this file. \quit
|
||||||
2
sql/vector--0.8.3--0.8.4.sql
Normal file
2
sql/vector--0.8.3--0.8.4.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.8.4'" to load this file. \quit
|
||||||
2
sql/vector--0.8.4--0.8.5.sql
Normal file
2
sql/vector--0.8.4--0.8.5.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.8.5'" to load this file. \quit
|
||||||
@@ -31,10 +31,12 @@
|
|||||||
#define BIT_TARGET_CLONES
|
#define BIT_TARGET_CLONES
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/* Use built-ins when possible for inlining */
|
/* Use built-ins when possible for Postgres < 19 for inlining */
|
||||||
#if defined(HAVE__BUILTIN_POPCOUNT) && defined(HAVE_LONG_INT_64)
|
#if PG_VERSION_NUM >= 190000
|
||||||
|
#define popcount64(x) pg_popcount64(x)
|
||||||
|
#elif defined(HAVE__BUILTIN_POPCOUNT) && (defined(HAVE_LONG_INT_64) || SIZEOF_LONG == 8)
|
||||||
#define popcount64(x) __builtin_popcountl(x)
|
#define popcount64(x) __builtin_popcountl(x)
|
||||||
#elif defined(HAVE__BUILTIN_POPCOUNT) && defined(HAVE_LONG_LONG_INT_64)
|
#elif defined(HAVE__BUILTIN_POPCOUNT) && (defined(HAVE_LONG_LONG_INT_64) || SIZEOF_LONG_LONG == 8)
|
||||||
#define popcount64(x) __builtin_popcountll(x)
|
#define popcount64(x) __builtin_popcountll(x)
|
||||||
#elif !defined(_MSC_VER)
|
#elif !defined(_MSC_VER)
|
||||||
/* Fails to resolve with MSVC */
|
/* Fails to resolve with MSVC */
|
||||||
|
|||||||
33
src/hnsw.h
33
src/hnsw.h
@@ -18,6 +18,10 @@
|
|||||||
#include "utils/sampling.h"
|
#include "utils/sampling.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
|
#ifdef HNSW_BENCH
|
||||||
|
#include "portability/instr_time.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
#if PG_VERSION_NUM >= 190000
|
||||||
typedef Pointer Item;
|
typedef Pointer Item;
|
||||||
#endif
|
#endif
|
||||||
@@ -78,6 +82,21 @@ typedef Pointer Item;
|
|||||||
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
||||||
#define HnswPageGetMeta(page) ((HnswMetaPageData *) PageGetContents(page))
|
#define HnswPageGetMeta(page) ((HnswMetaPageData *) PageGetContents(page))
|
||||||
|
|
||||||
|
#ifdef HNSW_BENCH
|
||||||
|
#define HnswBench(name, code) \
|
||||||
|
do { \
|
||||||
|
instr_time start; \
|
||||||
|
instr_time duration; \
|
||||||
|
INSTR_TIME_SET_CURRENT(start); \
|
||||||
|
(code); \
|
||||||
|
INSTR_TIME_SET_CURRENT(duration); \
|
||||||
|
INSTR_TIME_SUBTRACT(duration, start); \
|
||||||
|
elog(INFO, "%s: %.3f ms", name, INSTR_TIME_GET_MILLISEC(duration)); \
|
||||||
|
} while (0)
|
||||||
|
#else
|
||||||
|
#define HnswBench(name, code) (code)
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 150000
|
#if PG_VERSION_NUM >= 150000
|
||||||
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
|
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
|
||||||
#define SeedRandom(seed) pg_prng_seed(&pg_global_prng_state, seed)
|
#define SeedRandom(seed) pg_prng_seed(&pg_global_prng_state, seed)
|
||||||
@@ -372,13 +391,6 @@ typedef union
|
|||||||
ItemPointerData indextid;
|
ItemPointerData indextid;
|
||||||
} HnswUnvisited;
|
} HnswUnvisited;
|
||||||
|
|
||||||
typedef struct HnswReadStreamData
|
|
||||||
{
|
|
||||||
HnswUnvisited *unvisited;
|
|
||||||
int unvisitedLength;
|
|
||||||
int visited;
|
|
||||||
} HnswReadStreamData;
|
|
||||||
|
|
||||||
typedef struct HnswScanOpaqueData
|
typedef struct HnswScanOpaqueData
|
||||||
{
|
{
|
||||||
const HnswTypeInfo *typeInfo;
|
const HnswTypeInfo *typeInfo;
|
||||||
@@ -415,10 +427,11 @@ typedef struct HnswVacuumState
|
|||||||
HnswSupport support;
|
HnswSupport support;
|
||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
struct tidhash_hash *deleted;
|
struct tidhash_hash *deleting;
|
||||||
BufferAccessStrategy bas;
|
BufferAccessStrategy bas;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
HnswElementData highestPoint;
|
HnswElementData highestPoint;
|
||||||
|
HnswElementData fallbackPoint;
|
||||||
|
|
||||||
/* Memory */
|
/* Memory */
|
||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
@@ -434,13 +447,13 @@ bool HnswCheckNorm(HnswSupport * support, Datum value);
|
|||||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||||
void HnswInitPage(Buffer buf, Page page);
|
void HnswInitPage(Buffer buf, Page page);
|
||||||
void HnswInit(void);
|
void HnswInit(void);
|
||||||
List *HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples, bool maintenance);
|
List *HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples);
|
||||||
HnswElement HnswGetEntryPoint(Relation index);
|
HnswElement HnswGetEntryPoint(Relation index);
|
||||||
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
||||||
void *HnswAlloc(HnswAllocator * allocator, Size size);
|
void *HnswAlloc(HnswAllocator * allocator, Size size);
|
||||||
HnswElement HnswInitElement(char *base, ItemPointer tid, int m, double ml, int maxLevel, HnswAllocator * alloc);
|
HnswElement HnswInitElement(char *base, ItemPointer tid, int m, double ml, int maxLevel, HnswAllocator * alloc);
|
||||||
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
||||||
void HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool maintenance);
|
void HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing);
|
||||||
HnswSearchCandidate *HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec);
|
HnswSearchCandidate *HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec);
|
||||||
void HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum, bool building);
|
void HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum, bool building);
|
||||||
void HnswSetNeighborTuple(char *base, HnswNeighborTuple ntup, HnswElement e, int m);
|
void HnswSetNeighborTuple(char *base, HnswNeighborTuple ntup, HnswElement e, int m);
|
||||||
|
|||||||
@@ -470,7 +470,7 @@ InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find neighbors for element */
|
/* Find neighbors for element */
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, NULL, support, m, efConstruction, false, true);
|
HnswFindElementNeighbors(base, element, entryPoint, NULL, support, m, efConstruction, false);
|
||||||
|
|
||||||
/* Update graph in memory */
|
/* Update graph in memory */
|
||||||
UpdateGraphInMemory(support, element, m, entryPoint, buildstate);
|
UpdateGraphInMemory(support, element, m, entryPoint, buildstate);
|
||||||
@@ -719,7 +719,7 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
/* Get support functions */
|
/* Get support functions */
|
||||||
HnswInitSupport(&buildstate->support, index);
|
HnswInitSupport(&buildstate->support, index);
|
||||||
|
|
||||||
InitGraph(&buildstate->graphData, NULL, (Size) maintenance_work_mem * 1024L);
|
InitGraph(&buildstate->graphData, NULL, maintenance_work_mem * (Size) 1024);
|
||||||
buildstate->graph = &buildstate->graphData;
|
buildstate->graph = &buildstate->graphData;
|
||||||
buildstate->ml = HnswGetMl(buildstate->m);
|
buildstate->ml = HnswGetMl(buildstate->m);
|
||||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||||
@@ -956,7 +956,7 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
/* Leave space for other objects in shared memory */
|
/* Leave space for other objects in shared memory */
|
||||||
/* Docker has a default limit of 64 MB for shm_size */
|
/* Docker has a default limit of 64 MB for shm_size */
|
||||||
/* which happens to be the default value of maintenance_work_mem */
|
/* which happens to be the default value of maintenance_work_mem */
|
||||||
esthnswarea = maintenance_work_mem * 1024L;
|
esthnswarea = maintenance_work_mem * (Size) 1024;
|
||||||
estother = 3 * 1024 * 1024;
|
estother = 3 * 1024 * 1024;
|
||||||
if (esthnswarea > estother)
|
if (esthnswarea > estother)
|
||||||
esthnswarea -= estother;
|
esthnswarea -= estother;
|
||||||
|
|||||||
@@ -731,7 +731,7 @@ HnswInsertTupleOnDisk(Relation index, HnswSupport * support, Datum value, ItemPo
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find neighbors for element */
|
/* Find neighbors for element */
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, false, building);
|
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, false);
|
||||||
|
|
||||||
/* Update graph on disk */
|
/* Update graph on disk */
|
||||||
UpdateGraphOnDisk(index, support, element, m, entryPoint, building);
|
UpdateGraphOnDisk(index, support, element, m, entryPoint, building);
|
||||||
|
|||||||
@@ -48,11 +48,11 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
|
|
||||||
for (int lc = entryPoint->level; lc >= 1; lc--)
|
for (int lc = entryPoint->level; lc >= 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(base, q, ep, 1, lc, index, support, m, false, NULL, NULL, NULL, true, NULL, false);
|
w = HnswSearchLayer(base, q, ep, 1, lc, index, support, m, false, NULL, NULL, NULL, true, NULL);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, support, m, false, NULL, &so->v, hnsw_iterative_scan != HNSW_ITERATIVE_SCAN_OFF ? &so->discarded : NULL, true, &so->tuples, false);
|
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, support, m, false, NULL, &so->v, hnsw_iterative_scan != HNSW_ITERATIVE_SCAN_OFF ? &so->discarded : NULL, true, &so->tuples);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -83,7 +83,7 @@ ResumeScanItems(IndexScanDesc scan)
|
|||||||
ep = lappend(ep, sc);
|
ep = lappend(ep, sc);
|
||||||
}
|
}
|
||||||
|
|
||||||
return HnswSearchLayer(base, &so->q, ep, batch_size, 0, index, &so->support, so->m, false, NULL, &so->v, &so->discarded, false, &so->tuples, false);
|
return HnswSearchLayer(base, &so->q, ep, batch_size, 0, index, &so->support, so->m, false, NULL, &so->v, &so->discarded, false, &so->tuples);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
107
src/hnswutils.c
107
src/hnswutils.c
@@ -21,10 +21,6 @@
|
|||||||
#include "varatt.h"
|
#include "varatt.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
#include "storage/read_stream.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 170000
|
#if PG_VERSION_NUM < 170000
|
||||||
static inline uint64
|
static inline uint64
|
||||||
murmurhash64(uint64 data)
|
murmurhash64(uint64 data)
|
||||||
@@ -535,12 +531,14 @@ HnswGetDistance(Datum a, Datum b, HnswSupport * support)
|
|||||||
* Load an element and optionally get its distance from q
|
* Load an element and optionally get its distance from q
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswLoadElementImpl(Buffer buf, OffsetNumber offno, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance, HnswElement * element)
|
HnswLoadElementImpl(BlockNumber blkno, OffsetNumber offno, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance, HnswElement * element)
|
||||||
{
|
{
|
||||||
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
|
|
||||||
/* Read vector */
|
/* Read vector */
|
||||||
|
buf = ReadBuffer(index, blkno);
|
||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
page = BufferGetPage(buf);
|
page = BufferGetPage(buf);
|
||||||
|
|
||||||
@@ -548,6 +546,9 @@ HnswLoadElementImpl(Buffer buf, OffsetNumber offno, double *distance, HnswQuery
|
|||||||
|
|
||||||
Assert(HnswIsElementTuple(etup));
|
Assert(HnswIsElementTuple(etup));
|
||||||
|
|
||||||
|
if (unlikely(etup->deleted))
|
||||||
|
elog(ERROR, "cannot load deleted element");
|
||||||
|
|
||||||
/* Calculate distance */
|
/* Calculate distance */
|
||||||
if (distance != NULL)
|
if (distance != NULL)
|
||||||
{
|
{
|
||||||
@@ -561,7 +562,7 @@ HnswLoadElementImpl(Buffer buf, OffsetNumber offno, double *distance, HnswQuery
|
|||||||
if (distance == NULL || maxDistance == NULL || *distance < *maxDistance)
|
if (distance == NULL || maxDistance == NULL || *distance < *maxDistance)
|
||||||
{
|
{
|
||||||
if (*element == NULL)
|
if (*element == NULL)
|
||||||
*element = HnswInitElementFromBlock(BufferGetBlockNumber(buf), offno);
|
*element = HnswInitElementFromBlock(blkno, offno);
|
||||||
|
|
||||||
HnswLoadElementFromTuple(*element, etup, true, loadVec);
|
HnswLoadElementFromTuple(*element, etup, true, loadVec);
|
||||||
}
|
}
|
||||||
@@ -575,9 +576,7 @@ HnswLoadElementImpl(Buffer buf, OffsetNumber offno, double *distance, HnswQuery
|
|||||||
void
|
void
|
||||||
HnswLoadElement(HnswElement element, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance)
|
HnswLoadElement(HnswElement element, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance)
|
||||||
{
|
{
|
||||||
Buffer buf = ReadBuffer(index, element->blkno);
|
HnswLoadElementImpl(element->blkno, element->offno, distance, q, index, support, loadVec, maxDistance, &element);
|
||||||
|
|
||||||
HnswLoadElementImpl(buf, element->offno, distance, q, index, support, loadVec, maxDistance, &element);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -817,31 +816,11 @@ HnswLoadUnvisitedFromDisk(HnswElement element, HnswUnvisited * unvisited, int *u
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
/*
|
|
||||||
* Get next block number for read stream
|
|
||||||
*/
|
|
||||||
static BlockNumber
|
|
||||||
HnswReadStreamNextBlock(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
|
|
||||||
{
|
|
||||||
HnswReadStreamData *streamData = callback_private_data;
|
|
||||||
OffsetNumber *offno = per_buffer_data;
|
|
||||||
HnswUnvisited *uv;
|
|
||||||
|
|
||||||
if (streamData->visited == streamData->unvisitedLength)
|
|
||||||
return InvalidBlockNumber;
|
|
||||||
|
|
||||||
uv = &streamData->unvisited[streamData->visited++];
|
|
||||||
*offno = ItemPointerGetOffsetNumber(&uv->indextid);
|
|
||||||
return ItemPointerGetBlockNumber(&uv->indextid);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Algorithm 2 from paper
|
* Algorithm 2 from paper
|
||||||
*/
|
*/
|
||||||
List *
|
List *
|
||||||
HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples, bool maintenance)
|
HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples)
|
||||||
{
|
{
|
||||||
List *w = NIL;
|
List *w = NIL;
|
||||||
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||||
@@ -856,21 +835,6 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
int unvisitedLength;
|
int unvisitedLength;
|
||||||
bool inMemory = index == NULL;
|
bool inMemory = index == NULL;
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
HnswReadStreamData streamData;
|
|
||||||
ReadStream *stream = NULL;
|
|
||||||
|
|
||||||
if (!inMemory)
|
|
||||||
{
|
|
||||||
int flags = READ_STREAM_USE_BATCHING;
|
|
||||||
|
|
||||||
if (maintenance)
|
|
||||||
flags |= READ_STREAM_MAINTENANCE;
|
|
||||||
|
|
||||||
stream = read_stream_begin_relation(flags, NULL, index, MAIN_FORKNUM, HnswReadStreamNextBlock, &streamData, sizeof(OffsetNumber));
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (v == NULL)
|
if (v == NULL)
|
||||||
{
|
{
|
||||||
v = &vh;
|
v = &vh;
|
||||||
@@ -933,23 +897,13 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
if (inMemory)
|
if (inMemory)
|
||||||
HnswLoadUnvisitedFromMemory(base, cElement, unvisited, &unvisitedLength, v, lc, localNeighborhood, neighborhoodSize);
|
HnswLoadUnvisitedFromMemory(base, cElement, unvisited, &unvisitedLength, v, lc, localNeighborhood, neighborhoodSize);
|
||||||
else
|
else
|
||||||
{
|
|
||||||
HnswLoadUnvisitedFromDisk(cElement, unvisited, &unvisitedLength, v, index, m, lm, lc);
|
HnswLoadUnvisitedFromDisk(cElement, unvisited, &unvisitedLength, v, index, m, lm, lc);
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
read_stream_resume(stream);
|
|
||||||
|
|
||||||
streamData.unvisited = unvisited;
|
|
||||||
streamData.unvisitedLength = unvisitedLength;
|
|
||||||
streamData.visited = 0;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
/* OK to count elements instead of tuples */
|
/* OK to count elements instead of tuples */
|
||||||
if (tuples != NULL)
|
if (tuples != NULL)
|
||||||
(*tuples) += unvisitedLength;
|
(*tuples) += unvisitedLength;
|
||||||
|
|
||||||
for (int i = 0;; i++)
|
for (int i = 0; i < unvisitedLength; i++)
|
||||||
{
|
{
|
||||||
HnswElement eElement;
|
HnswElement eElement;
|
||||||
HnswSearchCandidate *e;
|
HnswSearchCandidate *e;
|
||||||
@@ -960,40 +914,18 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
|
|
||||||
if (inMemory)
|
if (inMemory)
|
||||||
{
|
{
|
||||||
if (i == unvisitedLength)
|
|
||||||
break;
|
|
||||||
|
|
||||||
eElement = unvisited[i].element;
|
eElement = unvisited[i].element;
|
||||||
eDistance = GetElementDistance(base, eElement, q, support);
|
eDistance = GetElementDistance(base, eElement, q, support);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Buffer buf;
|
ItemPointer indextid = &unvisited[i].indextid;
|
||||||
OffsetNumber offno;
|
BlockNumber blkno = ItemPointerGetBlockNumber(indextid);
|
||||||
|
OffsetNumber offno = ItemPointerGetOffsetNumber(indextid);
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
void *offnoPtr;
|
|
||||||
|
|
||||||
buf = read_stream_next_buffer(stream, &offnoPtr);
|
|
||||||
|
|
||||||
if (!BufferIsValid(buf))
|
|
||||||
break;
|
|
||||||
|
|
||||||
offno = *((OffsetNumber *) offnoPtr);
|
|
||||||
#else
|
|
||||||
ItemPointer indextid;
|
|
||||||
|
|
||||||
if (i == unvisitedLength)
|
|
||||||
break;
|
|
||||||
|
|
||||||
indextid = &unvisited[i].indextid;
|
|
||||||
buf = ReadBuffer(index, ItemPointerGetBlockNumber(indextid));
|
|
||||||
offno = ItemPointerGetOffsetNumber(indextid);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Avoid any allocations if not adding */
|
/* Avoid any allocations if not adding */
|
||||||
eElement = NULL;
|
eElement = NULL;
|
||||||
HnswLoadElementImpl(buf, offno, &eDistance, q, index, support, inserting, alwaysAdd || discarded != NULL ? NULL : &f->distance, &eElement);
|
HnswLoadElementImpl(blkno, offno, &eDistance, q, index, support, inserting, alwaysAdd || discarded != NULL ? NULL : &f->distance, &eElement);
|
||||||
|
|
||||||
if (eElement == NULL)
|
if (eElement == NULL)
|
||||||
continue;
|
continue;
|
||||||
@@ -1049,11 +981,6 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
w = lappend(w, sc);
|
w = lappend(w, sc);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 190000
|
|
||||||
if (!inMemory)
|
|
||||||
read_stream_end(stream);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1349,7 +1276,7 @@ PrecomputeHash(char *base, HnswElement element)
|
|||||||
* Algorithm 1 from paper
|
* Algorithm 1 from paper
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool maintenance)
|
HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing)
|
||||||
{
|
{
|
||||||
List *ep;
|
List *ep;
|
||||||
List *w;
|
List *w;
|
||||||
@@ -1376,7 +1303,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
/* 1st phase: greedy search to insert level */
|
/* 1st phase: greedy search to insert level */
|
||||||
for (int lc = entryLevel; lc >= level + 1; lc--)
|
for (int lc = entryLevel; lc >= level + 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(base, &q, ep, 1, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL, maintenance);
|
w = HnswSearchLayer(base, &q, ep, 1, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1395,7 +1322,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
List *lw = NIL;
|
List *lw = NIL;
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
|
|
||||||
w = HnswSearchLayer(base, &q, ep, efConstruction, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL, maintenance);
|
w = HnswSearchLayer(base, &q, ep, efConstruction, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL);
|
||||||
|
|
||||||
/* Convert search candidates to candidates */
|
/* Convert search candidates to candidates */
|
||||||
foreach(lc2, w)
|
foreach(lc2, w)
|
||||||
|
|||||||
221
src/hnswvacuum.c
221
src/hnswvacuum.c
@@ -19,12 +19,12 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Check if deleted list contains an index TID
|
* Check if deletion list contains an element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
DeletedContains(tidhash_hash * deleted, ItemPointer indextid)
|
DeletingElement(tidhash_hash * deleting, ItemPointer indextid)
|
||||||
{
|
{
|
||||||
return tidhash_lookup(deleted, *indextid) != NULL;
|
return tidhash_lookup(deleting, *indextid) != NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -37,17 +37,20 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
{
|
{
|
||||||
BlockNumber blkno = HNSW_HEAD_BLKNO;
|
BlockNumber blkno = HNSW_HEAD_BLKNO;
|
||||||
HnswElement highestPoint = &vacuumstate->highestPoint;
|
HnswElement highestPoint = &vacuumstate->highestPoint;
|
||||||
|
HnswElement fallbackPoint = &vacuumstate->fallbackPoint;
|
||||||
Relation index = vacuumstate->index;
|
Relation index = vacuumstate->index;
|
||||||
BufferAccessStrategy bas = vacuumstate->bas;
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
HnswElement entryPoint = HnswGetEntryPoint(vacuumstate->index);
|
|
||||||
IndexBulkDeleteResult *stats = vacuumstate->stats;
|
IndexBulkDeleteResult *stats = vacuumstate->stats;
|
||||||
|
|
||||||
/* Store separately since highestPoint.level is uint8 */
|
/* Store separately since HnswElement level is uint8 */
|
||||||
int highestLevel = -1;
|
int highestLevel = -1;
|
||||||
|
int fallbackLevel = -1;
|
||||||
|
|
||||||
/* Initialize highest point */
|
/* Initialize highest point and fallback point */
|
||||||
highestPoint->blkno = InvalidBlockNumber;
|
highestPoint->blkno = InvalidBlockNumber;
|
||||||
highestPoint->offno = InvalidOffsetNumber;
|
highestPoint->offno = InvalidOffsetNumber;
|
||||||
|
fallbackPoint->blkno = InvalidBlockNumber;
|
||||||
|
fallbackPoint->offno = InvalidOffsetNumber;
|
||||||
|
|
||||||
while (BlockNumberIsValid(blkno))
|
while (BlockNumberIsValid(blkno))
|
||||||
{
|
{
|
||||||
@@ -77,6 +80,14 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
if (!HnswIsElementTuple(etup))
|
if (!HnswIsElementTuple(etup))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Skip deleted tuples. It is important they are not added to the
|
||||||
|
* deletion list to avoid false positives in NeedsUpdated and
|
||||||
|
* ConfirmRepaired.
|
||||||
|
*/
|
||||||
|
if (etup->deleted)
|
||||||
|
continue;
|
||||||
|
|
||||||
if (ItemPointerIsValid(&etup->heaptids[0]))
|
if (ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
{
|
{
|
||||||
for (int i = 0; i < HNSW_HEAPTIDS; i++)
|
for (int i = 0; i < HNSW_HEAPTIDS; i++)
|
||||||
@@ -110,23 +121,40 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
{
|
{
|
||||||
ItemPointerData ip;
|
ItemPointerData indextid;
|
||||||
bool found;
|
bool found;
|
||||||
|
|
||||||
/* Add to deleted list */
|
/* Add to deletion list */
|
||||||
ItemPointerSet(&ip, blkno, offno);
|
ItemPointerSet(&indextid, blkno, offno);
|
||||||
|
|
||||||
tidhash_insert(vacuumstate->deleted, ip, &found);
|
tidhash_insert(vacuumstate->deleting, indextid, &found);
|
||||||
Assert(!found);
|
Assert(!found);
|
||||||
}
|
}
|
||||||
else if (etup->level > highestLevel && !(entryPoint != NULL && blkno == entryPoint->blkno && offno == entryPoint->offno))
|
else if (etup->level > highestLevel)
|
||||||
{
|
{
|
||||||
/* Keep track of highest non-entry point */
|
if (BlockNumberIsValid(highestPoint->blkno))
|
||||||
|
{
|
||||||
|
/* Current highest point becomes fallback */
|
||||||
|
fallbackPoint->blkno = highestPoint->blkno;
|
||||||
|
fallbackPoint->offno = highestPoint->offno;
|
||||||
|
fallbackPoint->level = highestPoint->level;
|
||||||
|
fallbackLevel = highestLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Keep track of highest point */
|
||||||
highestPoint->blkno = blkno;
|
highestPoint->blkno = blkno;
|
||||||
highestPoint->offno = offno;
|
highestPoint->offno = offno;
|
||||||
highestPoint->level = etup->level;
|
highestPoint->level = etup->level;
|
||||||
highestLevel = etup->level;
|
highestLevel = etup->level;
|
||||||
}
|
}
|
||||||
|
else if (etup->level > fallbackLevel)
|
||||||
|
{
|
||||||
|
/* Keep track of second highest point */
|
||||||
|
fallbackPoint->blkno = blkno;
|
||||||
|
fallbackPoint->offno = offno;
|
||||||
|
fallbackPoint->level = etup->level;
|
||||||
|
fallbackLevel = etup->level;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
blkno = HnswPageGetOpaque(page)->nextblkno;
|
blkno = HnswPageGetOpaque(page)->nextblkno;
|
||||||
@@ -138,6 +166,10 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#ifdef HNSW_MEMORY
|
||||||
|
elog(INFO, "memory: %zu KB", MemoryContextMemAllocated(CurrentMemoryContext, true) / 1024);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -168,8 +200,8 @@ NeedsUpdated(HnswVacuumState * vacuumstate, HnswElement element)
|
|||||||
if (!ItemPointerIsValid(indextid))
|
if (!ItemPointerIsValid(indextid))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
/* Check if in deleted list */
|
/* Check if in deletion list */
|
||||||
if (DeletedContains(vacuumstate->deleted, indextid))
|
if (DeletingElement(vacuumstate->deleting, indextid))
|
||||||
{
|
{
|
||||||
needsUpdated = true;
|
needsUpdated = true;
|
||||||
break;
|
break;
|
||||||
@@ -178,13 +210,9 @@ NeedsUpdated(HnswVacuumState * vacuumstate, HnswElement element)
|
|||||||
|
|
||||||
/* Also update if layer 0 is not full */
|
/* Also update if layer 0 is not full */
|
||||||
/* This could indicate too many candidates being deleted during insert */
|
/* This could indicate too many candidates being deleted during insert */
|
||||||
if (!needsUpdated)
|
/* There should always be more than zero indextids, but check for safety */
|
||||||
{
|
if (!needsUpdated && ntup->count > 0)
|
||||||
/* Keep clang-tidy happy */
|
|
||||||
Assert(ntup->count > 0);
|
|
||||||
|
|
||||||
needsUpdated = !ItemPointerIsValid(&ntup->indextids[ntup->count - 1]);
|
needsUpdated = !ItemPointerIsValid(&ntup->indextids[ntup->count - 1]);
|
||||||
}
|
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
@@ -218,7 +246,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
element->heaptidsLength = 0;
|
element->heaptidsLength = 0;
|
||||||
|
|
||||||
/* Find neighbors for element, skipping itself */
|
/* Find neighbors for element, skipping itself */
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, true, true);
|
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, true);
|
||||||
|
|
||||||
/* Zero memory for each element */
|
/* Zero memory for each element */
|
||||||
MemSet(ntup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
MemSet(ntup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
||||||
@@ -269,12 +297,27 @@ RepairGraphEntryPoint(HnswVacuumState * vacuumstate)
|
|||||||
/* Get a shared lock */
|
/* Get a shared lock */
|
||||||
LockPage(index, HNSW_UPDATE_LOCK, ShareLock);
|
LockPage(index, HNSW_UPDATE_LOCK, ShareLock);
|
||||||
|
|
||||||
/* Load element */
|
/* Get latest entry point */
|
||||||
HnswLoadElement(highestPoint, NULL, NULL, index, support, true, NULL);
|
entryPoint = HnswGetEntryPoint(index);
|
||||||
|
|
||||||
/* Repair if needed */
|
/* Use fallback point if highest point is entry point */
|
||||||
if (NeedsUpdated(vacuumstate, highestPoint))
|
if (entryPoint != NULL && entryPoint->blkno == highestPoint->blkno && entryPoint->offno == highestPoint->offno)
|
||||||
RepairGraphElement(vacuumstate, highestPoint, HnswGetEntryPoint(index));
|
{
|
||||||
|
highestPoint = &vacuumstate->fallbackPoint;
|
||||||
|
|
||||||
|
if (!BlockNumberIsValid(highestPoint->blkno))
|
||||||
|
highestPoint = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (highestPoint != NULL)
|
||||||
|
{
|
||||||
|
/* Load element */
|
||||||
|
HnswLoadElement(highestPoint, NULL, NULL, index, support, true, NULL);
|
||||||
|
|
||||||
|
/* Repair if needed */
|
||||||
|
if (NeedsUpdated(vacuumstate, highestPoint))
|
||||||
|
RepairGraphElement(vacuumstate, highestPoint, entryPoint);
|
||||||
|
}
|
||||||
|
|
||||||
/* Release lock */
|
/* Release lock */
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, ShareLock);
|
UnlockPage(index, HNSW_UPDATE_LOCK, ShareLock);
|
||||||
@@ -292,7 +335,7 @@ RepairGraphEntryPoint(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
ItemPointerSet(&epData, entryPoint->blkno, entryPoint->offno);
|
ItemPointerSet(&epData, entryPoint->blkno, entryPoint->offno);
|
||||||
|
|
||||||
if (DeletedContains(vacuumstate->deleted, &epData))
|
if (DeletingElement(vacuumstate->deleting, &epData))
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
* Replace the entry point with the highest point. If highest
|
* Replace the entry point with the highest point. If highest
|
||||||
@@ -378,6 +421,10 @@ RepairGraph(HnswVacuumState * vacuumstate)
|
|||||||
if (!HnswIsElementTuple(etup))
|
if (!HnswIsElementTuple(etup))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
/* Skip deleted tuples */
|
||||||
|
if (etup->deleted)
|
||||||
|
continue;
|
||||||
|
|
||||||
/* Skip updating neighbors if being deleted */
|
/* Skip updating neighbors if being deleted */
|
||||||
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
continue;
|
continue;
|
||||||
@@ -441,6 +488,103 @@ RepairGraph(HnswVacuumState * vacuumstate)
|
|||||||
/* Reset memory context */
|
/* Reset memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
MemoryContextReset(vacuumstate->tmpCtx);
|
MemoryContextReset(vacuumstate->tmpCtx);
|
||||||
|
|
||||||
|
#ifdef HNSW_VACUUM_PROGRESS
|
||||||
|
if (!BlockNumberIsValid(blkno) || (blkno - HNSW_HEAD_BLKNO) % 1000 == 0)
|
||||||
|
{
|
||||||
|
BlockNumber totalBlocks = RelationGetNumberOfBlocks(index);
|
||||||
|
BlockNumber currentBlocks = BlockNumberIsValid(blkno) ? blkno : totalBlocks;
|
||||||
|
|
||||||
|
elog(INFO, "hnsw vacuum progress: %.1f%%", 100.0 * currentBlocks / totalBlocks);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Confirm graph was repaired
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
ConfirmRepaired(HnswVacuumState * vacuumstate)
|
||||||
|
{
|
||||||
|
BlockNumber blkno = HNSW_HEAD_BLKNO;
|
||||||
|
Relation index = vacuumstate->index;
|
||||||
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
|
|
||||||
|
while (BlockNumberIsValid(blkno))
|
||||||
|
{
|
||||||
|
Buffer buf;
|
||||||
|
Page page;
|
||||||
|
OffsetNumber offno;
|
||||||
|
OffsetNumber maxoffno;
|
||||||
|
|
||||||
|
vacuum_delay_point();
|
||||||
|
|
||||||
|
buf = ReadBufferExtended(index, MAIN_FORKNUM, blkno, RBM_NORMAL, bas);
|
||||||
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
|
page = BufferGetPage(buf);
|
||||||
|
maxoffno = PageGetMaxOffsetNumber(page);
|
||||||
|
|
||||||
|
/* Iterate over nodes */
|
||||||
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
|
{
|
||||||
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||||
|
HnswNeighborTuple ntup;
|
||||||
|
Buffer nbuf;
|
||||||
|
Page npage;
|
||||||
|
BlockNumber neighborPage;
|
||||||
|
OffsetNumber neighborOffno;
|
||||||
|
|
||||||
|
/* Skip neighbor tuples */
|
||||||
|
if (!HnswIsElementTuple(etup))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Skip deleted tuples */
|
||||||
|
if (etup->deleted)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Skip if being deleted */
|
||||||
|
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Get neighbor page */
|
||||||
|
neighborPage = ItemPointerGetBlockNumber(&etup->neighbortid);
|
||||||
|
neighborOffno = ItemPointerGetOffsetNumber(&etup->neighbortid);
|
||||||
|
|
||||||
|
if (neighborPage == blkno)
|
||||||
|
{
|
||||||
|
nbuf = buf;
|
||||||
|
npage = page;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
nbuf = ReadBufferExtended(index, MAIN_FORKNUM, neighborPage, RBM_NORMAL, bas);
|
||||||
|
LockBuffer(nbuf, BUFFER_LOCK_SHARE);
|
||||||
|
npage = BufferGetPage(nbuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
ntup = (HnswNeighborTuple) PageGetItem(npage, PageGetItemId(npage, neighborOffno));
|
||||||
|
|
||||||
|
/* Check neighbors */
|
||||||
|
for (int i = 0; i < ntup->count; i++)
|
||||||
|
{
|
||||||
|
ItemPointer indextid = &ntup->indextids[i];
|
||||||
|
|
||||||
|
if (!ItemPointerIsValid(indextid))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Check if in deletion list */
|
||||||
|
if (DeletingElement(vacuumstate->deleting, indextid))
|
||||||
|
elog(ERROR, "hnsw graph not repaired");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nbuf != buf)
|
||||||
|
UnlockReleaseBuffer(nbuf);
|
||||||
|
}
|
||||||
|
|
||||||
|
blkno = HnswPageGetOpaque(page)->nextblkno;
|
||||||
|
|
||||||
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -456,10 +600,15 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
BufferAccessStrategy bas = vacuumstate->bas;
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Wait for index scans to complete. Scans before this point may contain
|
* Wait for inserts and index scans to complete. Inserts and scans before
|
||||||
* tuples about to be deleted. Scans after this point will not, since the
|
* this point may visit tuples about to be deleted. Inserts and scans
|
||||||
* graph has been repaired.
|
* after this point will not, since the graph has been repaired.
|
||||||
*/
|
*/
|
||||||
|
LockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
||||||
|
UnlockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
||||||
|
|
||||||
|
ConfirmRepaired(vacuumstate);
|
||||||
|
|
||||||
LockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
LockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
||||||
UnlockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
UnlockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
||||||
|
|
||||||
@@ -607,7 +756,7 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
HnswGetMetaPageInfo(index, &vacuumstate->m, NULL);
|
HnswGetMetaPageInfo(index, &vacuumstate->m, NULL);
|
||||||
|
|
||||||
/* Create hash table */
|
/* Create hash table */
|
||||||
vacuumstate->deleted = tidhash_create(CurrentMemoryContext, 256, NULL);
|
vacuumstate->deleting = tidhash_create(CurrentMemoryContext, 256, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -616,7 +765,7 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
static void
|
static void
|
||||||
FreeVacuumState(HnswVacuumState * vacuumstate)
|
FreeVacuumState(HnswVacuumState * vacuumstate)
|
||||||
{
|
{
|
||||||
tidhash_destroy(vacuumstate->deleted);
|
tidhash_destroy(vacuumstate->deleting);
|
||||||
FreeAccessStrategy(vacuumstate->bas);
|
FreeAccessStrategy(vacuumstate->bas);
|
||||||
pfree(vacuumstate->ntup);
|
pfree(vacuumstate->ntup);
|
||||||
MemoryContextDelete(vacuumstate->tmpCtx);
|
MemoryContextDelete(vacuumstate->tmpCtx);
|
||||||
@@ -634,13 +783,13 @@ hnswbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
|||||||
InitVacuumState(&vacuumstate, info, stats, callback, callback_state);
|
InitVacuumState(&vacuumstate, info, stats, callback, callback_state);
|
||||||
|
|
||||||
/* Pass 1: Remove heap TIDs */
|
/* Pass 1: Remove heap TIDs */
|
||||||
RemoveHeapTids(&vacuumstate);
|
HnswBench("RemoveHeapTids", RemoveHeapTids(&vacuumstate));
|
||||||
|
|
||||||
/* Pass 2: Repair graph */
|
/* Pass 2: Repair graph */
|
||||||
RepairGraph(&vacuumstate);
|
HnswBench("RepairGraph", RepairGraph(&vacuumstate));
|
||||||
|
|
||||||
/* Pass 3: Mark as deleted */
|
/* Passes 3 and 4: Confirm repaired and mark as deleted */
|
||||||
MarkDeleted(&vacuumstate);
|
HnswBench("MarkDeleted", MarkDeleted(&vacuumstate));
|
||||||
|
|
||||||
FreeVacuumState(&vacuumstate);
|
FreeVacuumState(&vacuumstate);
|
||||||
|
|
||||||
|
|||||||
@@ -145,24 +145,14 @@ SampleRows(IvfflatBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
BlockNumber targblock = BlockSampler_Next(&buildstate->bs);
|
BlockNumber targblock = BlockSampler_Next(&buildstate->bs);
|
||||||
|
|
||||||
|
/* Set anyvisible to false like table_index_build_scan */
|
||||||
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
|
false, false, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->kmeansnormprocinfo != NULL)
|
if (buildstate->kmeansnormprocinfo != NULL)
|
||||||
{
|
IvfflatNormVectors(buildstate->typeInfo, buildstate->collation, buildstate->samples, buildstate->tmpCtx);
|
||||||
VectorArray samples = buildstate->samples;
|
|
||||||
|
|
||||||
for (int i = 0; i < samples->length; i++)
|
|
||||||
{
|
|
||||||
Datum value = PointerGetDatum(VectorArrayGet(samples, i));
|
|
||||||
Datum normValue = IvfflatNormValue(buildstate->typeInfo, buildstate->collation, value);
|
|
||||||
|
|
||||||
VectorArraySet(samples, i, DatumGetPointer(normValue));
|
|
||||||
pfree(DatumGetPointer(normValue));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -398,7 +388,14 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
|||||||
|
|
||||||
buildstate->slot = MakeSingleTupleTableSlot(buildstate->sortdesc, &TTSOpsVirtual);
|
buildstate->slot = MakeSingleTupleTableSlot(buildstate->sortdesc, &TTSOpsVirtual);
|
||||||
|
|
||||||
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions, buildstate->typeInfo->itemSize(buildstate->dimensions));
|
buildstate->memoryUsed = 0;
|
||||||
|
buildstate->itemsize = buildstate->typeInfo->itemSize(buildstate->dimensions);
|
||||||
|
|
||||||
|
buildstate->memoryUsed += VECTOR_ARRAY_SIZE(buildstate->lists, buildstate->itemsize);
|
||||||
|
IvfflatCheckMemoryUsage(buildstate->memoryUsed);
|
||||||
|
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions, buildstate->itemsize);
|
||||||
|
|
||||||
|
/* TODO Move allocation to page creation */
|
||||||
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
||||||
|
|
||||||
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
@@ -441,19 +438,27 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
||||||
|
|
||||||
/* Target 50 samples per list, with at least 10000 samples */
|
|
||||||
/* The number of samples has a large effect on index build time */
|
|
||||||
numSamples = buildstate->lists * 50;
|
|
||||||
if (numSamples < 10000)
|
|
||||||
numSamples = 10000;
|
|
||||||
|
|
||||||
/* Skip samples for unlogged table */
|
/* Skip samples for unlogged table */
|
||||||
if (buildstate->heap == NULL)
|
if (buildstate->heap == NULL)
|
||||||
numSamples = 1;
|
numSamples = 1;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int64 maxTuples = (int64) RelationGetNumberOfBlocks(buildstate->heap) * MaxHeapTuplesPerPage;
|
||||||
|
|
||||||
|
/* Target 50 samples per list, with at least 10000 samples */
|
||||||
|
/* The number of samples has a large effect on index build time */
|
||||||
|
numSamples = buildstate->lists * 50;
|
||||||
|
if (numSamples < 10000)
|
||||||
|
numSamples = 10000;
|
||||||
|
|
||||||
|
/* Save memory since will not have more than max tuples */
|
||||||
|
numSamples = Max(Min(numSamples, maxTuples), 1);
|
||||||
|
}
|
||||||
|
|
||||||
/* Sample rows */
|
/* Sample rows */
|
||||||
/* TODO Ensure within maintenance_work_mem */
|
buildstate->memoryUsed += VECTOR_ARRAY_SIZE(numSamples, buildstate->itemsize);
|
||||||
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions, buildstate->centers->itemsize);
|
IvfflatCheckMemoryUsage(buildstate->memoryUsed);
|
||||||
|
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions, buildstate->itemsize);
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
{
|
{
|
||||||
IvfflatBench("sample rows", SampleRows(buildstate));
|
IvfflatBench("sample rows", SampleRows(buildstate));
|
||||||
@@ -468,7 +473,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Calculate centers */
|
/* Calculate centers */
|
||||||
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers, buildstate->typeInfo));
|
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers, buildstate->typeInfo, buildstate->memoryUsed));
|
||||||
|
|
||||||
/* Free samples before we allocate more memory */
|
/* Free samples before we allocate more memory */
|
||||||
VectorArrayFree(buildstate->samples);
|
VectorArrayFree(buildstate->samples);
|
||||||
|
|||||||
@@ -204,6 +204,7 @@ typedef struct IvfflatBuildState
|
|||||||
VectorArray samples;
|
VectorArray samples;
|
||||||
VectorArray centers;
|
VectorArray centers;
|
||||||
ListInfo *listInfo;
|
ListInfo *listInfo;
|
||||||
|
Size itemsize;
|
||||||
|
|
||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
double inertia;
|
double inertia;
|
||||||
@@ -223,6 +224,7 @@ typedef struct IvfflatBuildState
|
|||||||
TupleTableSlot *slot;
|
TupleTableSlot *slot;
|
||||||
|
|
||||||
/* Memory */
|
/* Memory */
|
||||||
|
Size memoryUsed;
|
||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
|
|
||||||
/* Parallel builds */
|
/* Parallel builds */
|
||||||
@@ -303,22 +305,32 @@ typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
|
|||||||
static inline Pointer
|
static inline Pointer
|
||||||
VectorArrayGet(VectorArray arr, int offset)
|
VectorArrayGet(VectorArray arr, int offset)
|
||||||
{
|
{
|
||||||
|
if (offset >= arr->maxlen)
|
||||||
|
elog(ERROR, "safety check failed");
|
||||||
|
|
||||||
return ((char *) arr->items) + (offset * arr->itemsize);
|
return ((char *) arr->items) + (offset * arr->itemsize);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline void
|
static inline void
|
||||||
VectorArraySet(VectorArray arr, int offset, Pointer val)
|
VectorArraySet(VectorArray arr, int offset, Pointer val)
|
||||||
{
|
{
|
||||||
memcpy(VectorArrayGet(arr, offset), val, VARSIZE_ANY(val));
|
Size size = VARSIZE_ANY(val);
|
||||||
|
|
||||||
|
if (size > arr->itemsize)
|
||||||
|
elog(ERROR, "safety check failed");
|
||||||
|
|
||||||
|
memcpy(VectorArrayGet(arr, offset), val, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Methods */
|
/* Methods */
|
||||||
VectorArray VectorArrayInit(int maxlen, int dimensions, Size itemsize);
|
VectorArray VectorArrayInit(int maxlen, int dimensions, Size itemsize);
|
||||||
void VectorArrayFree(VectorArray arr);
|
void VectorArrayFree(VectorArray arr);
|
||||||
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo);
|
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo, Size memoryUsed);
|
||||||
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
Datum IvfflatNormValue(const IvfflatTypeInfo * typeInfo, Oid collation, Datum value);
|
Datum IvfflatNormValue(const IvfflatTypeInfo * typeInfo, Oid collation, Datum value);
|
||||||
bool IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value);
|
bool IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value);
|
||||||
|
void IvfflatNormVectors(const IvfflatTypeInfo * typeInfo, Oid collation, VectorArray arr, MemoryContext tmpCtx);
|
||||||
|
void IvfflatCheckMemoryUsage(Size totalSize);
|
||||||
int IvfflatGetLists(Relation index);
|
int IvfflatGetLists(Relation index);
|
||||||
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
||||||
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include "fmgr.h"
|
#include "fmgr.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
|
#include "utils/datum.h"
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
#include "utils/relcache.h"
|
#include "utils/relcache.h"
|
||||||
|
|
||||||
@@ -99,36 +100,50 @@ NormCenters(const IvfflatTypeInfo * typeInfo, Oid collation, VectorArray centers
|
|||||||
MemoryContext normCtx = AllocSetContextCreate(CurrentMemoryContext,
|
MemoryContext normCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Ivfflat norm temporary context",
|
"Ivfflat norm temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
MemoryContext oldCtx = MemoryContextSwitchTo(normCtx);
|
|
||||||
|
|
||||||
for (int j = 0; j < centers->length; j++)
|
IvfflatNormVectors(typeInfo, collation, centers, normCtx);
|
||||||
{
|
|
||||||
Datum center = PointerGetDatum(VectorArrayGet(centers, j));
|
|
||||||
Datum newCenter = IvfflatNormValue(typeInfo, collation, center);
|
|
||||||
Size size = VARSIZE_ANY(DatumGetPointer(newCenter));
|
|
||||||
|
|
||||||
if (size > centers->itemsize)
|
|
||||||
elog(ERROR, "safety check failed");
|
|
||||||
|
|
||||||
memcpy(DatumGetPointer(center), DatumGetPointer(newCenter), size);
|
|
||||||
MemoryContextReset(normCtx);
|
|
||||||
}
|
|
||||||
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
|
||||||
MemoryContextDelete(normCtx);
|
MemoryContextDelete(normCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Quick approach if we have no data
|
* Check if vector array contains a vector
|
||||||
|
*/
|
||||||
|
static bool
|
||||||
|
VectorArrayContains(VectorArray arr, Pointer val)
|
||||||
|
{
|
||||||
|
Datum d = PointerGetDatum(val);
|
||||||
|
|
||||||
|
for (int i = 0; i < arr->length; i++)
|
||||||
|
{
|
||||||
|
if (datumIsEqual(d, PointerGetDatum(VectorArrayGet(arr, i)), false, -1))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Quick approach if we have little data
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
RandomCenters(Relation index, VectorArray centers, const IvfflatTypeInfo * typeInfo)
|
QuickCenters(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo)
|
||||||
{
|
{
|
||||||
int dimensions = centers->dim;
|
int dimensions = centers->dim;
|
||||||
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||||
Oid collation = index->rd_indcollation[0];
|
Oid collation = index->rd_indcollation[0];
|
||||||
float *x = (float *) palloc(sizeof(float) * dimensions);
|
float *x = (float *) palloc(sizeof(float) * dimensions);
|
||||||
|
|
||||||
|
/* Fill with unique samples (already normalized) */
|
||||||
|
for (int i = 0; i < samples->length; i++)
|
||||||
|
{
|
||||||
|
Pointer sample = VectorArrayGet(samples, i);
|
||||||
|
|
||||||
|
if (!VectorArrayContains(centers, sample))
|
||||||
|
{
|
||||||
|
VectorArraySet(centers, centers->length, sample);
|
||||||
|
centers->length++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Fill with random data */
|
/* Fill with random data */
|
||||||
while (centers->length < centers->maxlen)
|
while (centers->length < centers->maxlen)
|
||||||
{
|
{
|
||||||
@@ -258,7 +273,7 @@ ComputeNewCenters(VectorArray samples, float *agg, VectorArray newCenters, int *
|
|||||||
* https://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf
|
* https://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
ElkanKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo)
|
ElkanKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo, Size memoryUsed)
|
||||||
{
|
{
|
||||||
FmgrInfo *procinfo;
|
FmgrInfo *procinfo;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
@@ -277,8 +292,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers, const Ivff
|
|||||||
float *newcdist;
|
float *newcdist;
|
||||||
|
|
||||||
/* Calculate allocation sizes */
|
/* Calculate allocation sizes */
|
||||||
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->itemsize);
|
|
||||||
Size centersSize = VECTOR_ARRAY_SIZE(centers->maxlen, centers->itemsize);
|
|
||||||
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, centers->itemsize);
|
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, centers->itemsize);
|
||||||
Size aggSize = sizeof(float) * (int64) numCenters * dimensions;
|
Size aggSize = sizeof(float) * (int64) numCenters * dimensions;
|
||||||
Size centerCountsSize = sizeof(int) * numCenters;
|
Size centerCountsSize = sizeof(int) * numCenters;
|
||||||
@@ -290,18 +303,13 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers, const Ivff
|
|||||||
Size newcdistSize = sizeof(float) * numCenters;
|
Size newcdistSize = sizeof(float) * numCenters;
|
||||||
|
|
||||||
/* Calculate total size */
|
/* Calculate total size */
|
||||||
Size totalSize = samplesSize + centersSize + newCentersSize + aggSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
|
Size totalSize = memoryUsed + newCentersSize + aggSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
|
||||||
|
|
||||||
/* Check memory requirements */
|
/* Check memory requirements */
|
||||||
/* Add one to error message to ceil */
|
IvfflatCheckMemoryUsage(totalSize);
|
||||||
if (totalSize > (Size) maintenance_work_mem * 1024L)
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
|
||||||
errmsg("memory required is %zu MB, maintenance_work_mem is %d MB",
|
|
||||||
totalSize / (1024 * 1024) + 1, maintenance_work_mem / 1024)));
|
|
||||||
|
|
||||||
/* Ensure indexing does not overflow */
|
/* Ensure indexing does not overflow */
|
||||||
if (numCenters * numCenters > INT_MAX)
|
if (numCenters > INT_MAX / numCenters)
|
||||||
elog(ERROR, "Indexing overflow detected. Please report a bug.");
|
elog(ERROR, "Indexing overflow detected. Please report a bug.");
|
||||||
|
|
||||||
/* Set support functions */
|
/* Set support functions */
|
||||||
@@ -562,17 +570,17 @@ CheckCenters(Relation index, VectorArray centers, const IvfflatTypeInfo * typeIn
|
|||||||
* We use spherical k-means for inner product and cosine
|
* We use spherical k-means for inner product and cosine
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo)
|
IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo, Size memoryUsed)
|
||||||
{
|
{
|
||||||
MemoryContext kmeansCtx = AllocSetContextCreate(CurrentMemoryContext,
|
MemoryContext kmeansCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Ivfflat kmeans temporary context",
|
"Ivfflat kmeans temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
MemoryContext oldCtx = MemoryContextSwitchTo(kmeansCtx);
|
MemoryContext oldCtx = MemoryContextSwitchTo(kmeansCtx);
|
||||||
|
|
||||||
if (samples->length == 0)
|
if (samples->length <= centers->maxlen)
|
||||||
RandomCenters(index, centers, typeInfo);
|
QuickCenters(index, samples, centers, typeInfo);
|
||||||
else
|
else
|
||||||
ElkanKmeans(index, samples, centers, typeInfo);
|
ElkanKmeans(index, samples, centers, typeInfo, memoryUsed);
|
||||||
|
|
||||||
CheckCenters(index, centers, typeInfo);
|
CheckCenters(index, centers, typeInfo);
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,9 @@
|
|||||||
#include "halfutils.h"
|
#include "halfutils.h"
|
||||||
#include "halfvec.h"
|
#include "halfvec.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
|
#include "miscadmin.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
|
#include "utils/memutils.h"
|
||||||
#include "utils/relcache.h"
|
#include "utils/relcache.h"
|
||||||
#include "utils/varbit.h"
|
#include "utils/varbit.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
@@ -21,11 +23,15 @@
|
|||||||
VectorArray
|
VectorArray
|
||||||
VectorArrayInit(int maxlen, int dimensions, Size itemsize)
|
VectorArrayInit(int maxlen, int dimensions, Size itemsize)
|
||||||
{
|
{
|
||||||
VectorArray res = palloc(sizeof(VectorArrayData));
|
VectorArray res;
|
||||||
|
|
||||||
|
if (maxlen < 1 || dimensions < 1 || itemsize == 0)
|
||||||
|
elog(ERROR, "cannot create vector array");
|
||||||
|
|
||||||
/* Ensure items are aligned to prevent UB */
|
/* Ensure items are aligned to prevent UB */
|
||||||
itemsize = MAXALIGN(itemsize);
|
itemsize = MAXALIGN(itemsize);
|
||||||
|
|
||||||
|
res = palloc(sizeof(VectorArrayData));
|
||||||
res->length = 0;
|
res->length = 0;
|
||||||
res->maxlen = maxlen;
|
res->maxlen = maxlen;
|
||||||
res->dim = dimensions;
|
res->dim = dimensions;
|
||||||
@@ -88,6 +94,40 @@ IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value)
|
|||||||
return DatumGetFloat8(FunctionCall1Coll(procinfo, collation, value)) > 0;
|
return DatumGetFloat8(FunctionCall1Coll(procinfo, collation, value)) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Normalize vectors
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
IvfflatNormVectors(const IvfflatTypeInfo * typeInfo, Oid collation, VectorArray arr, MemoryContext tmpCtx)
|
||||||
|
{
|
||||||
|
MemoryContext oldCtx = MemoryContextSwitchTo(tmpCtx);
|
||||||
|
|
||||||
|
for (int i = 0; i < arr->length; i++)
|
||||||
|
{
|
||||||
|
Datum value = PointerGetDatum(VectorArrayGet(arr, i));
|
||||||
|
Datum newValue = IvfflatNormValue(typeInfo, collation, value);
|
||||||
|
|
||||||
|
VectorArraySet(arr, i, DatumGetPointer(newValue));
|
||||||
|
MemoryContextReset(tmpCtx);
|
||||||
|
}
|
||||||
|
|
||||||
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check memory usage
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
IvfflatCheckMemoryUsage(Size totalSize)
|
||||||
|
{
|
||||||
|
/* Add one to error message to ceil */
|
||||||
|
if (totalSize > maintenance_work_mem * (Size) 1024)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("memory required is %zu MB, maintenance_work_mem is %d MB",
|
||||||
|
totalSize / (1024 * 1024) + 1, maintenance_work_mem / 1024)));
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* New buffer
|
* New buffer
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -182,10 +182,10 @@ sparsevec_isspace(char ch)
|
|||||||
static int
|
static int
|
||||||
CompareIndices(const void *a, const void *b)
|
CompareIndices(const void *a, const void *b)
|
||||||
{
|
{
|
||||||
if (((SparseInputElement *) a)->index < ((SparseInputElement *) b)->index)
|
if (((const SparseInputElement *) a)->index < ((const SparseInputElement *) b)->index)
|
||||||
return -1;
|
return -1;
|
||||||
|
|
||||||
if (((SparseInputElement *) a)->index > ((SparseInputElement *) b)->index)
|
if (((const SparseInputElement *) a)->index > ((const SparseInputElement *) b)->index)
|
||||||
return 1;
|
return 1;
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@@ -40,7 +40,7 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 180000
|
#if PG_VERSION_NUM >= 180000
|
||||||
PG_MODULE_MAGIC_EXT(.name = "vector",.version = "0.8.2");
|
PG_MODULE_MAGIC_EXT(.name = "vector", .version = "0.8.5");
|
||||||
#else
|
#else
|
||||||
PG_MODULE_MAGIC;
|
PG_MODULE_MAGIC;
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -49,3 +49,11 @@ CREATE INDEX ON t USING hnsw ((val::bit(3)) bit_hamming_ops);
|
|||||||
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
||||||
ERROR: column cannot have more than 64000 dimensions for hnsw index
|
ERROR: column cannot have more than 64000 dimensions for hnsw index
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val bit(64001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
ERROR: column cannot have more than 64000 dimensions for hnsw index
|
||||||
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -100,3 +100,11 @@ SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <+> (SELECT NULL::halfvec)) t
|
|||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val halfvec(4001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_l2_ops);
|
||||||
|
ERROR: column cannot have more than 4000 dimensions for hnsw index
|
||||||
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ ERROR: value 1001 out of bounds for option "ef_construction"
|
|||||||
DETAIL: Valid values are between "4" and "1000".
|
DETAIL: Valid values are between "4" and "1000".
|
||||||
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (m = 16, ef_construction = 31);
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (m = 16, ef_construction = 31);
|
||||||
ERROR: ef_construction must be greater than or equal to 2 * m
|
ERROR: ef_construction must be greater than or equal to 2 * m
|
||||||
|
DROP TABLE t;
|
||||||
SHOW hnsw.ef_search;
|
SHOW hnsw.ef_search;
|
||||||
hnsw.ef_search
|
hnsw.ef_search
|
||||||
----------------
|
----------------
|
||||||
@@ -198,4 +199,11 @@ SET hnsw.scan_mem_multiplier = 0;
|
|||||||
ERROR: 0 is outside the valid range for parameter "hnsw.scan_mem_multiplier" (1 .. 1000)
|
ERROR: 0 is outside the valid range for parameter "hnsw.scan_mem_multiplier" (1 .. 1000)
|
||||||
SET hnsw.scan_mem_multiplier = 1001;
|
SET hnsw.scan_mem_multiplier = 1001;
|
||||||
ERROR: 1001 is outside the valid range for parameter "hnsw.scan_mem_multiplier" (1 .. 1000)
|
ERROR: 1001 is outside the valid range for parameter "hnsw.scan_mem_multiplier" (1 .. 1000)
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val vector(2001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops);
|
||||||
|
ERROR: column cannot have more than 2000 dimensions for hnsw index
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -35,3 +35,32 @@ NOTICE: ivfflat index created with little data
|
|||||||
DETAIL: This will cause low recall.
|
DETAIL: This will cause low recall.
|
||||||
HINT: Drop the index until the table has more data.
|
HINT: Drop the index until the table has more data.
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val bit(64001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
ERROR: column cannot have more than 64000 dimensions for ivfflat index
|
||||||
|
DROP TABLE t;
|
||||||
|
-- memory
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
SET maintenance_work_mem = '29MB';
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
INSERT INTO t (val) VALUES (B'0'::bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
@@ -82,3 +82,32 @@ SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::halfvec)) t
|
|||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val halfvec(4001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
ERROR: column cannot have more than 4000 dimensions for ivfflat index
|
||||||
|
DROP TABLE t;
|
||||||
|
-- memory
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
SET maintenance_work_mem = '6MB';
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(0, ARRAY[4000]));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
@@ -143,6 +143,7 @@ DETAIL: Valid values are between "1" and "32768".
|
|||||||
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 32769);
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 32769);
|
||||||
ERROR: value 32769 out of bounds for option "lists"
|
ERROR: value 32769 out of bounds for option "lists"
|
||||||
DETAIL: Valid values are between "1" and "32768".
|
DETAIL: Valid values are between "1" and "32768".
|
||||||
|
DROP TABLE t;
|
||||||
SHOW ivfflat.probes;
|
SHOW ivfflat.probes;
|
||||||
ivfflat.probes
|
ivfflat.probes
|
||||||
----------------
|
----------------
|
||||||
@@ -172,4 +173,32 @@ SET ivfflat.max_probes = 0;
|
|||||||
ERROR: 0 is outside the valid range for parameter "ivfflat.max_probes" (1 .. 32768)
|
ERROR: 0 is outside the valid range for parameter "ivfflat.max_probes" (1 .. 32768)
|
||||||
SET ivfflat.max_probes = 32769;
|
SET ivfflat.max_probes = 32769;
|
||||||
ERROR: 32769 is outside the valid range for parameter "ivfflat.max_probes" (1 .. 32768)
|
ERROR: 32769 is outside the valid range for parameter "ivfflat.max_probes" (1 .. 32768)
|
||||||
|
-- dimensions
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
CREATE TABLE t (val vector(2001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
ERROR: column cannot have more than 2000 dimensions for ivfflat index
|
||||||
|
DROP TABLE t;
|
||||||
|
-- memory
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
SET maintenance_work_mem = '5MB';
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(0, ARRAY[2000]));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
NOTICE: ivfflat index created with little data
|
||||||
|
DETAIL: This will cause low recall.
|
||||||
|
HINT: Drop the index until the table has more data.
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
@@ -33,3 +33,13 @@ CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
|||||||
CREATE INDEX ON t USING hnsw ((val::bit(3)) bit_hamming_ops);
|
CREATE INDEX ON t USING hnsw ((val::bit(3)) bit_hamming_ops);
|
||||||
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
CREATE INDEX ON t USING hnsw ((val::bit(64001)) bit_hamming_ops);
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val bit(64001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -56,3 +56,13 @@ SELECT * FROM t ORDER BY val <+> '[3,3,3]';
|
|||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <+> (SELECT NULL::halfvec)) t2;
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <+> (SELECT NULL::halfvec)) t2;
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(4001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -95,23 +95,28 @@ CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (m = 101);
|
|||||||
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (ef_construction = 3);
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (ef_construction = 3);
|
||||||
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (ef_construction = 1001);
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (ef_construction = 1001);
|
||||||
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (m = 16, ef_construction = 31);
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops) WITH (m = 16, ef_construction = 31);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
SHOW hnsw.ef_search;
|
SHOW hnsw.ef_search;
|
||||||
|
|
||||||
SET hnsw.ef_search = 0;
|
SET hnsw.ef_search = 0;
|
||||||
SET hnsw.ef_search = 1001;
|
SET hnsw.ef_search = 1001;
|
||||||
|
|
||||||
SHOW hnsw.iterative_scan;
|
SHOW hnsw.iterative_scan;
|
||||||
|
|
||||||
SET hnsw.iterative_scan = on;
|
SET hnsw.iterative_scan = on;
|
||||||
|
|
||||||
SHOW hnsw.max_scan_tuples;
|
SHOW hnsw.max_scan_tuples;
|
||||||
|
|
||||||
SET hnsw.max_scan_tuples = 0;
|
SET hnsw.max_scan_tuples = 0;
|
||||||
|
|
||||||
SHOW hnsw.scan_mem_multiplier;
|
SHOW hnsw.scan_mem_multiplier;
|
||||||
|
|
||||||
SET hnsw.scan_mem_multiplier = 0;
|
SET hnsw.scan_mem_multiplier = 0;
|
||||||
SET hnsw.scan_mem_multiplier = 1001;
|
SET hnsw.scan_mem_multiplier = 1001;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val vector(2001));
|
||||||
|
CREATE INDEX ON t USING hnsw (val vector_l2_ops);
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -21,3 +21,28 @@ CREATE INDEX ON t USING ivfflat ((val::bit(3)) bit_hamming_ops) WITH (lists = 1)
|
|||||||
CREATE INDEX ON t USING ivfflat ((val::bit(64001)) bit_hamming_ops) WITH (lists = 1);
|
CREATE INDEX ON t USING ivfflat ((val::bit(64001)) bit_hamming_ops) WITH (lists = 1);
|
||||||
CREATE INDEX ON t USING ivfflat ((val::bit(2)) bit_hamming_ops) WITH (lists = 5);
|
CREATE INDEX ON t USING ivfflat ((val::bit(2)) bit_hamming_ops) WITH (lists = 5);
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val bit(64001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- memory
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '29MB';
|
||||||
|
CREATE TABLE t (val bit(64000));
|
||||||
|
INSERT INTO t (val) VALUES (B'0'::bit(64000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val bit_hamming_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
@@ -43,3 +43,28 @@ SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
|
|||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::halfvec)) t2;
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::halfvec)) t2;
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val halfvec(4001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- memory
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '6MB';
|
||||||
|
CREATE TABLE t (val halfvec(4000));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(0, ARRAY[4000]));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val halfvec_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
@@ -81,19 +81,40 @@ DROP TABLE t;
|
|||||||
CREATE TABLE t (val vector(3));
|
CREATE TABLE t (val vector(3));
|
||||||
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 0);
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 0);
|
||||||
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 32769);
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops) WITH (lists = 32769);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
SHOW ivfflat.probes;
|
SHOW ivfflat.probes;
|
||||||
|
|
||||||
SET ivfflat.probes = 0;
|
SET ivfflat.probes = 0;
|
||||||
SET ivfflat.probes = 32769;
|
SET ivfflat.probes = 32769;
|
||||||
|
|
||||||
SHOW ivfflat.iterative_scan;
|
SHOW ivfflat.iterative_scan;
|
||||||
|
|
||||||
SET ivfflat.iterative_scan = on;
|
SET ivfflat.iterative_scan = on;
|
||||||
|
|
||||||
SHOW ivfflat.max_probes;
|
SHOW ivfflat.max_probes;
|
||||||
|
|
||||||
SET ivfflat.max_probes = 0;
|
SET ivfflat.max_probes = 0;
|
||||||
SET ivfflat.max_probes = 32769;
|
SET ivfflat.max_probes = 32769;
|
||||||
|
|
||||||
|
-- dimensions
|
||||||
|
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|
||||||
|
CREATE TABLE t (val vector(2001));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
|
||||||
|
-- memory
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '1MB';
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|
||||||
|
SET maintenance_work_mem = '5MB';
|
||||||
|
CREATE TABLE t (val vector(2000));
|
||||||
|
INSERT INTO t (val) VALUES (array_fill(0, ARRAY[2000]));
|
||||||
|
CREATE INDEX ON t USING ivfflat (val vector_l2_ops);
|
||||||
|
DROP TABLE t;
|
||||||
|
RESET maintenance_work_mem;
|
||||||
|
|||||||
38
test/t/046_hnsw_vacuum_scan.pl
Normal file
38
test/t/046_hnsw_vacuum_scan.pl
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings FATAL => 'all';
|
||||||
|
use PostgreSQL::Test::Cluster;
|
||||||
|
use PostgreSQL::Test::Utils;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $dim = 3;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = PostgreSQL::Test::Cluster->new('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table and index
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v vector($dim));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst (v) SELECT ARRAY[$array_sql] FROM generate_series(1, 1000) i;"
|
||||||
|
);
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v vector_l2_ops);");
|
||||||
|
$node->safe_psql("postgres", "DELETE FROM tst");
|
||||||
|
|
||||||
|
# Test HNSW_SCAN_LOCK at the beginning of MarkDeleted is effective
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=1000",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent SELECTs and VACUUM",
|
||||||
|
{
|
||||||
|
"046_hnsw_vacuum_scan_select\@1000" => "SELECT i FROM tst ORDER BY v <-> '[0,0,0]' LIMIT 10;",
|
||||||
|
"046_hnsw_vacuum_scan_vacuum\@1" => "VACUUM tst;"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
39
test/t/047_hnsw_vacuum_insert.pl
Normal file
39
test/t/047_hnsw_vacuum_insert.pl
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings FATAL => 'all';
|
||||||
|
use PostgreSQL::Test::Cluster;
|
||||||
|
use PostgreSQL::Test::Utils;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $dim = 3;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = PostgreSQL::Test::Cluster->new('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table and index
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v vector($dim));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst (v) SELECT ARRAY[$array_sql] FROM generate_series(1, 1000) i;"
|
||||||
|
);
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v vector_l2_ops);");
|
||||||
|
|
||||||
|
# Test no "hnsw graph not repaired" errors
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=1000",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs, DELETEs, SELECTs, and VACUUM",
|
||||||
|
{
|
||||||
|
"047_hnsw_vacuum_insert_insert\@500" => "INSERT INTO tst (v) VALUES (ARRAY[$array_sql]);",
|
||||||
|
"047_hnsw_vacuum_insert_delete\@500" => "DELETE FROM tst WHERE i = (SELECT i FROM tst LIMIT 1);",
|
||||||
|
"047_hnsw_vacuum_insert_select\@20" => "SELECT i FROM tst ORDER BY v <-> (SELECT ARRAY[$array_sql]::vector) LIMIT 10;",
|
||||||
|
"047_hnsw_vacuum_insert_vacuum\@1" => "VACUUM tst;"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
39
test/t/048_ivfflat_vacuum_insert.pl
Normal file
39
test/t/048_ivfflat_vacuum_insert.pl
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings FATAL => 'all';
|
||||||
|
use PostgreSQL::Test::Cluster;
|
||||||
|
use PostgreSQL::Test::Utils;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $dim = 3;
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = PostgreSQL::Test::Cluster->new('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table and index
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v vector($dim));");
|
||||||
|
$node->safe_psql("postgres", "ALTER TABLE tst SET (autovacuum_enabled = false);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst (v) SELECT ARRAY[$array_sql] FROM generate_series(1, 1000) i;"
|
||||||
|
);
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v vector_l2_ops) WITH (lists = 10);");
|
||||||
|
|
||||||
|
# Test no errors
|
||||||
|
$node->pgbench(
|
||||||
|
"--no-vacuum --client=5 --transactions=1500",
|
||||||
|
0,
|
||||||
|
[qr{actually processed}],
|
||||||
|
[qr{^$}],
|
||||||
|
"concurrent INSERTs, DELETEs, SELECTs, and VACUUM",
|
||||||
|
{
|
||||||
|
"048_ivfflat_vacuum_insert_insert\@500" => "INSERT INTO tst (v) VALUES (ARRAY[$array_sql]);",
|
||||||
|
"048_ivfflat_vacuum_insert_delete\@500" => "DELETE FROM tst WHERE i = (SELECT i FROM tst LIMIT 1);",
|
||||||
|
"048_ivfflat_vacuum_insert_select\@500" => "SELECT i FROM tst ORDER BY v <-> (SELECT ARRAY[$array_sql]::vector) LIMIT 10;",
|
||||||
|
"048_ivfflat_vacuum_insert_vacuum\@1" => "VACUUM tst;"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
done_testing();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
comment = 'vector data type and ivfflat and hnsw access methods'
|
comment = 'vector data type and ivfflat and hnsw access methods'
|
||||||
default_version = '0.8.2'
|
default_version = '0.8.5'
|
||||||
module_pathname = '$libdir/vector'
|
module_pathname = '$libdir/vector'
|
||||||
relocatable = true
|
relocatable = true
|
||||||
|
|||||||
Reference in New Issue
Block a user