mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 12:07:34 +08:00
Compare commits
9 Commits
v0.6.0
...
hnsw-fast-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7b6be73e1 | ||
|
|
d801a843f4 | ||
|
|
1458c7bb2a | ||
|
|
cad48d9203 | ||
|
|
719b4b7436 | ||
|
|
fa0acbf62d | ||
|
|
1612b84069 | ||
|
|
2f9371516d | ||
|
|
9d3e4e74df |
12
.github/workflows/build.yml
vendored
12
.github/workflows/build.yml
vendored
@@ -20,6 +20,8 @@ jobs:
|
|||||||
os: ubuntu-20.04
|
os: ubuntu-20.04
|
||||||
- postgres: 12
|
- postgres: 12
|
||||||
os: ubuntu-20.04
|
os: ubuntu-20.04
|
||||||
|
- postgres: 11
|
||||||
|
os: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
@@ -57,9 +59,9 @@ jobs:
|
|||||||
- run: |
|
- run: |
|
||||||
brew install cpanm
|
brew install cpanm
|
||||||
cpanm --notest IPC::Run
|
cpanm --notest IPC::Run
|
||||||
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_10.tar.gz
|
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz
|
||||||
tar xf REL_14_10.tar.gz
|
tar xf REL_14_5.tar.gz
|
||||||
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_10/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
|
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
|
||||||
- run: make clean && /usr/local/opt/llvm@15/bin/scan-build --status-bugs make PG_CFLAGS="-DUSE_ASSERT_CHECKING"
|
- run: make clean && /usr/local/opt/llvm@15/bin/scan-build --status-bugs make PG_CFLAGS="-DUSE_ASSERT_CHECKING"
|
||||||
windows:
|
windows:
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
@@ -81,10 +83,10 @@ 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
|
||||||
container:
|
container:
|
||||||
image: debian:12
|
image: debian:11
|
||||||
options: --platform linux/386
|
options: --platform linux/386
|
||||||
steps:
|
steps:
|
||||||
- run: apt-get update && apt-get install -y build-essential git libipc-run-perl postgresql-15 postgresql-server-dev-15 sudo
|
- run: apt-get update && apt-get install -y build-essential git libipc-run-perl postgresql-13 postgresql-server-dev-13 sudo
|
||||||
- run: service postgresql start
|
- run: service postgresql start
|
||||||
- run: |
|
- run: |
|
||||||
git clone https://github.com/${{ github.repository }}.git pgvector
|
git clone https://github.com/${{ github.repository }}.git pgvector
|
||||||
|
|||||||
18
CHANGELOG.md
18
CHANGELOG.md
@@ -1,18 +1,10 @@
|
|||||||
## 0.6.0 (2024-01-29)
|
## 0.5.2 (unreleased)
|
||||||
|
|
||||||
If upgrading with Postgres 12 or Docker, see [these notes](https://github.com/pgvector/pgvector#060).
|
|
||||||
|
|
||||||
- Changed storage for vector from `extended` to `external`
|
|
||||||
- Added support for parallel index builds for HNSW
|
|
||||||
- Added validation for GUC parameters
|
|
||||||
- Improved performance of HNSW
|
- Improved performance of HNSW
|
||||||
|
- Added support for parallel index builds for HNSW
|
||||||
- Reduced memory usage for HNSW index builds
|
- Reduced memory usage for HNSW index builds
|
||||||
- Reduced WAL generation for HNSW index builds
|
- Reduced WAL generation for HNSW index builds
|
||||||
- Fixed error with logical replication
|
- Fixed `invalid memory alloc request size` error with HNSW index build
|
||||||
- Fixed `invalid memory alloc request size` error with HNSW index builds
|
|
||||||
- Moved Docker image to `pgvector` org
|
|
||||||
- Added Docker tags for each supported version of Postgres
|
|
||||||
- Dropped support for Postgres 11
|
|
||||||
|
|
||||||
## 0.5.1 (2023-10-10)
|
## 0.5.1 (2023-10-10)
|
||||||
|
|
||||||
@@ -60,7 +52,7 @@ If upgrading with Postgres 12 or Docker, see [these notes](https://github.com/pg
|
|||||||
|
|
||||||
## 0.4.0 (2023-01-11)
|
## 0.4.0 (2023-01-11)
|
||||||
|
|
||||||
If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgvector/blob/v0.4.0/README.md#040).
|
If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgvector#040).
|
||||||
|
|
||||||
- Changed text representation for vector elements to match `real`
|
- Changed text representation for vector elements to match `real`
|
||||||
- Changed storage for vector from `plain` to `extended`
|
- Changed storage for vector from `plain` to `extended`
|
||||||
@@ -77,7 +69,7 @@ If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgv
|
|||||||
|
|
||||||
## 0.3.1 (2022-11-02)
|
## 0.3.1 (2022-11-02)
|
||||||
|
|
||||||
If upgrading from 0.2.7 or 0.3.0, [recreate](https://github.com/pgvector/pgvector/blob/v0.3.1/README.md#031) all `ivfflat` indexes after upgrading to ensure all data is indexed.
|
If upgrading from 0.2.7 or 0.3.0, [recreate](https://github.com/pgvector/pgvector#031) all `ivfflat` indexes after upgrading to ensure all data is indexed.
|
||||||
|
|
||||||
- Fixed issue with inserts silently corrupting `ivfflat` indexes (introduced in 0.2.7)
|
- Fixed issue with inserts silently corrupting `ivfflat` indexes (introduced in 0.2.7)
|
||||||
- Fixed segmentation fault with index creation when lists > 6500
|
- Fixed segmentation fault with index creation when lists > 6500
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
ARG PG_MAJOR=16
|
ARG PG_MAJOR=15
|
||||||
FROM postgres:$PG_MAJOR
|
FROM postgres:$PG_MAJOR
|
||||||
ARG PG_MAJOR
|
ARG PG_MAJOR
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"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.6.0",
|
"version": "0.5.1",
|
||||||
"maintainer": [
|
"maintainer": [
|
||||||
"Andrew Kane <andrew@ankane.org>"
|
"Andrew Kane <andrew@ankane.org>"
|
||||||
],
|
],
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
"prereqs": {
|
"prereqs": {
|
||||||
"runtime": {
|
"runtime": {
|
||||||
"requires": {
|
"requires": {
|
||||||
"PostgreSQL": "12.0.0"
|
"PostgreSQL": "11.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"vector": {
|
"vector": {
|
||||||
"file": "sql/vector.sql",
|
"file": "sql/vector.sql",
|
||||||
"docfile": "README.md",
|
"docfile": "README.md",
|
||||||
"version": "0.6.0",
|
"version": "0.5.1",
|
||||||
"abstract": "Open-source vector similarity search for Postgres"
|
"abstract": "Open-source vector similarity search for Postgres"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
12
Makefile
12
Makefile
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.0
|
EXTVERSION = 0.5.1
|
||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
@@ -65,17 +65,13 @@ dist:
|
|||||||
mkdir -p dist
|
mkdir -p dist
|
||||||
git archive --format zip --prefix=$(EXTENSION)-$(EXTVERSION)/ --output dist/$(EXTENSION)-$(EXTVERSION).zip master
|
git archive --format zip --prefix=$(EXTENSION)-$(EXTVERSION)/ --output dist/$(EXTENSION)-$(EXTVERSION).zip master
|
||||||
|
|
||||||
# for Docker
|
|
||||||
PG_MAJOR ?= 16
|
|
||||||
|
|
||||||
.PHONY: docker
|
.PHONY: docker
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
docker build --pull --no-cache --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(PG_MAJOR) .
|
docker build --pull --no-cache --platform linux/amd64 -t ankane/pgvector:latest .
|
||||||
docker build --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:$(EXTVERSION)-pg$(PG_MAJOR) .
|
|
||||||
|
|
||||||
.PHONY: docker-release
|
.PHONY: docker-release
|
||||||
|
|
||||||
docker-release:
|
docker-release:
|
||||||
docker buildx build --push --pull --no-cache --platform linux/amd64,linux/arm64 --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(PG_MAJOR) .
|
docker buildx build --push --pull --no-cache --platform linux/amd64,linux/arm64 -t ankane/pgvector:latest .
|
||||||
docker buildx build --push --platform linux/amd64,linux/arm64 --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:$(EXTVERSION)-pg$(PG_MAJOR) .
|
docker buildx build --push --platform linux/amd64,linux/arm64 -t ankane/pgvector:v$(EXTVERSION) .
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.0
|
EXTVERSION = 0.5.1
|
||||||
|
|
||||||
OBJS = 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\vector.obj
|
OBJS = 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\vector.obj
|
||||||
HEADERS = src\vector.h
|
HEADERS = src\vector.h
|
||||||
|
|||||||
134
README.md
134
README.md
@@ -14,13 +14,11 @@ Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recove
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Linux and Mac
|
|
||||||
|
|
||||||
Compile and install the extension (supports Postgres 11+)
|
Compile and install the extension (supports Postgres 11+)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone --branch v0.6.0 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
make
|
make
|
||||||
make install # may need sudo
|
make install # may need sudo
|
||||||
@@ -30,28 +28,6 @@ See the [installation notes](#installation-notes) if you run into issues
|
|||||||
|
|
||||||
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres). There are also instructions for [GitHub Actions](https://github.com/pgvector/setup-pgvector).
|
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres). There are also instructions for [GitHub Actions](https://github.com/pgvector/setup-pgvector).
|
||||||
|
|
||||||
### Windows
|
|
||||||
|
|
||||||
Ensure [C++ support in Visual Studio](https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170#download-and-install-the-tools) is installed, and run:
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
|
|
||||||
```
|
|
||||||
|
|
||||||
Note: The exact path will vary depending on your Visual Studio version and edition
|
|
||||||
|
|
||||||
Then use `nmake` to build:
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
|
||||||
git clone --branch v0.6.0 https://github.com/pgvector/pgvector.git
|
|
||||||
cd pgvector
|
|
||||||
nmake /F Makefile.win
|
|
||||||
nmake /F Makefile.win install
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also install it with [Docker](#docker) or [conda-forge](#conda-forge).
|
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
Enable the extension (do this once in each database where you want to use it)
|
Enable the extension (do this once in each database where you want to use it)
|
||||||
@@ -264,14 +240,6 @@ HINT: Increase maintenance_work_mem to speed up builds.
|
|||||||
|
|
||||||
Note: Do not set `maintenance_work_mem` so high that it exhausts the memory on the server
|
Note: Do not set `maintenance_work_mem` so high that it exhausts the memory on the server
|
||||||
|
|
||||||
Starting with 0.6.0, you can also speed up index creation by increasing the number of parallel workers (2 by default)
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SET max_parallel_maintenance_workers = 7; -- plus leader
|
|
||||||
```
|
|
||||||
|
|
||||||
For a large number of workers, you may also need to increase `max_parallel_workers` (8 by default)
|
|
||||||
|
|
||||||
### Indexing Progress
|
### Indexing Progress
|
||||||
|
|
||||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||||
@@ -336,16 +304,6 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Index Build Time
|
|
||||||
|
|
||||||
Speed up index creation on large tables by increasing the number of parallel workers (2 by default)
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SET max_parallel_maintenance_workers = 7; -- plus leader
|
|
||||||
```
|
|
||||||
|
|
||||||
For a large number of workers, you may also need to increase `max_parallel_workers` (8 by default)
|
|
||||||
|
|
||||||
### Indexing Progress
|
### Indexing Progress
|
||||||
|
|
||||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||||
@@ -614,7 +572,7 @@ sum(vector) → vector | sum | 0.5.0
|
|||||||
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
|
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
export PG_CONFIG=/Library/PostgreSQL/16/bin/pg_config
|
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
|
||||||
```
|
```
|
||||||
|
|
||||||
Then re-run the installation instructions (run `make clean` before `make` if needed). If `sudo` is needed for `make install`, use:
|
Then re-run the installation instructions (run `make clean` before `make` if needed). If `sudo` is needed for `make install`, use:
|
||||||
@@ -623,14 +581,6 @@ Then re-run the installation instructions (run `make clean` before `make` if nee
|
|||||||
sudo --preserve-env=PG_CONFIG make install
|
sudo --preserve-env=PG_CONFIG make install
|
||||||
```
|
```
|
||||||
|
|
||||||
A few common paths on Mac are:
|
|
||||||
|
|
||||||
- EDB installer - `/Library/PostgreSQL/16/bin/pg_config`
|
|
||||||
- Homebrew (arm64) - `/opt/homebrew/opt/postgresql@16/bin/pg_config`
|
|
||||||
- Homebrew (x86-64) - `/usr/local/opt/postgresql@16/bin/pg_config`
|
|
||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
|
||||||
|
|
||||||
### Missing Header
|
### Missing Header
|
||||||
|
|
||||||
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
|
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
|
||||||
@@ -643,18 +593,34 @@ sudo apt install postgresql-server-dev-16
|
|||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `16` with your Postgres server version
|
||||||
|
|
||||||
### Missing SDK
|
### Windows
|
||||||
|
|
||||||
If compilation fails and the output includes `warning: no such sysroot directory` on Mac, reinstall Xcode Command Line Tools.
|
Support for Windows is currently experimental. Ensure [C++ support in Visual Studio](https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170#download-and-install-the-tools) is installed, and run:
|
||||||
|
|
||||||
|
```cmd
|
||||||
|
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: The exact path will vary depending on your Visual Studio version and edition
|
||||||
|
|
||||||
|
Then use `nmake` to build:
|
||||||
|
|
||||||
|
```cmd
|
||||||
|
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
||||||
|
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||||
|
cd pgvector
|
||||||
|
nmake /F Makefile.win
|
||||||
|
nmake /F Makefile.win install
|
||||||
|
```
|
||||||
|
|
||||||
## Additional Installation Methods
|
## Additional Installation Methods
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
|
|
||||||
Get the [Docker image](https://hub.docker.com/r/pgvector/pgvector) with:
|
Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker pull pgvector/pgvector:pg16
|
docker pull ankane/pgvector
|
||||||
```
|
```
|
||||||
|
|
||||||
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (run it the same way).
|
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (run it the same way).
|
||||||
@@ -662,9 +628,9 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
|||||||
You can also build the image manually:
|
You can also build the image manually:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone --branch v0.6.0 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
docker build --build-arg PG_MAJOR=16 -t myuser/pgvector .
|
docker build --build-arg PG_MAJOR=15 -t myuser/pgvector .
|
||||||
```
|
```
|
||||||
|
|
||||||
### Homebrew
|
### Homebrew
|
||||||
@@ -741,32 +707,28 @@ SELECT extversion FROM pg_extension WHERE extname = 'vector';
|
|||||||
|
|
||||||
## Upgrade Notes
|
## Upgrade Notes
|
||||||
|
|
||||||
### 0.6.0
|
### 0.4.0
|
||||||
|
|
||||||
#### Postgres 12
|
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
|
||||||
|
|
||||||
If upgrading with Postgres 12, remove this line from `sql/vector--0.5.1--0.6.0.sql`:
|
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
ALTER TYPE vector SET (STORAGE = external);
|
ALTER TYPE vector SET (STORAGE = extended);
|
||||||
```
|
```
|
||||||
|
|
||||||
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
|
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
|
||||||
|
|
||||||
#### Docker
|
### 0.3.1
|
||||||
|
|
||||||
The Docker image is now published in the `pgvector` org, and there are tags for each supported version of Postgres (rather than a `latest` tag).
|
If upgrading from 0.2.7 or 0.3.0, recreate all `ivfflat` indexes after upgrading to ensure all data is indexed.
|
||||||
|
|
||||||
```sh
|
```sql
|
||||||
docker pull pgvector/pgvector:pg16
|
-- Postgres 12+
|
||||||
# or
|
REINDEX INDEX CONCURRENTLY index_name;
|
||||||
docker pull pgvector/pgvector:0.6.0-pg16
|
|
||||||
```
|
|
||||||
|
|
||||||
Also, if you’ve increased `maintenance_work_mem`, make sure `--shm-size` is at least that size to avoid an error with parallel HNSW index builds.
|
-- Postgres < 12
|
||||||
|
CREATE INDEX CONCURRENTLY temp_name ON table USING ivfflat (column opclass);
|
||||||
```sh
|
DROP INDEX CONCURRENTLY index_name;
|
||||||
docker run --shm-size=1g ...
|
ALTER INDEX temp_name RENAME TO index_name;
|
||||||
```
|
```
|
||||||
|
|
||||||
## Thanks
|
## Thanks
|
||||||
@@ -812,32 +774,14 @@ make prove_installcheck # TAP tests
|
|||||||
To run single tests:
|
To run single tests:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make installcheck REGRESS=functions # regression test
|
make installcheck REGRESS=functions # regression test
|
||||||
make prove_installcheck PROVE_TESTS=test/t/001_ivfflat_wal.pl # TAP test
|
make prove_installcheck PROVE_TESTS=test/t/001_wal.pl # TAP test
|
||||||
```
|
```
|
||||||
|
|
||||||
To enable benchmarking:
|
To enable benchmarking:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make clean && PG_CFLAGS="-DIVFFLAT_BENCH" make && make install
|
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
|
||||||
```
|
|
||||||
|
|
||||||
To show memory usage:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DHNSW_MEMORY -DIVFFLAT_MEMORY" make && make install
|
|
||||||
```
|
|
||||||
|
|
||||||
To enable assertions:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DUSE_ASSERT_CHECKING" make && make install
|
|
||||||
```
|
|
||||||
|
|
||||||
To get k-means metrics:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DIVFFLAT_KMEANS_DEBUG" make && make install
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Resources for contributors
|
Resources for contributors
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
|
||||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.6.0'" to load this file. \quit
|
|
||||||
|
|
||||||
-- remove this single line for Postgres < 13
|
|
||||||
ALTER TYPE vector SET (STORAGE = external);
|
|
||||||
@@ -26,7 +26,7 @@ CREATE TYPE vector (
|
|||||||
TYPMOD_IN = vector_typmod_in,
|
TYPMOD_IN = vector_typmod_in,
|
||||||
RECEIVE = vector_recv,
|
RECEIVE = vector_recv,
|
||||||
SEND = vector_send,
|
SEND = vector_send,
|
||||||
STORAGE = external
|
STORAGE = extended
|
||||||
);
|
);
|
||||||
|
|
||||||
-- functions
|
-- functions
|
||||||
|
|||||||
20
src/hnsw.c
20
src/hnsw.c
@@ -4,15 +4,13 @@
|
|||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/amapi.h"
|
#include "access/amapi.h"
|
||||||
#include "access/reloptions.h"
|
|
||||||
#include "commands/progress.h"
|
|
||||||
#include "commands/vacuum.h"
|
#include "commands/vacuum.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "utils/guc.h"
|
#include "utils/guc.h"
|
||||||
#include "utils/selfuncs.h"
|
#include "utils/selfuncs.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 150000
|
#if PG_VERSION_NUM >= 120000
|
||||||
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
#include "commands/progress.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int hnsw_ef_search;
|
int hnsw_ef_search;
|
||||||
@@ -72,13 +70,12 @@ HnswInit(void)
|
|||||||
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
|
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
|
||||||
"Valid range is 1..1000.", &hnsw_ef_search,
|
"Valid range is 1..1000.", &hnsw_ef_search,
|
||||||
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
|
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||||
|
|
||||||
MarkGUCPrefixReserved("hnsw");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the name of index build phase
|
* Get the name of index build phase
|
||||||
*/
|
*/
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
static char *
|
static char *
|
||||||
hnswbuildphasename(int64 phasenum)
|
hnswbuildphasename(int64 phasenum)
|
||||||
{
|
{
|
||||||
@@ -92,6 +89,7 @@ hnswbuildphasename(int64 phasenum)
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Estimate the cost of an index scan
|
* Estimate the cost of an index scan
|
||||||
@@ -106,6 +104,9 @@ hnswcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
int m;
|
int m;
|
||||||
int entryLevel;
|
int entryLevel;
|
||||||
Relation index;
|
Relation index;
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
List *qinfos;
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Never use index without order */
|
/* Never use index without order */
|
||||||
if (path->indexorderbys == NULL)
|
if (path->indexorderbys == NULL)
|
||||||
@@ -131,7 +132,12 @@ hnswcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
/* Account for number of tuples (or entry level), m, and ef_search */
|
/* Account for number of tuples (or entry level), m, and ef_search */
|
||||||
costs.numIndexTuples = (entryLevel + 2) * m;
|
costs.numIndexTuples = (entryLevel + 2) * m;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
genericcostestimate(root, path, loop_count, &costs);
|
genericcostestimate(root, path, loop_count, &costs);
|
||||||
|
#else
|
||||||
|
qinfos = deconstruct_indexquals(path);
|
||||||
|
genericcostestimate(root, path, loop_count, qinfos, &costs);
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Use total cost since most work happens before first tuple is returned */
|
/* Use total cost since most work happens before first tuple is returned */
|
||||||
*indexStartupCost = costs.indexTotalCost;
|
*indexStartupCost = costs.indexTotalCost;
|
||||||
@@ -225,7 +231,9 @@ hnswhandler(PG_FUNCTION_ARGS)
|
|||||||
amroutine->amcostestimate = hnswcostestimate;
|
amroutine->amcostestimate = hnswcostestimate;
|
||||||
amroutine->amoptions = hnswoptions;
|
amroutine->amoptions = hnswoptions;
|
||||||
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
amroutine->ambuildphasename = hnswbuildphasename;
|
amroutine->ambuildphasename = hnswbuildphasename;
|
||||||
|
#endif
|
||||||
amroutine->amvalidate = hnswvalidate;
|
amroutine->amvalidate = hnswvalidate;
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
amroutine->amadjustmembers = NULL;
|
amroutine->amadjustmembers = NULL;
|
||||||
|
|||||||
37
src/hnsw.h
37
src/hnsw.h
@@ -3,17 +3,21 @@
|
|||||||
|
|
||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/genam.h"
|
#include "access/generic_xlog.h"
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "access/reloptions.h"
|
||||||
#include "nodes/execnodes.h"
|
#include "nodes/execnodes.h"
|
||||||
#include "port.h" /* for random() */
|
#include "port.h" /* for random() */
|
||||||
#include "utils/relptr.h"
|
#include "utils/relptr.h"
|
||||||
#include "utils/sampling.h"
|
#include "utils/sampling.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 110000
|
||||||
|
#error "Requires PostgreSQL 11+"
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 120000
|
#if PG_VERSION_NUM < 120000
|
||||||
#error "Requires PostgreSQL 12+"
|
#include "access/relscan.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define HNSW_MAX_DIM 2000
|
#define HNSW_MAX_DIM 2000
|
||||||
@@ -60,13 +64,10 @@
|
|||||||
#define PROGRESS_HNSW_PHASE_LOAD 2
|
#define PROGRESS_HNSW_PHASE_LOAD 2
|
||||||
|
|
||||||
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
||||||
#define HNSW_TUPLE_ALLOC_SIZE BLCKSZ
|
|
||||||
|
|
||||||
#define HNSW_ELEMENT_TUPLE_SIZE(size) MAXALIGN(offsetof(HnswElementTupleData, data) + (size))
|
#define HNSW_ELEMENT_TUPLE_SIZE(size) MAXALIGN(offsetof(HnswElementTupleData, data) + (size))
|
||||||
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
||||||
|
|
||||||
#define HNSW_NEIGHBOR_ARRAY_SIZE(lm) (offsetof(HnswNeighborArray, items) + sizeof(HnswCandidate) * (lm))
|
|
||||||
|
|
||||||
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
||||||
#define HnswPageGetMeta(page) ((HnswMetaPageData *) PageGetContents(page))
|
#define HnswPageGetMeta(page) ((HnswMetaPageData *) PageGetContents(page))
|
||||||
|
|
||||||
@@ -113,6 +114,8 @@
|
|||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
extern int hnsw_ef_search;
|
extern int hnsw_ef_search;
|
||||||
|
|
||||||
|
/* This is initialized when the module is loaded */
|
||||||
extern int hnsw_lock_tranche_id;
|
extern int hnsw_lock_tranche_id;
|
||||||
|
|
||||||
typedef struct HnswElementData HnswElementData;
|
typedef struct HnswElementData HnswElementData;
|
||||||
@@ -197,12 +200,20 @@ typedef struct HnswGraph
|
|||||||
bool flushed;
|
bool flushed;
|
||||||
} HnswGraph;
|
} HnswGraph;
|
||||||
|
|
||||||
|
typedef struct HnswSpool
|
||||||
|
{
|
||||||
|
Relation heap;
|
||||||
|
Relation index;
|
||||||
|
} HnswSpool;
|
||||||
|
|
||||||
typedef struct HnswShared
|
typedef struct HnswShared
|
||||||
{
|
{
|
||||||
/* Immutable state */
|
/* Immutable state */
|
||||||
Oid heaprelid;
|
Oid heaprelid;
|
||||||
Oid indexrelid;
|
Oid indexrelid;
|
||||||
bool isconcurrent;
|
bool isconcurrent;
|
||||||
|
int scantuplesortstates;
|
||||||
|
dsa_pointer dsaptr;
|
||||||
|
|
||||||
/* Worker progress */
|
/* Worker progress */
|
||||||
ConditionVariable workersdonecv;
|
ConditionVariable workersdonecv;
|
||||||
@@ -214,10 +225,16 @@ typedef struct HnswShared
|
|||||||
int nparticipantsdone;
|
int nparticipantsdone;
|
||||||
double reltuples;
|
double reltuples;
|
||||||
HnswGraph graphData;
|
HnswGraph graphData;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
ParallelHeapScanDescData heapdesc; /* must come last */
|
||||||
|
#endif
|
||||||
} HnswShared;
|
} HnswShared;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
#define ParallelTableScanFromHnswShared(shared) \
|
#define ParallelTableScanFromHnswShared(shared) \
|
||||||
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(HnswShared)))
|
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(HnswShared)))
|
||||||
|
#endif
|
||||||
|
|
||||||
typedef struct HnswLeader
|
typedef struct HnswLeader
|
||||||
{
|
{
|
||||||
@@ -376,18 +393,18 @@ 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, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing);
|
void HnswInsertElement(char *base, HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing);
|
||||||
HnswCandidate *HnswEntryCandidate(char *base, HnswElement em, Datum q, Relation rel, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
HnswCandidate *HnswEntryCandidate(char *base, HnswElement em, Datum q, Relation rel, FmgrInfo *procinfo, Oid collation, 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);
|
||||||
void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
|
void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
|
||||||
void HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * alloc);
|
void HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * alloc);
|
||||||
bool HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building);
|
bool HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel, bool building);
|
||||||
void HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building);
|
void HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building);
|
||||||
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
|
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
|
||||||
void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
||||||
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element);
|
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element);
|
||||||
void HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
void HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
||||||
void HnswLoadNeighbors(HnswElement element, Relation index, int m);
|
void HnswLoadNeighbors(HnswElement element, Relation index, int m);
|
||||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
||||||
|
|
||||||
|
|||||||
372
src/hnswbuild.c
372
src/hnswbuild.c
@@ -1,53 +1,14 @@
|
|||||||
/*
|
|
||||||
* The HNSW build happens in two phases:
|
|
||||||
*
|
|
||||||
* 1. In-memory phase
|
|
||||||
*
|
|
||||||
* In this first phase, the graph is held completely in memory. When the graph
|
|
||||||
* is fully built, or we run out of memory reserved for the build (determined
|
|
||||||
* by maintenance_work_mem), we materialize the graph to disk (see
|
|
||||||
* FlushPages()), and switch to the on-disk phase.
|
|
||||||
*
|
|
||||||
* In a parallel build, a large contiguous chunk of shared memory is allocated
|
|
||||||
* to hold the graph. Each worker process has its own HnswBuildState struct in
|
|
||||||
* private memory, which contains information that doesn't change throughout
|
|
||||||
* the build, and pointers to the shared structs in shared memory. The shared
|
|
||||||
* memory area is mapped to a different address in each worker process, and
|
|
||||||
* 'HnswBuildState.hnswarea' points to the beginning of the shared area in the
|
|
||||||
* worker process's address space. All pointers used in the graph are
|
|
||||||
* "relative pointers", stored as an offset from 'hnswarea'.
|
|
||||||
*
|
|
||||||
* Each element is protected by an LWLock. It must be held when reading or
|
|
||||||
* modifying the element's neighbors or 'heaptids'.
|
|
||||||
*
|
|
||||||
* In a non-parallel build, the graph is held in backend-private memory. All
|
|
||||||
* the elements are allocated in a dedicated memory context, 'graphCtx', and
|
|
||||||
* the pointers used in the graph are regular pointers.
|
|
||||||
*
|
|
||||||
* 2. On-disk phase
|
|
||||||
*
|
|
||||||
* In the on-disk phase, the index is built by inserting each vector to the
|
|
||||||
* index one by one, just like on INSERT. The only difference is that we don't
|
|
||||||
* WAL-log the individual inserts. If the graph fit completely in memory and
|
|
||||||
* was fully built in the in-memory phase, the on-disk phase is skipped.
|
|
||||||
*
|
|
||||||
* After we have finished building the graph, we perform one more scan through
|
|
||||||
* the index and write all the pages to the WAL.
|
|
||||||
*/
|
|
||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "access/table.h"
|
|
||||||
#include "access/tableam.h"
|
|
||||||
#include "access/xact.h"
|
#include "access/xact.h"
|
||||||
#include "access/xloginsert.h"
|
|
||||||
#include "catalog/index.h"
|
#include "catalog/index.h"
|
||||||
#include "commands/progress.h"
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "optimizer/optimizer.h"
|
#include "lib/pairingheap.h"
|
||||||
|
#include "nodes/pg_list.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
#include "tcop/tcopprot.h"
|
||||||
#include "utils/datum.h"
|
#include "utils/datum.h"
|
||||||
@@ -55,21 +16,43 @@
|
|||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_progress.h"
|
#include "utils/backend_progress.h"
|
||||||
#else
|
#elif PG_VERSION_NUM >= 120000
|
||||||
#include "pgstat.h"
|
#include "pgstat.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "access/tableam.h"
|
||||||
|
#include "commands/progress.h"
|
||||||
|
#else
|
||||||
|
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
#define CALLBACK_ITEM_POINTER ItemPointer tid
|
#define CALLBACK_ITEM_POINTER ItemPointer tid
|
||||||
#else
|
#else
|
||||||
#define CALLBACK_ITEM_POINTER HeapTuple hup
|
#define CALLBACK_ITEM_POINTER HeapTuple hup
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#define UpdateProgress(index, val) pgstat_progress_update_param(index, val)
|
||||||
|
#else
|
||||||
|
#define UpdateProgress(index, val) ((void)val)
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_status.h"
|
#include "utils/backend_status.h"
|
||||||
#include "utils/wait_event.h"
|
#include "utils/wait_event.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "access/table.h"
|
||||||
|
#include "optimizer/optimizer.h"
|
||||||
|
#else
|
||||||
|
#include "access/heapam.h"
|
||||||
|
#include "optimizer/planner.h"
|
||||||
|
#include "pgstat.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
||||||
#define PARALLEL_KEY_HNSW_AREA UINT64CONST(0xA000000000000002)
|
#define PARALLEL_KEY_HNSW_AREA UINT64CONST(0xA000000000000002)
|
||||||
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000003)
|
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000003)
|
||||||
@@ -141,13 +124,14 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, ForkNumber forkNum)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create graph pages
|
* Create element pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
CreateGraphPages(HnswBuildState * buildstate)
|
CreateElementPages(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
|
Size etupAllocSize;
|
||||||
Size maxSize;
|
Size maxSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
@@ -159,11 +143,12 @@ CreateGraphPages(HnswBuildState * buildstate)
|
|||||||
char *base = buildstate->hnswarea;
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
|
etupAllocSize = BLCKSZ;
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = HNSW_MAX_SIZE;
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
etup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
etup = palloc0(etupAllocSize);
|
||||||
ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
ntup = palloc0(BLCKSZ);
|
||||||
|
|
||||||
/* Prepare first page */
|
/* Prepare first page */
|
||||||
buf = HnswNewBuffer(index, forkNum);
|
buf = HnswNewBuffer(index, forkNum);
|
||||||
@@ -182,7 +167,7 @@ CreateGraphPages(HnswBuildState * buildstate)
|
|||||||
iter = element->next;
|
iter = element->next;
|
||||||
|
|
||||||
/* Zero memory for each element */
|
/* Zero memory for each element */
|
||||||
MemSet(etup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
MemSet(etup, 0, etupAllocSize);
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(valuePtr));
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(valuePtr));
|
||||||
@@ -190,7 +175,7 @@ CreateGraphPages(HnswBuildState * buildstate)
|
|||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* Initial size check */
|
/* Initial size check */
|
||||||
if (etupSize > HNSW_TUPLE_ALLOC_SIZE)
|
if (etupSize > etupAllocSize)
|
||||||
elog(ERROR, "index tuple too large");
|
elog(ERROR, "index tuple too large");
|
||||||
|
|
||||||
HnswSetElementTuple(base, etup, element);
|
HnswSetElementTuple(base, etup, element);
|
||||||
@@ -242,10 +227,10 @@ CreateGraphPages(HnswBuildState * buildstate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Write neighbor tuples
|
* Create neighbor pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteNeighborTuples(HnswBuildState * buildstate)
|
CreateNeighborPages(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
@@ -255,32 +240,29 @@ WriteNeighborTuples(HnswBuildState * buildstate)
|
|||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
ntup = palloc0(BLCKSZ);
|
||||||
|
|
||||||
while (!HnswPtrIsNull(base, iter))
|
while (!HnswPtrIsNull(base, iter))
|
||||||
{
|
{
|
||||||
HnswElement element = HnswPtrAccess(base, iter);
|
HnswElement e = HnswPtrAccess(base, iter);
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, m);
|
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||||
|
|
||||||
/* Update iterator */
|
/* Update iterator */
|
||||||
iter = element->next;
|
iter = e->next;
|
||||||
|
|
||||||
/* Zero memory for each element */
|
|
||||||
MemSet(ntup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
|
||||||
|
|
||||||
/* Can take a while, so ensure we can interrupt */
|
/* Can take a while, so ensure we can interrupt */
|
||||||
/* Needs to be called when no buffer locks are held */
|
/* Needs to be called when no buffer locks are held */
|
||||||
CHECK_FOR_INTERRUPTS();
|
CHECK_FOR_INTERRUPTS();
|
||||||
|
|
||||||
buf = ReadBufferExtended(index, forkNum, element->neighborPage, RBM_NORMAL, NULL);
|
buf = ReadBufferExtended(index, forkNum, e->neighborPage, RBM_NORMAL, NULL);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
page = BufferGetPage(buf);
|
page = BufferGetPage(buf);
|
||||||
|
|
||||||
HnswSetNeighborTuple(base, ntup, element, m);
|
HnswSetNeighborTuple(base, ntup, e, m);
|
||||||
|
|
||||||
if (!PageIndexTupleOverwrite(page, element->neighborOffno, (Item) ntup, ntupSize))
|
if (!PageIndexTupleOverwrite(page, e->neighborOffno, (Item) ntup, ntupSize))
|
||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
@@ -302,8 +284,8 @@ FlushPages(HnswBuildState * buildstate)
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
CreateMetaPage(buildstate);
|
CreateMetaPage(buildstate);
|
||||||
CreateGraphPages(buildstate);
|
CreateElementPages(buildstate);
|
||||||
WriteNeighborTuples(buildstate);
|
CreateNeighborPages(buildstate);
|
||||||
|
|
||||||
buildstate->graph->flushed = true;
|
buildstate->graph->flushed = true;
|
||||||
MemoryContextReset(buildstate->graphCtx);
|
MemoryContextReset(buildstate->graphCtx);
|
||||||
@@ -313,7 +295,7 @@ FlushPages(HnswBuildState * buildstate)
|
|||||||
* Add a heap TID to an existing element
|
* Add a heap TID to an existing element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
AddDuplicateInMemory(HnswElement element, HnswElement dup)
|
HnswAddDuplicateInMemory(HnswElement element, HnswElement dup)
|
||||||
{
|
{
|
||||||
LWLockAcquire(&dup->lock, LW_EXCLUSIVE);
|
LWLockAcquire(&dup->lock, LW_EXCLUSIVE);
|
||||||
|
|
||||||
@@ -334,15 +316,15 @@ AddDuplicateInMemory(HnswElement element, HnswElement dup)
|
|||||||
* Find duplicate element
|
* Find duplicate element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
FindDuplicateInMemory(char *base, HnswElement element)
|
HnswFindDuplicateInMemory(char *base, HnswElement element)
|
||||||
{
|
{
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
||||||
Datum value = HnswGetValue(base, element);
|
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
{
|
{
|
||||||
HnswCandidate *neighbor = &neighbors->items[i];
|
HnswCandidate *neighbor = &neighbors->items[i];
|
||||||
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
||||||
|
Datum value = HnswGetValue(base, element);
|
||||||
Datum neighborValue = HnswGetValue(base, neighborElement);
|
Datum neighborValue = HnswGetValue(base, neighborElement);
|
||||||
|
|
||||||
/* Exit early since ordered by distance */
|
/* Exit early since ordered by distance */
|
||||||
@@ -350,7 +332,7 @@ FindDuplicateInMemory(char *base, HnswElement element)
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
/* Check for space */
|
/* Check for space */
|
||||||
if (AddDuplicateInMemory(element, neighborElement))
|
if (HnswAddDuplicateInMemory(element, neighborElement))
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -358,10 +340,10 @@ FindDuplicateInMemory(char *base, HnswElement element)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add to element list
|
* Add to element and neighbor pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
AddElementInMemory(char *base, HnswGraph * graph, HnswElement element)
|
WriteNewElementPagesInMemory(char *base, HnswGraph * graph, HnswElement element)
|
||||||
{
|
{
|
||||||
SpinLockAcquire(&graph->lock);
|
SpinLockAcquire(&graph->lock);
|
||||||
element->next = graph->head;
|
element->next = graph->head;
|
||||||
@@ -373,7 +355,7 @@ AddElementInMemory(char *base, HnswGraph * graph, HnswElement element)
|
|||||||
* Update neighbors
|
* Update neighbors
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
UpdateNeighborsInMemory(char *base, FmgrInfo *procinfo, Oid collation, HnswElement e, int m)
|
HnswUpdateNeighborPagesInMemory(char *base, FmgrInfo *procinfo, Oid collation, HnswElement e, int m)
|
||||||
{
|
{
|
||||||
for (int lc = e->level; lc >= 0; lc--)
|
for (int lc = e->level; lc >= 0; lc--)
|
||||||
{
|
{
|
||||||
@@ -397,82 +379,45 @@ UpdateNeighborsInMemory(char *base, FmgrInfo *procinfo, Oid collation, HnswEleme
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Update graph in memory
|
* Write changes in memory
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
UpdateGraphInMemory(FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, HnswBuildState * buildstate)
|
WriteElementInMemory(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, HnswBuildState * buildstate, HnswGraph * graph, bool updateEntryPoint)
|
||||||
{
|
{
|
||||||
HnswGraph *graph = buildstate->graph;
|
|
||||||
char *base = buildstate->hnswarea;
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
/* Look for duplicate */
|
/* Try to add to existing page */
|
||||||
if (FindDuplicateInMemory(base, element))
|
if (HnswFindDuplicateInMemory(base, element))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Add element */
|
/* Write element and neighbor tuples */
|
||||||
AddElementInMemory(base, graph, element);
|
WriteNewElementPagesInMemory(base, graph, element);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
UpdateNeighborsInMemory(base, procinfo, collation, element, m);
|
HnswUpdateNeighborPagesInMemory(base, procinfo, collation, element, m);
|
||||||
|
|
||||||
/* Update entry point if needed (already have lock) */
|
/* Update entry point if needed (already have lock) */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (updateEntryPoint)
|
||||||
HnswPtrStore(base, graph->entryPoint, element);
|
HnswPtrStore(base, graph->entryPoint, element);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Insert tuple in memory
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
|
||||||
{
|
|
||||||
FmgrInfo *procinfo = buildstate->procinfo;
|
|
||||||
Oid collation = buildstate->collation;
|
|
||||||
HnswGraph *graph = buildstate->graph;
|
|
||||||
HnswElement entryPoint;
|
|
||||||
LWLock *entryLock = &graph->entryLock;
|
|
||||||
int efConstruction = buildstate->efConstruction;
|
|
||||||
int m = buildstate->m;
|
|
||||||
char *base = buildstate->hnswarea;
|
|
||||||
|
|
||||||
/* Get entry point */
|
|
||||||
LWLockAcquire(entryLock, LW_SHARED);
|
|
||||||
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
|
||||||
|
|
||||||
/* Prevent concurrent inserts when likely updating entry point */
|
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
|
||||||
{
|
|
||||||
/* Release shared lock */
|
|
||||||
LWLockRelease(entryLock);
|
|
||||||
|
|
||||||
/* Get exclusive lock */
|
|
||||||
LWLockAcquire(entryLock, LW_EXCLUSIVE);
|
|
||||||
|
|
||||||
/* Get latest entry point after lock is acquired */
|
|
||||||
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Find neighbors for element */
|
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
|
||||||
|
|
||||||
/* Update graph in memory */
|
|
||||||
UpdateGraphInMemory(procinfo, collation, element, m, efConstruction, entryPoint, buildstate);
|
|
||||||
|
|
||||||
/* Release entry lock */
|
|
||||||
LWLockRelease(entryLock);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Insert tuple
|
* Insert tuple
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, HnswBuildState * buildstate)
|
InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
|
FmgrInfo *procinfo = buildstate->procinfo;
|
||||||
|
Oid collation = buildstate->collation;
|
||||||
HnswGraph *graph = buildstate->graph;
|
HnswGraph *graph = buildstate->graph;
|
||||||
|
HnswElement entryPoint;
|
||||||
|
int efConstruction = buildstate->efConstruction;
|
||||||
|
int m = buildstate->m;
|
||||||
HnswElement element;
|
HnswElement element;
|
||||||
HnswAllocator *allocator = &buildstate->allocator;
|
HnswAllocator *allocator = &buildstate->allocator;
|
||||||
Size valueSize;
|
Size valueSize;
|
||||||
Pointer valuePtr;
|
Pointer valuePtr;
|
||||||
|
bool updateEntryPoint;
|
||||||
LWLock *flushLock = &graph->flushLock;
|
LWLock *flushLock = &graph->flushLock;
|
||||||
char *base = buildstate->hnswarea;
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
@@ -482,7 +427,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->normvec))
|
if (!HnswNormValue(buildstate->normprocinfo, collation, &value, buildstate->normvec))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -492,24 +437,17 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
/* Ensure graph not flushed when inserting */
|
/* Ensure graph not flushed when inserting */
|
||||||
LWLockAcquire(flushLock, LW_SHARED);
|
LWLockAcquire(flushLock, LW_SHARED);
|
||||||
|
|
||||||
/* Are we in the on-disk phase? */
|
|
||||||
if (graph->flushed)
|
if (graph->flushed)
|
||||||
{
|
{
|
||||||
LWLockRelease(flushLock);
|
LWLockRelease(flushLock);
|
||||||
|
|
||||||
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, true);
|
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, buildstate->heap, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/* Get lock for allocator */
|
||||||
* In a parallel build, the HnswElement is allocated from the shared
|
|
||||||
* memory area, so we need to coordinate with other processes.
|
|
||||||
*/
|
|
||||||
LWLockAcquire(&graph->allocatorLock, LW_EXCLUSIVE);
|
LWLockAcquire(&graph->allocatorLock, LW_EXCLUSIVE);
|
||||||
|
|
||||||
/*
|
/* Flush pages if needed */
|
||||||
* Check that we have enough memory available for the new element now that
|
|
||||||
* we have the allocator lock, and flush pages if needed.
|
|
||||||
*/
|
|
||||||
if (graph->memoryUsed >= graph->memoryTotal)
|
if (graph->memoryUsed >= graph->memoryTotal)
|
||||||
{
|
{
|
||||||
LWLockRelease(&graph->allocatorLock);
|
LWLockRelease(&graph->allocatorLock);
|
||||||
@@ -529,29 +467,41 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
|
|
||||||
LWLockRelease(flushLock);
|
LWLockRelease(flushLock);
|
||||||
|
|
||||||
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, true);
|
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, buildstate->heap, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Ok, we can proceed to allocate the element */
|
/* Create an element */
|
||||||
element = HnswInitElement(base, heaptid, buildstate->m, buildstate->ml, buildstate->maxLevel, allocator);
|
element = HnswInitElement(base, heaptid, buildstate->m, buildstate->ml, buildstate->maxLevel, allocator);
|
||||||
valuePtr = HnswAlloc(allocator, valueSize);
|
valuePtr = HnswAlloc(allocator, valueSize);
|
||||||
|
|
||||||
/*
|
/* Release allocator lock */
|
||||||
* We have now allocated the space needed for the element, so we don't
|
|
||||||
* need the allocator lock anymore. Release it and initialize the rest of
|
|
||||||
* the element.
|
|
||||||
*/
|
|
||||||
LWLockRelease(&graph->allocatorLock);
|
LWLockRelease(&graph->allocatorLock);
|
||||||
|
|
||||||
/* Copy the datum */
|
/* Copy datum */
|
||||||
memcpy(valuePtr, DatumGetPointer(value), valueSize);
|
memcpy(valuePtr, DatumGetPointer(value), valueSize);
|
||||||
HnswPtrStore(base, element->value, valuePtr);
|
HnswPtrStore(base, element->value, valuePtr);
|
||||||
|
|
||||||
/* Create a lock for the element */
|
/* Create element lock */
|
||||||
LWLockInitialize(&element->lock, hnsw_lock_tranche_id);
|
LWLockInitialize(&element->lock, hnsw_lock_tranche_id);
|
||||||
|
|
||||||
/* Insert tuple */
|
/* Get entry point */
|
||||||
InsertTupleInMemory(buildstate, element);
|
LWLockAcquire(&graph->entryLock, LW_EXCLUSIVE);
|
||||||
|
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
||||||
|
updateEntryPoint = entryPoint == NULL || element->level > entryPoint->level;
|
||||||
|
|
||||||
|
/* Release lock if not updating entry point */
|
||||||
|
if (!updateEntryPoint)
|
||||||
|
LWLockRelease(&graph->entryLock);
|
||||||
|
|
||||||
|
/* Insert element in graph */
|
||||||
|
HnswInsertElement(base, element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
|
/* Write to memory */
|
||||||
|
WriteElementInMemory(index, procinfo, collation, element, m, efConstruction, entryPoint, buildstate, graph, updateEntryPoint);
|
||||||
|
|
||||||
|
/* Release lock if needed */
|
||||||
|
if (updateEntryPoint)
|
||||||
|
LWLockRelease(&graph->entryLock);
|
||||||
|
|
||||||
/* Release flush lock */
|
/* Release flush lock */
|
||||||
LWLockRelease(flushLock);
|
LWLockRelease(flushLock);
|
||||||
@@ -586,7 +536,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
{
|
{
|
||||||
/* Update progress */
|
/* Update progress */
|
||||||
SpinLockAcquire(&graph->lock);
|
SpinLockAcquire(&graph->lock);
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE, ++graph->indtuples);
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++graph->indtuples);
|
||||||
SpinLockRelease(&graph->lock);
|
SpinLockRelease(&graph->lock);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -760,25 +710,36 @@ ParallelHeapScan(HnswBuildState * buildstate)
|
|||||||
* Perform a worker's portion of a parallel insert
|
* Perform a worker's portion of a parallel insert
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswParallelScanAndInsert(Relation heapRel, Relation indexRel, HnswShared * hnswshared, char *hnswarea, bool progress)
|
HnswParallelScanAndInsert(HnswSpool * hnswspool, HnswShared * hnswshared, char *hnswarea, bool progress)
|
||||||
{
|
{
|
||||||
HnswBuildState buildstate;
|
HnswBuildState buildstate;
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
TableScanDesc scan;
|
TableScanDesc scan;
|
||||||
|
#else
|
||||||
|
HeapScanDesc scan;
|
||||||
|
#endif
|
||||||
double reltuples;
|
double reltuples;
|
||||||
IndexInfo *indexInfo;
|
IndexInfo *indexInfo;
|
||||||
|
|
||||||
/* Join parallel scan */
|
/* Join parallel scan */
|
||||||
indexInfo = BuildIndexInfo(indexRel);
|
indexInfo = BuildIndexInfo(hnswspool->index);
|
||||||
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
||||||
InitBuildState(&buildstate, heapRel, indexRel, indexInfo, MAIN_FORKNUM);
|
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
||||||
buildstate.graph = &hnswshared->graphData;
|
buildstate.graph = &hnswshared->graphData;
|
||||||
buildstate.hnswarea = hnswarea;
|
buildstate.hnswarea = hnswarea;
|
||||||
InitAllocator(&buildstate.allocator, &HnswSharedMemoryAlloc, &buildstate);
|
InitAllocator(&buildstate.allocator, &HnswSharedMemoryAlloc, &buildstate);
|
||||||
scan = table_beginscan_parallel(heapRel,
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
scan = table_beginscan_parallel(hnswspool->heap,
|
||||||
ParallelTableScanFromHnswShared(hnswshared));
|
ParallelTableScanFromHnswShared(hnswshared));
|
||||||
reltuples = table_index_build_scan(heapRel, indexRel, indexInfo,
|
reltuples = table_index_build_scan(hnswspool->heap, hnswspool->index, indexInfo,
|
||||||
true, progress, BuildCallback,
|
true, progress, BuildCallback,
|
||||||
(void *) &buildstate, scan);
|
(void *) &buildstate, scan);
|
||||||
|
#else
|
||||||
|
scan = heap_beginscan_parallel(hnswspool->heap, &hnswshared->heapdesc);
|
||||||
|
reltuples = IndexBuildHeapScan(hnswspool->heap, hnswspool->index, indexInfo,
|
||||||
|
true, BuildCallback,
|
||||||
|
(void *) &buildstate, scan);
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Record statistics */
|
/* Record statistics */
|
||||||
SpinLockAcquire(&hnswshared->mutex);
|
SpinLockAcquire(&hnswshared->mutex);
|
||||||
@@ -805,7 +766,10 @@ void
|
|||||||
HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
||||||
{
|
{
|
||||||
char *sharedquery;
|
char *sharedquery;
|
||||||
|
HnswSpool *hnswspool;
|
||||||
HnswShared *hnswshared;
|
HnswShared *hnswshared;
|
||||||
|
dsa_area *dsa;
|
||||||
|
void *dsaspace;
|
||||||
char *hnswarea;
|
char *hnswarea;
|
||||||
Relation heapRel;
|
Relation heapRel;
|
||||||
Relation indexRel;
|
Relation indexRel;
|
||||||
@@ -835,17 +799,32 @@ HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Open relations within worker */
|
/* Open relations within worker */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
heapRel = table_open(hnswshared->heaprelid, heapLockmode);
|
heapRel = table_open(hnswshared->heaprelid, heapLockmode);
|
||||||
|
#else
|
||||||
|
heapRel = heap_open(hnswshared->heaprelid, heapLockmode);
|
||||||
|
#endif
|
||||||
indexRel = index_open(hnswshared->indexrelid, indexLockmode);
|
indexRel = index_open(hnswshared->indexrelid, indexLockmode);
|
||||||
|
|
||||||
hnswarea = shm_toc_lookup(toc, PARALLEL_KEY_HNSW_AREA, false);
|
/* Initialize worker's own spool */
|
||||||
|
hnswspool = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
||||||
|
hnswspool->heap = heapRel;
|
||||||
|
hnswspool->index = indexRel;
|
||||||
|
|
||||||
|
dsaspace = shm_toc_lookup(toc, PARALLEL_KEY_HNSW_AREA, false);
|
||||||
|
dsa = dsa_attach_in_place(dsaspace, seg);
|
||||||
|
hnswarea = dsa_get_address(dsa, hnswshared->dsaptr);
|
||||||
|
|
||||||
/* Perform inserts */
|
/* Perform inserts */
|
||||||
HnswParallelScanAndInsert(heapRel, indexRel, hnswshared, hnswarea, false);
|
HnswParallelScanAndInsert(hnswspool, hnswshared, hnswarea, false);
|
||||||
|
|
||||||
/* Close relations within worker */
|
/* Close relations within worker */
|
||||||
index_close(indexRel, indexLockmode);
|
index_close(indexRel, indexLockmode);
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
table_close(heapRel, heapLockmode);
|
table_close(heapRel, heapLockmode);
|
||||||
|
#else
|
||||||
|
heap_close(heapRel, heapLockmode);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -870,7 +849,19 @@ HnswEndParallel(HnswLeader * hnswleader)
|
|||||||
static Size
|
static Size
|
||||||
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
||||||
{
|
{
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
return add_size(BUFFERALIGN(sizeof(HnswShared)), table_parallelscan_estimate(heap, snapshot));
|
return add_size(BUFFERALIGN(sizeof(HnswShared)), table_parallelscan_estimate(heap, snapshot));
|
||||||
|
#else
|
||||||
|
if (!IsMVCCSnapshot(snapshot))
|
||||||
|
{
|
||||||
|
Assert(snapshot == SnapshotAny);
|
||||||
|
return sizeof(HnswShared);
|
||||||
|
}
|
||||||
|
|
||||||
|
return add_size(offsetof(HnswShared, heapdesc) +
|
||||||
|
offsetof(ParallelHeapScanDescData, phs_snapshot_data),
|
||||||
|
EstimateSnapshotSpace(snapshot));
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -880,9 +871,15 @@ static void
|
|||||||
HnswLeaderParticipateAsWorker(HnswBuildState * buildstate)
|
HnswLeaderParticipateAsWorker(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
HnswLeader *hnswleader = buildstate->hnswleader;
|
HnswLeader *hnswleader = buildstate->hnswleader;
|
||||||
|
HnswSpool *leaderworker;
|
||||||
|
|
||||||
|
/* Allocate memory and initialize private spool */
|
||||||
|
leaderworker = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
||||||
|
leaderworker->heap = buildstate->heap;
|
||||||
|
leaderworker->index = buildstate->index;
|
||||||
|
|
||||||
/* Perform work common to all participants */
|
/* Perform work common to all participants */
|
||||||
HnswParallelScanAndInsert(buildstate->heap, buildstate->index, hnswleader->hnswshared, hnswleader->hnswarea, true);
|
HnswParallelScanAndInsert(leaderworker, hnswleader->hnswshared, hnswleader->hnswarea, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -892,11 +889,14 @@ static void
|
|||||||
HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
||||||
{
|
{
|
||||||
ParallelContext *pcxt;
|
ParallelContext *pcxt;
|
||||||
|
int scantuplesortstates;
|
||||||
Snapshot snapshot;
|
Snapshot snapshot;
|
||||||
Size esthnswshared;
|
Size esthnswshared;
|
||||||
Size esthnswarea;
|
Size esthnswarea;
|
||||||
Size estother;
|
Size estdsaspace;
|
||||||
HnswShared *hnswshared;
|
HnswShared *hnswshared;
|
||||||
|
void *dsaspace;
|
||||||
|
dsa_area *dsa;
|
||||||
char *hnswarea;
|
char *hnswarea;
|
||||||
HnswLeader *hnswleader = (HnswLeader *) palloc0(sizeof(HnswLeader));
|
HnswLeader *hnswleader = (HnswLeader *) palloc0(sizeof(HnswLeader));
|
||||||
bool leaderparticipates = true;
|
bool leaderparticipates = true;
|
||||||
@@ -909,7 +909,13 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
/* Enter parallel mode and create context */
|
/* Enter parallel mode and create context */
|
||||||
EnterParallelMode();
|
EnterParallelMode();
|
||||||
Assert(request > 0);
|
Assert(request > 0);
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request);
|
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request);
|
||||||
|
#else
|
||||||
|
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request, true);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
scantuplesortstates = leaderparticipates ? request + 1 : request;
|
||||||
|
|
||||||
/* Get snapshot for table scan */
|
/* Get snapshot for table scan */
|
||||||
if (!isconcurrent)
|
if (!isconcurrent)
|
||||||
@@ -921,15 +927,9 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
esthnswshared = ParallelEstimateShared(buildstate->heap, snapshot);
|
esthnswshared = ParallelEstimateShared(buildstate->heap, snapshot);
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, esthnswshared);
|
shm_toc_estimate_chunk(&pcxt->estimator, esthnswshared);
|
||||||
|
|
||||||
/* Leave space for other objects in shared memory */
|
/* Start with a minimal DSA so InitializeParallelDSM does not fail */
|
||||||
/* Docker has a default limit of 64 MB for shm_size */
|
estdsaspace = dsa_minimum_size();
|
||||||
/* which happens to be the default value of maintenance_work_mem */
|
shm_toc_estimate_chunk(&pcxt->estimator, estdsaspace);
|
||||||
esthnswarea = maintenance_work_mem * 1024L;
|
|
||||||
estother = 3 * 1024 * 1024;
|
|
||||||
if (esthnswarea > estother)
|
|
||||||
esthnswarea -= estother;
|
|
||||||
|
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, esthnswarea);
|
|
||||||
shm_toc_estimate_keys(&pcxt->estimator, 2);
|
shm_toc_estimate_keys(&pcxt->estimator, 2);
|
||||||
|
|
||||||
/* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
|
/* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
|
||||||
@@ -961,21 +961,42 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
hnswshared->heaprelid = RelationGetRelid(buildstate->heap);
|
hnswshared->heaprelid = RelationGetRelid(buildstate->heap);
|
||||||
hnswshared->indexrelid = RelationGetRelid(buildstate->index);
|
hnswshared->indexrelid = RelationGetRelid(buildstate->index);
|
||||||
hnswshared->isconcurrent = isconcurrent;
|
hnswshared->isconcurrent = isconcurrent;
|
||||||
|
hnswshared->scantuplesortstates = scantuplesortstates;
|
||||||
ConditionVariableInit(&hnswshared->workersdonecv);
|
ConditionVariableInit(&hnswshared->workersdonecv);
|
||||||
SpinLockInit(&hnswshared->mutex);
|
SpinLockInit(&hnswshared->mutex);
|
||||||
/* Initialize mutable state */
|
/* Initialize mutable state */
|
||||||
hnswshared->nparticipantsdone = 0;
|
hnswshared->nparticipantsdone = 0;
|
||||||
hnswshared->reltuples = 0;
|
hnswshared->reltuples = 0;
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
table_parallelscan_initialize(buildstate->heap,
|
table_parallelscan_initialize(buildstate->heap,
|
||||||
ParallelTableScanFromHnswShared(hnswshared),
|
ParallelTableScanFromHnswShared(hnswshared),
|
||||||
snapshot);
|
snapshot);
|
||||||
|
#else
|
||||||
|
heap_parallelscan_initialize(&hnswshared->heapdesc, buildstate->heap, snapshot);
|
||||||
|
#endif
|
||||||
|
|
||||||
hnswarea = (char *) shm_toc_allocate(pcxt->toc, esthnswarea);
|
dsaspace = shm_toc_allocate(pcxt->toc, estdsaspace);
|
||||||
|
dsa = dsa_create_in_place(dsaspace, estdsaspace, hnsw_lock_tranche_id, pcxt->seg);
|
||||||
|
|
||||||
|
esthnswarea = maintenance_work_mem * 1024L;
|
||||||
|
hnswshared->dsaptr = dsa_allocate_extended(dsa, esthnswarea, DSA_ALLOC_HUGE | DSA_ALLOC_NO_OOM);
|
||||||
|
|
||||||
|
/* If not enough shared memory, back out (do serial build) */
|
||||||
|
if (!DsaPointerIsValid(hnswshared->dsaptr))
|
||||||
|
{
|
||||||
|
if (IsMVCCSnapshot(snapshot))
|
||||||
|
UnregisterSnapshot(snapshot);
|
||||||
|
DestroyParallelContext(pcxt);
|
||||||
|
ExitParallelMode();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
hnswarea = dsa_get_address(dsa, hnswshared->dsaptr);
|
||||||
/* Report less than allocated so never fails */
|
/* Report less than allocated so never fails */
|
||||||
InitGraph(&hnswshared->graphData, hnswarea, esthnswarea - 1024 * 1024);
|
InitGraph(&hnswshared->graphData, hnswarea, esthnswarea - 1024 * 1024);
|
||||||
|
|
||||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_SHARED, hnswshared);
|
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_SHARED, hnswshared);
|
||||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_AREA, hnswarea);
|
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_AREA, dsaspace);
|
||||||
|
|
||||||
/* Store query string for workers */
|
/* Store query string for workers */
|
||||||
if (debug_query_string)
|
if (debug_query_string)
|
||||||
@@ -1047,7 +1068,7 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
{
|
{
|
||||||
int parallel_workers = 0;
|
int parallel_workers = 0;
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
/* Calculate parallel workers */
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
@@ -1063,8 +1084,15 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
if (buildstate->hnswleader)
|
if (buildstate->hnswleader)
|
||||||
buildstate->reltuples = ParallelHeapScan(buildstate);
|
buildstate->reltuples = ParallelHeapScan(buildstate);
|
||||||
else
|
else
|
||||||
|
{
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
true, true, BuildCallback, (void *) buildstate, NULL);
|
true, true, BuildCallback, (void *) buildstate, NULL);
|
||||||
|
#else
|
||||||
|
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
|
true, BuildCallback, (void *) buildstate, NULL);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
buildstate->indtuples = buildstate->graph->indtuples;
|
buildstate->indtuples = buildstate->graph->indtuples;
|
||||||
}
|
}
|
||||||
@@ -1078,6 +1106,22 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
HnswEndParallel(buildstate->hnswleader);
|
HnswEndParallel(buildstate->hnswleader);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 110008
|
||||||
|
void
|
||||||
|
log_newpage_range(Relation rel, ForkNumber forkNum, BlockNumber startblk, BlockNumber endblk, bool page_std)
|
||||||
|
{
|
||||||
|
for (BlockNumber blkno = startblk; blkno < endblk; blkno++)
|
||||||
|
{
|
||||||
|
Buffer buf = ReadBufferExtended(rel, forkNum, blkno, RBM_NORMAL, NULL);
|
||||||
|
|
||||||
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
|
log_newpage_buffer(buf, page_std);
|
||||||
|
UnlockReleaseBuffer(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Build the index
|
* Build the index
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "storage/lmgr.h"
|
#include "storage/lmgr.h"
|
||||||
@@ -117,7 +116,7 @@ HnswInsertAppendPage(Relation index, Buffer *nbuf, Page *npage, GenericXLogState
|
|||||||
* Add to element and neighbor pages
|
* Add to element and neighbor pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
AddElementOnDisk(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage, bool building)
|
WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage, bool building)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -340,7 +339,7 @@ ConnectionExists(HnswElement e, HnswNeighborTuple ntup, int startIdx, int lm)
|
|||||||
* Update neighbors
|
* Update neighbors
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building)
|
HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building)
|
||||||
{
|
{
|
||||||
char *base = NULL;
|
char *base = NULL;
|
||||||
|
|
||||||
@@ -355,7 +354,9 @@ HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, Hns
|
|||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
|
ItemId itemid;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
|
Size ntupSize;
|
||||||
int idx = -1;
|
int idx = -1;
|
||||||
int startIdx;
|
int startIdx;
|
||||||
HnswElement neighborElement = HnswPtrAccess(base, hc->element);
|
HnswElement neighborElement = HnswPtrAccess(base, hc->element);
|
||||||
@@ -394,7 +395,9 @@ HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, Hns
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Get tuple */
|
/* Get tuple */
|
||||||
ntup = (HnswNeighborTuple) PageGetItem(page, PageGetItemId(page, offno));
|
itemid = PageGetItemId(page, offno);
|
||||||
|
ntup = (HnswNeighborTuple) PageGetItem(page, itemid);
|
||||||
|
ntupSize = ItemIdGetLength(itemid);
|
||||||
|
|
||||||
/* Calculate index for update */
|
/* Calculate index for update */
|
||||||
startIdx = (neighborElement->level - lc) * m;
|
startIdx = (neighborElement->level - lc) * m;
|
||||||
@@ -423,9 +426,13 @@ HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, Hns
|
|||||||
{
|
{
|
||||||
ItemPointer indextid = &ntup->indextids[idx];
|
ItemPointer indextid = &ntup->indextids[idx];
|
||||||
|
|
||||||
/* Update neighbor on the buffer */
|
/* Update neighbor */
|
||||||
ItemPointerSet(indextid, e->blkno, e->offno);
|
ItemPointerSet(indextid, e->blkno, e->offno);
|
||||||
|
|
||||||
|
/* Overwrite tuple */
|
||||||
|
if (!PageIndexTupleOverwrite(page, offno, (Item) ntup, ntupSize))
|
||||||
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
if (building)
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(buf);
|
||||||
@@ -444,12 +451,14 @@ HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, Hns
|
|||||||
* Add a heap TID to an existing element
|
* Add a heap TID to an existing element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
AddDuplicateOnDisk(Relation index, HnswElement element, HnswElement dup, bool building)
|
HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool building)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
|
ItemId itemid;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
|
Size etupSize;
|
||||||
int i;
|
int i;
|
||||||
|
|
||||||
/* Read page */
|
/* Read page */
|
||||||
@@ -467,7 +476,9 @@ AddDuplicateOnDisk(Relation index, HnswElement element, HnswElement dup, bool bu
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find space */
|
/* Find space */
|
||||||
etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, dup->offno));
|
itemid = PageGetItemId(page, dup->offno);
|
||||||
|
etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||||
|
etupSize = ItemIdGetLength(itemid);
|
||||||
for (i = 0; i < HNSW_HEAPTIDS; i++)
|
for (i = 0; i < HNSW_HEAPTIDS; i++)
|
||||||
{
|
{
|
||||||
if (!ItemPointerIsValid(&etup->heaptids[i]))
|
if (!ItemPointerIsValid(&etup->heaptids[i]))
|
||||||
@@ -483,9 +494,13 @@ AddDuplicateOnDisk(Relation index, HnswElement element, HnswElement dup, bool bu
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add heap TID, modifying the tuple on the page directly */
|
/* Add heap TID */
|
||||||
etup->heaptids[i] = element->heaptids[0];
|
etup->heaptids[i] = element->heaptids[0];
|
||||||
|
|
||||||
|
/* Overwrite tuple */
|
||||||
|
if (!PageIndexTupleOverwrite(page, dup->offno, (Item) etup, etupSize))
|
||||||
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
if (building)
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(buf);
|
||||||
@@ -500,23 +515,23 @@ AddDuplicateOnDisk(Relation index, HnswElement element, HnswElement dup, bool bu
|
|||||||
* Find duplicate element
|
* Find duplicate element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
FindDuplicateOnDisk(Relation index, HnswElement element, bool building)
|
HnswFindDuplicate(Relation index, HnswElement element, bool building)
|
||||||
{
|
{
|
||||||
char *base = NULL;
|
char *base = NULL;
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
||||||
Datum value = HnswGetValue(base, element);
|
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
{
|
{
|
||||||
HnswCandidate *neighbor = &neighbors->items[i];
|
HnswCandidate *neighbor = &neighbors->items[i];
|
||||||
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
||||||
|
Datum value = HnswGetValue(base, element);
|
||||||
Datum neighborValue = HnswGetValue(base, neighborElement);
|
Datum neighborValue = HnswGetValue(base, neighborElement);
|
||||||
|
|
||||||
/* Exit early since ordered by distance */
|
/* Exit early since ordered by distance */
|
||||||
if (!datumIsEqual(value, neighborValue, false, -1))
|
if (!datumIsEqual(value, neighborValue, false, -1))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
if (AddDuplicateOnDisk(index, element, neighborElement, building))
|
if (HnswAddDuplicate(index, element, neighborElement, building))
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -524,26 +539,26 @@ FindDuplicateOnDisk(Relation index, HnswElement element, bool building)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Update graph on disk
|
* Write changes to disk
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
UpdateGraphOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, bool building)
|
WriteElement(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, bool building)
|
||||||
{
|
{
|
||||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||||
|
|
||||||
/* Look for duplicate */
|
/* Look for duplicate */
|
||||||
if (FindDuplicateOnDisk(index, element, building))
|
if (HnswFindDuplicate(index, element, building))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Add element */
|
/* Write element and neighbor tuples */
|
||||||
AddElementOnDisk(index, element, m, GetInsertPage(index), &newInsertPage, building);
|
WriteNewElementPages(index, element, m, GetInsertPage(index), &newInsertPage, building);
|
||||||
|
|
||||||
/* Update insert page if needed */
|
/* Update insert page if needed */
|
||||||
if (BlockNumberIsValid(newInsertPage))
|
if (BlockNumberIsValid(newInsertPage))
|
||||||
HnswUpdateMetaPage(index, 0, NULL, newInsertPage, MAIN_FORKNUM, building);
|
HnswUpdateMetaPage(index, 0, NULL, newInsertPage, MAIN_FORKNUM, building);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborsOnDisk(index, procinfo, collation, element, m, false, building);
|
HnswUpdateNeighborPages(index, procinfo, collation, element, m, false, building);
|
||||||
|
|
||||||
/* Update entry point if needed */
|
/* Update entry point if needed */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
@@ -554,7 +569,7 @@ UpdateGraphOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement
|
|||||||
* Insert a tuple into the index
|
* Insert a tuple into the index
|
||||||
*/
|
*/
|
||||||
bool
|
bool
|
||||||
HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building)
|
HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel, bool building)
|
||||||
{
|
{
|
||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
HnswElement element;
|
HnswElement element;
|
||||||
@@ -593,11 +608,11 @@ HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull,
|
|||||||
entryPoint = HnswGetEntryPoint(index);
|
entryPoint = HnswGetEntryPoint(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Find neighbors for element */
|
/* Insert element in graph */
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
HnswInsertElement(base, element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
/* Update graph on disk */
|
/* Write to disk */
|
||||||
UpdateGraphOnDisk(index, procinfo, collation, element, m, efConstruction, entryPoint, building);
|
WriteElement(index, procinfo, collation, element, m, efConstruction, entryPoint, building);
|
||||||
|
|
||||||
/* Release lock */
|
/* Release lock */
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||||
@@ -609,7 +624,7 @@ HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull,
|
|||||||
* Insert a tuple into the index
|
* Insert a tuple into the index
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid)
|
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
||||||
{
|
{
|
||||||
Datum value;
|
Datum value;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
@@ -626,7 +641,7 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
HnswInsertTupleOnDisk(index, value, values, isnull, heap_tid, false);
|
HnswInsertTupleOnDisk(index, value, values, isnull, heap_tid, heapRel, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -655,7 +670,7 @@ hnswinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid,
|
|||||||
oldCtx = MemoryContextSwitchTo(insertCtx);
|
oldCtx = MemoryContextSwitchTo(insertCtx);
|
||||||
|
|
||||||
/* Insert tuple */
|
/* Insert tuple */
|
||||||
HnswInsertTuple(index, values, isnull, heap_tid);
|
HnswInsertTuple(index, values, isnull, heap_tid, heap);
|
||||||
|
|
||||||
/* Delete memory context */
|
/* Delete memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|||||||
@@ -201,8 +201,12 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan->xs_heaptid = *heaptid;
|
scan->xs_heaptid = *heaptid;
|
||||||
scan->xs_recheck = false;
|
#else
|
||||||
|
scan->xs_ctup.t_self = *heaptid;
|
||||||
|
#endif
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
167
src/hnswutils.c
167
src/hnswutils.c
@@ -2,13 +2,9 @@
|
|||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "lib/pairingheap.h"
|
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "utils/datum.h"
|
#include "utils/datum.h"
|
||||||
#include "utils/memdebug.h"
|
|
||||||
#include "utils/rel.h"
|
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
@@ -60,6 +56,13 @@ hash_tid(ItemPointerData tid)
|
|||||||
#define SH_DEFINE
|
#define SH_DEFINE
|
||||||
#include "lib/simplehash.h"
|
#include "lib/simplehash.h"
|
||||||
|
|
||||||
|
/* Needed to include simplehash.h twice */
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
#undef SH_EQUAL
|
||||||
|
#define sh_log2 pointerhash_sh_log2
|
||||||
|
#define sh_pow2 pointerhash_sh_pow2
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Pointer hash table */
|
/* Pointer hash table */
|
||||||
static uint32
|
static uint32
|
||||||
hash_pointer(uintptr_t ptr)
|
hash_pointer(uintptr_t ptr)
|
||||||
@@ -81,6 +84,15 @@ hash_pointer(uintptr_t ptr)
|
|||||||
#define SH_DEFINE
|
#define SH_DEFINE
|
||||||
#include "lib/simplehash.h"
|
#include "lib/simplehash.h"
|
||||||
|
|
||||||
|
/* Needed to include simplehash.h again */
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
#undef SH_EQUAL
|
||||||
|
#undef sh_log2
|
||||||
|
#undef sh_pow2
|
||||||
|
#define sh_log2 offsethash_sh_log2
|
||||||
|
#define sh_pow2 offsethash_sh_pow2
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Offset hash table */
|
/* Offset hash table */
|
||||||
static uint32
|
static uint32
|
||||||
hash_offset(Size offset)
|
hash_offset(Size offset)
|
||||||
@@ -203,19 +215,6 @@ HnswInitPage(Buffer buf, Page page)
|
|||||||
HnswPageGetOpaque(page)->page_id = HNSW_PAGE_ID;
|
HnswPageGetOpaque(page)->page_id = HNSW_PAGE_ID;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Allocate a neighbor array
|
|
||||||
*/
|
|
||||||
static HnswNeighborArray *
|
|
||||||
HnswInitNeighborArray(int lm, HnswAllocator * allocator)
|
|
||||||
{
|
|
||||||
HnswNeighborArray *a = HnswAlloc(allocator, HNSW_NEIGHBOR_ARRAY_SIZE(lm));
|
|
||||||
|
|
||||||
a->length = 0;
|
|
||||||
a->closerSet = false;
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Allocate neighbors
|
* Allocate neighbors
|
||||||
*/
|
*/
|
||||||
@@ -223,12 +222,22 @@ void
|
|||||||
HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * allocator)
|
HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * allocator)
|
||||||
{
|
{
|
||||||
int level = element->level;
|
int level = element->level;
|
||||||
|
|
||||||
HnswNeighborArrayPtr *neighborList = (HnswNeighborArrayPtr *) HnswAlloc(allocator, sizeof(HnswNeighborArrayPtr) * (level + 1));
|
HnswNeighborArrayPtr *neighborList = (HnswNeighborArrayPtr *) HnswAlloc(allocator, sizeof(HnswNeighborArrayPtr) * (level + 1));
|
||||||
|
|
||||||
HnswPtrStore(base, element->neighbors, neighborList);
|
HnswPtrStore(base, element->neighbors, neighborList);
|
||||||
|
|
||||||
for (int lc = 0; lc <= level; lc++)
|
for (int lc = 0; lc <= level; lc++)
|
||||||
HnswPtrStore(base, neighborList[lc], HnswInitNeighborArray(HnswGetLayerM(m, lc), allocator));
|
{
|
||||||
|
HnswNeighborArray *a;
|
||||||
|
int lm = HnswGetLayerM(m, lc);
|
||||||
|
|
||||||
|
HnswPtrStore(base, neighborList[lc], (HnswNeighborArray *) HnswAlloc(allocator, offsetof(HnswNeighborArray, items) + sizeof(HnswCandidate) * lm));
|
||||||
|
|
||||||
|
a = HnswGetNeighbors(base, element, lc);
|
||||||
|
a->length = 0;
|
||||||
|
a->closerSet = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -316,10 +325,7 @@ HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint)
|
|||||||
if (entryPoint != NULL)
|
if (entryPoint != NULL)
|
||||||
{
|
{
|
||||||
if (BlockNumberIsValid(metap->entryBlkno))
|
if (BlockNumberIsValid(metap->entryBlkno))
|
||||||
{
|
|
||||||
*entryPoint = HnswInitElementFromBlock(metap->entryBlkno, metap->entryOffno);
|
*entryPoint = HnswInitElementFromBlock(metap->entryBlkno, metap->entryOffno);
|
||||||
(*entryPoint)->level = metap->entryLevel;
|
|
||||||
}
|
|
||||||
else
|
else
|
||||||
*entryPoint = NULL;
|
*entryPoint = NULL;
|
||||||
}
|
}
|
||||||
@@ -650,25 +656,11 @@ CreatePairingHeapNode(HnswCandidate * c)
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Init visited
|
|
||||||
*/
|
|
||||||
static inline void
|
|
||||||
InitVisited(char *base, visited_hash * v, Relation index, int ef, int m)
|
|
||||||
{
|
|
||||||
if (index != NULL)
|
|
||||||
v->tids = tidhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
|
||||||
else if (base != NULL)
|
|
||||||
v->offsets = offsethash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
|
||||||
else
|
|
||||||
v->pointers = pointerhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add to visited
|
* Add to visited
|
||||||
*/
|
*/
|
||||||
static inline void
|
static inline void
|
||||||
AddToVisited(char *base, visited_hash * v, HnswCandidate * hc, Relation index, bool *found)
|
AddToVisited(char *base, visited_hash v, HnswCandidate * hc, Relation index, bool *found)
|
||||||
{
|
{
|
||||||
if (index != NULL)
|
if (index != NULL)
|
||||||
{
|
{
|
||||||
@@ -676,16 +668,16 @@ AddToVisited(char *base, visited_hash * v, HnswCandidate * hc, Relation index, b
|
|||||||
ItemPointerData indextid;
|
ItemPointerData indextid;
|
||||||
|
|
||||||
ItemPointerSet(&indextid, element->blkno, element->offno);
|
ItemPointerSet(&indextid, element->blkno, element->offno);
|
||||||
tidhash_insert(v->tids, indextid, found);
|
tidhash_insert(v.tids, indextid, found);
|
||||||
}
|
}
|
||||||
else if (base != NULL)
|
else if (base != NULL)
|
||||||
{
|
{
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
HnswElement element = HnswPtrAccess(base, hc->element);
|
HnswElement element = HnswPtrAccess(base, hc->element);
|
||||||
|
|
||||||
offsethash_insert_hash(v->offsets, HnswPtrOffset(hc->element), element->hash, found);
|
offsethash_insert_hash(v.offsets, HnswPtrOffset(hc->element), element->hash, found);
|
||||||
#else
|
#else
|
||||||
offsethash_insert(v->offsets, HnswPtrOffset(hc->element), found);
|
offsethash_insert(v.offsets, HnswPtrOffset(hc->element), found);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -693,9 +685,9 @@ AddToVisited(char *base, visited_hash * v, HnswCandidate * hc, Relation index, b
|
|||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
HnswElement element = HnswPtrAccess(base, hc->element);
|
HnswElement element = HnswPtrAccess(base, hc->element);
|
||||||
|
|
||||||
pointerhash_insert_hash(v->pointers, (uintptr_t) HnswPtrPointer(hc->element), element->hash, found);
|
pointerhash_insert_hash(v.pointers, (uintptr_t) HnswPtrPointer(hc->element), element->hash, found);
|
||||||
#else
|
#else
|
||||||
pointerhash_insert(v->pointers, (uintptr_t) HnswPtrPointer(hc->element), found);
|
pointerhash_insert(v.pointers, (uintptr_t) HnswPtrPointer(hc->element), found);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -733,12 +725,18 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
HnswNeighborArray *neighborhoodData = NULL;
|
HnswNeighborArray *neighborhoodData = NULL;
|
||||||
Size neighborhoodSize;
|
Size neighborhoodSize;
|
||||||
|
|
||||||
InitVisited(base, &v, index, ef, m);
|
/* Create hash table */
|
||||||
|
if (index != NULL)
|
||||||
|
v.tids = tidhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
||||||
|
else if (base != NULL)
|
||||||
|
v.offsets = offsethash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
||||||
|
else
|
||||||
|
v.pointers = pointerhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
||||||
|
|
||||||
/* Create local memory for neighborhood if needed */
|
/* Create local memory for neighborhood if needed */
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
{
|
{
|
||||||
neighborhoodSize = HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, lc));
|
neighborhoodSize = offsetof(HnswNeighborArray, items) + sizeof(HnswCandidate) * HnswGetLayerM(m, lc);
|
||||||
neighborhoodData = palloc(neighborhoodSize);
|
neighborhoodData = palloc(neighborhoodSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -748,7 +746,7 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
HnswCandidate *hc = (HnswCandidate *) lfirst(lc2);
|
HnswCandidate *hc = (HnswCandidate *) lfirst(lc2);
|
||||||
bool found;
|
bool found;
|
||||||
|
|
||||||
AddToVisited(base, &v, hc, index, &found);
|
AddToVisited(base, v, hc, index, &found);
|
||||||
|
|
||||||
pairingheap_add(C, &(CreatePairingHeapNode(hc)->ph_node));
|
pairingheap_add(C, &(CreatePairingHeapNode(hc)->ph_node));
|
||||||
pairingheap_add(W, &(CreatePairingHeapNode(hc)->ph_node));
|
pairingheap_add(W, &(CreatePairingHeapNode(hc)->ph_node));
|
||||||
@@ -783,7 +781,7 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
/* Copy neighborhood to local memory if needed */
|
/* Copy neighborhood to local memory if needed */
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
{
|
{
|
||||||
LWLockAcquire(&cElement->lock, LW_SHARED);
|
LWLockAcquire(&cElement->lock, LW_EXCLUSIVE);
|
||||||
memcpy(neighborhoodData, neighborhood, neighborhoodSize);
|
memcpy(neighborhoodData, neighborhood, neighborhoodSize);
|
||||||
LWLockRelease(&cElement->lock);
|
LWLockRelease(&cElement->lock);
|
||||||
neighborhood = neighborhoodData;
|
neighborhood = neighborhoodData;
|
||||||
@@ -794,7 +792,7 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
HnswCandidate *e = &neighborhood->items[i];
|
HnswCandidate *e = &neighborhood->items[i];
|
||||||
bool visited;
|
bool visited;
|
||||||
|
|
||||||
AddToVisited(base, &v, e, index, &visited);
|
AddToVisited(base, v, e, index, &visited);
|
||||||
|
|
||||||
if (!visited)
|
if (!visited)
|
||||||
{
|
{
|
||||||
@@ -914,10 +912,40 @@ CompareCandidateDistancesOffset(const void *a, const void *b)
|
|||||||
* Calculate the distance between elements
|
* Calculate the distance between elements
|
||||||
*/
|
*/
|
||||||
static float
|
static float
|
||||||
HnswGetDistance(char *base, HnswElement a, HnswElement b, FmgrInfo *procinfo, Oid collation)
|
HnswGetDistance(char *base, HnswElement a, HnswElement b, int lc, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
Datum aValue = HnswGetValue(base, a);
|
Datum aValue;
|
||||||
Datum bValue = HnswGetValue(base, b);
|
Datum bValue;
|
||||||
|
|
||||||
|
/* Look for cached distance */
|
||||||
|
if (!HnswPtrIsNull(base, a->neighbors))
|
||||||
|
{
|
||||||
|
HnswNeighborArray *neighbors = HnswGetNeighbors(base, a, lc);
|
||||||
|
|
||||||
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
|
{
|
||||||
|
HnswElement element = HnswPtrAccess(base, neighbors->items[i].element);
|
||||||
|
|
||||||
|
if (element == b)
|
||||||
|
return neighbors->items[i].distance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!HnswPtrIsNull(base, b->neighbors))
|
||||||
|
{
|
||||||
|
HnswNeighborArray *neighbors = HnswGetNeighbors(base, b, lc);
|
||||||
|
|
||||||
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
|
{
|
||||||
|
HnswElement element = HnswPtrAccess(base, neighbors->items[i].element);
|
||||||
|
|
||||||
|
if (element == a)
|
||||||
|
return neighbors->items[i].distance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
aValue = HnswGetValue(base, a);
|
||||||
|
bValue = HnswGetValue(base, b);
|
||||||
|
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, aValue, bValue));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, aValue, bValue));
|
||||||
}
|
}
|
||||||
@@ -926,7 +954,7 @@ HnswGetDistance(char *base, HnswElement a, HnswElement b, FmgrInfo *procinfo, Oi
|
|||||||
* Check if an element is closer to q than any element from R
|
* Check if an element is closer to q than any element from R
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
CheckElementCloser(char *base, HnswCandidate * e, List *r, FmgrInfo *procinfo, Oid collation)
|
CheckElementCloser(char *base, HnswCandidate * e, List *r, int lc, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
HnswElement eElement = HnswPtrAccess(base, e->element);
|
HnswElement eElement = HnswPtrAccess(base, e->element);
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
@@ -935,7 +963,8 @@ CheckElementCloser(char *base, HnswCandidate * e, List *r, FmgrInfo *procinfo, O
|
|||||||
{
|
{
|
||||||
HnswCandidate *ri = lfirst(lc2);
|
HnswCandidate *ri = lfirst(lc2);
|
||||||
HnswElement riElement = HnswPtrAccess(base, ri->element);
|
HnswElement riElement = HnswPtrAccess(base, ri->element);
|
||||||
float distance = HnswGetDistance(base, eElement, riElement, procinfo, collation);
|
|
||||||
|
float distance = HnswGetDistance(base, eElement, riElement, lc, procinfo, collation);
|
||||||
|
|
||||||
if (distance <= e->distance)
|
if (distance <= e->distance)
|
||||||
return false;
|
return false;
|
||||||
@@ -948,7 +977,7 @@ CheckElementCloser(char *base, HnswCandidate * e, List *r, FmgrInfo *procinfo, O
|
|||||||
* Algorithm 4 from paper
|
* Algorithm 4 from paper
|
||||||
*/
|
*/
|
||||||
static List *
|
static List *
|
||||||
SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid collation, HnswElement e2, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswElement e2, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
||||||
{
|
{
|
||||||
List *r = NIL;
|
List *r = NIL;
|
||||||
List *w = list_copy(c);
|
List *w = list_copy(c);
|
||||||
@@ -958,7 +987,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
List *added = NIL;
|
List *added = NIL;
|
||||||
bool removedAny = false;
|
bool removedAny = false;
|
||||||
|
|
||||||
if (list_length(w) <= lm)
|
if (list_length(w) <= m)
|
||||||
return w;
|
return w;
|
||||||
|
|
||||||
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||||
@@ -972,7 +1001,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
list_sort(w, CompareCandidateDistancesOffset);
|
list_sort(w, CompareCandidateDistancesOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (list_length(w) > 0 && list_length(r) < lm)
|
while (list_length(w) > 0 && list_length(r) < m)
|
||||||
{
|
{
|
||||||
/* Assumes w is already ordered desc */
|
/* Assumes w is already ordered desc */
|
||||||
HnswCandidate *e = llast(w);
|
HnswCandidate *e = llast(w);
|
||||||
@@ -981,20 +1010,16 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
|
|
||||||
/* Use previous state of r and wd to skip work when possible */
|
/* Use previous state of r and wd to skip work when possible */
|
||||||
if (mustCalculate)
|
if (mustCalculate)
|
||||||
e->closer = CheckElementCloser(base, e, r, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, lc, procinfo, collation);
|
||||||
else if (list_length(added) > 0)
|
else if (list_length(added) > 0)
|
||||||
{
|
{
|
||||||
/* Keep Valgrind happy for in-memory, parallel builds */
|
|
||||||
if (base != NULL)
|
|
||||||
VALGRIND_MAKE_MEM_DEFINED(&e->closer, 1);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* If the current candidate was closer, we only need to compare it
|
* If the current candidate was closer, we only need to compare it
|
||||||
* with the other candidates that we have added.
|
* with the other candidates that we have added.
|
||||||
*/
|
*/
|
||||||
if (e->closer)
|
if (e->closer)
|
||||||
{
|
{
|
||||||
e->closer = CheckElementCloser(base, e, added, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, added, lc, procinfo, collation);
|
||||||
|
|
||||||
if (!e->closer)
|
if (!e->closer)
|
||||||
removedAny = true;
|
removedAny = true;
|
||||||
@@ -1007,7 +1032,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
*/
|
*/
|
||||||
if (removedAny)
|
if (removedAny)
|
||||||
{
|
{
|
||||||
e->closer = CheckElementCloser(base, e, r, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, lc, procinfo, collation);
|
||||||
if (e->closer)
|
if (e->closer)
|
||||||
added = lappend(added, e);
|
added = lappend(added, e);
|
||||||
}
|
}
|
||||||
@@ -1015,15 +1040,11 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
}
|
}
|
||||||
else if (e == newCandidate)
|
else if (e == newCandidate)
|
||||||
{
|
{
|
||||||
e->closer = CheckElementCloser(base, e, r, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, lc, procinfo, collation);
|
||||||
if (e->closer)
|
if (e->closer)
|
||||||
added = lappend(added, e);
|
added = lappend(added, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Keep Valgrind happy for in-memory, parallel builds */
|
|
||||||
if (base != NULL)
|
|
||||||
VALGRIND_MAKE_MEM_DEFINED(&e->closer, 1);
|
|
||||||
|
|
||||||
if (e->closer)
|
if (e->closer)
|
||||||
r = lappend(r, e);
|
r = lappend(r, e);
|
||||||
else
|
else
|
||||||
@@ -1034,7 +1055,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
neighbors->closerSet = sortCandidates;
|
neighbors->closerSet = sortCandidates;
|
||||||
|
|
||||||
/* Keep pruned connections */
|
/* Keep pruned connections */
|
||||||
while (!pairingheap_is_empty(wd) && list_length(r) < lm)
|
while (!pairingheap_is_empty(wd) && list_length(r) < m)
|
||||||
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
||||||
|
|
||||||
/* Return pruned for update connections */
|
/* Return pruned for update connections */
|
||||||
@@ -1053,7 +1074,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
* Add connections
|
* Add connections
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
AddConnections(char *base, HnswElement element, List *neighbors, int lc)
|
AddConnections(char *base, HnswElement element, List *neighbors, int m, int lc)
|
||||||
{
|
{
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
HnswNeighborArray *a = HnswGetNeighbors(base, element, lc);
|
HnswNeighborArray *a = HnswGetNeighbors(base, element, lc);
|
||||||
@@ -1066,7 +1087,7 @@ AddConnections(char *base, HnswElement element, List *neighbors, int lc)
|
|||||||
* Update connections
|
* Update connections
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation)
|
HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
HnswElement hce = HnswPtrAccess(base, hc->element);
|
HnswElement hce = HnswPtrAccess(base, hc->element);
|
||||||
HnswNeighborArray *currentNeighbors = HnswGetNeighbors(base, hce, lc);
|
HnswNeighborArray *currentNeighbors = HnswGetNeighbors(base, hce, lc);
|
||||||
@@ -1075,7 +1096,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm
|
|||||||
HnswPtrStore(base, hc2.element, element);
|
HnswPtrStore(base, hc2.element, element);
|
||||||
hc2.distance = hc->distance;
|
hc2.distance = hc->distance;
|
||||||
|
|
||||||
if (currentNeighbors->length < lm)
|
if (currentNeighbors->length < m)
|
||||||
{
|
{
|
||||||
currentNeighbors->items[currentNeighbors->length++] = hc2;
|
currentNeighbors->items[currentNeighbors->length++] = hc2;
|
||||||
|
|
||||||
@@ -1121,7 +1142,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm
|
|||||||
c = lappend(c, ¤tNeighbors->items[i]);
|
c = lappend(c, ¤tNeighbors->items[i]);
|
||||||
c = lappend(c, &hc2);
|
c = lappend(c, &hc2);
|
||||||
|
|
||||||
SelectNeighbors(base, c, lm, lc, procinfo, collation, hce, &hc2, &pruned, true);
|
SelectNeighbors(base, c, m, lc, procinfo, collation, hce, &hc2, &pruned, true);
|
||||||
|
|
||||||
/* Should not happen */
|
/* Should not happen */
|
||||||
if (pruned == NULL)
|
if (pruned == NULL)
|
||||||
@@ -1195,7 +1216,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, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing)
|
HnswInsertElement(char *base, HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing)
|
||||||
{
|
{
|
||||||
List *ep;
|
List *ep;
|
||||||
List *w;
|
List *w;
|
||||||
@@ -1255,7 +1276,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
*/
|
*/
|
||||||
neighbors = SelectNeighbors(base, lw, lm, lc, procinfo, collation, element, NULL, NULL, false);
|
neighbors = SelectNeighbors(base, lw, lm, lc, procinfo, collation, element, NULL, NULL, false);
|
||||||
|
|
||||||
AddConnections(base, element, neighbors, lc);
|
AddConnections(base, element, neighbors, lm, lc);
|
||||||
|
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "commands/vacuum.h"
|
#include "commands/vacuum.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
@@ -60,7 +59,8 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
/* Iterate over nodes */
|
/* Iterate over nodes */
|
||||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
ItemId itemid = PageGetItemId(page, offno);
|
||||||
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||||
int idx = 0;
|
int idx = 0;
|
||||||
bool itemUpdated = false;
|
bool itemUpdated = false;
|
||||||
|
|
||||||
@@ -91,10 +91,15 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
if (itemUpdated)
|
if (itemUpdated)
|
||||||
{
|
{
|
||||||
|
Size etupSize = ItemIdGetLength(itemid);
|
||||||
|
|
||||||
/* Mark rest as invalid */
|
/* Mark rest as invalid */
|
||||||
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
||||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||||
|
|
||||||
|
if (!PageIndexTupleOverwrite(page, offno, (Item) etup, etupSize))
|
||||||
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
updated = true;
|
updated = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -194,25 +199,21 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
BufferAccessStrategy bas = vacuumstate->bas;
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
HnswNeighborTuple ntup = vacuumstate->ntup;
|
HnswNeighborTuple ntup = vacuumstate->ntup;
|
||||||
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, m);
|
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, m);
|
||||||
char *base = NULL;
|
|
||||||
|
|
||||||
/* Skip if element is entry point */
|
/* Skip if element is entry point */
|
||||||
if (entryPoint != NULL && element->blkno == entryPoint->blkno && element->offno == entryPoint->offno)
|
if (entryPoint != NULL && element->blkno == entryPoint->blkno && element->offno == entryPoint->offno)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Init fields */
|
/* Init fields */
|
||||||
HnswInitNeighbors(base, element, m, NULL);
|
HnswInitNeighbors(NULL, element, m, NULL);
|
||||||
element->heaptidsLength = 0;
|
element->heaptidsLength = 0;
|
||||||
|
|
||||||
/* Find neighbors for element, skipping itself */
|
/* Add element to graph, skipping itself */
|
||||||
HnswFindElementNeighbors(base, element, entryPoint, index, procinfo, collation, m, efConstruction, true);
|
HnswInsertElement(NULL, element, entryPoint, index, procinfo, collation, m, efConstruction, true);
|
||||||
|
|
||||||
/* Zero memory for each element */
|
|
||||||
MemSet(ntup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
|
||||||
|
|
||||||
/* Update neighbor tuple */
|
/* Update neighbor tuple */
|
||||||
/* Do this before getting page to minimize locking */
|
/* Do this before getting page to minimize locking */
|
||||||
HnswSetNeighborTuple(base, ntup, element, m);
|
HnswSetNeighborTuple(NULL, ntup, element, m);
|
||||||
|
|
||||||
/* Get neighbor page */
|
/* Get neighbor page */
|
||||||
buf = ReadBufferExtended(index, MAIN_FORKNUM, element->neighborPage, RBM_NORMAL, bas);
|
buf = ReadBufferExtended(index, MAIN_FORKNUM, element->neighborPage, RBM_NORMAL, bas);
|
||||||
@@ -229,7 +230,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborsOnDisk(index, procinfo, collation, element, m, true, false);
|
HnswUpdateNeighborPages(index, procinfo, collation, element, m, true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -476,8 +477,11 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
/* Update element and neighbors together */
|
/* Update element and neighbors together */
|
||||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
ItemId itemid = PageGetItemId(page, offno);
|
||||||
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
|
Size etupSize;
|
||||||
|
Size ntupSize;
|
||||||
Buffer nbuf;
|
Buffer nbuf;
|
||||||
Page npage;
|
Page npage;
|
||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
@@ -501,6 +505,10 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
if (ItemPointerIsValid(&etup->heaptids[0]))
|
if (ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
/* Calculate sizes */
|
||||||
|
etupSize = ItemIdGetLength(itemid);
|
||||||
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
||||||
|
|
||||||
/* Get neighbor page */
|
/* Get neighbor page */
|
||||||
neighborPage = ItemPointerGetBlockNumber(&etup->neighbortid);
|
neighborPage = ItemPointerGetBlockNumber(&etup->neighbortid);
|
||||||
neighborOffno = ItemPointerGetOffsetNumber(&etup->neighbortid);
|
neighborOffno = ItemPointerGetOffsetNumber(&etup->neighbortid);
|
||||||
@@ -527,10 +535,13 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
for (int i = 0; i < ntup->count; i++)
|
for (int i = 0; i < ntup->count; i++)
|
||||||
ItemPointerSetInvalid(&ntup->indextids[i]);
|
ItemPointerSetInvalid(&ntup->indextids[i]);
|
||||||
|
|
||||||
/*
|
/* Overwrite element tuple */
|
||||||
* We modified the tuples in place, no need to call
|
if (!PageIndexTupleOverwrite(page, offno, (Item) etup, etupSize))
|
||||||
* PageIndexTupleOverwrite
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
*/
|
|
||||||
|
/* Overwrite neighbor tuple */
|
||||||
|
if (!PageIndexTupleOverwrite(npage, neighborOffno, (Item) ntup, ntupSize))
|
||||||
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
@@ -575,7 +586,7 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
vacuumstate->bas = GetAccessStrategy(BAS_BULKREAD);
|
vacuumstate->bas = GetAccessStrategy(BAS_BULKREAD);
|
||||||
vacuumstate->procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
vacuumstate->procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
||||||
vacuumstate->collation = index->rd_indcollation[0];
|
vacuumstate->collation = index->rd_indcollation[0];
|
||||||
vacuumstate->ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
vacuumstate->ntup = palloc0(BLCKSZ);
|
||||||
vacuumstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
vacuumstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Hnsw vacuum temporary context",
|
"Hnsw vacuum temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
|
|||||||
105
src/ivfbuild.c
105
src/ivfbuild.c
@@ -2,38 +2,58 @@
|
|||||||
|
|
||||||
#include <float.h>
|
#include <float.h>
|
||||||
|
|
||||||
#include "access/table.h"
|
|
||||||
#include "access/tableam.h"
|
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "access/xact.h"
|
#include "access/xact.h"
|
||||||
#include "catalog/index.h"
|
#include "catalog/index.h"
|
||||||
#include "catalog/pg_operator_d.h"
|
#include "catalog/pg_operator_d.h"
|
||||||
#include "catalog/pg_type_d.h"
|
#include "catalog/pg_type_d.h"
|
||||||
#include "commands/progress.h"
|
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "optimizer/optimizer.h"
|
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
#include "tcop/tcopprot.h"
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_progress.h"
|
#include "utils/backend_progress.h"
|
||||||
#else
|
#elif PG_VERSION_NUM >= 120000
|
||||||
#include "pgstat.h"
|
#include "pgstat.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "access/tableam.h"
|
||||||
|
#include "commands/progress.h"
|
||||||
|
#else
|
||||||
|
#define PROGRESS_CREATEIDX_SUBPHASE 0
|
||||||
|
#define PROGRESS_CREATEIDX_TUPLES_TOTAL 0
|
||||||
|
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
#define CALLBACK_ITEM_POINTER ItemPointer tid
|
#define CALLBACK_ITEM_POINTER ItemPointer tid
|
||||||
#else
|
#else
|
||||||
#define CALLBACK_ITEM_POINTER HeapTuple hup
|
#define CALLBACK_ITEM_POINTER HeapTuple hup
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#define UpdateProgress(index, val) pgstat_progress_update_param(index, val)
|
||||||
|
#else
|
||||||
|
#define UpdateProgress(index, val) ((void)val)
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_status.h"
|
#include "utils/backend_status.h"
|
||||||
#include "utils/wait_event.h"
|
#include "utils/wait_event.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "access/table.h"
|
||||||
|
#include "optimizer/optimizer.h"
|
||||||
|
#else
|
||||||
|
#include "access/heapam.h"
|
||||||
|
#include "optimizer/planner.h"
|
||||||
|
#include "pgstat.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
#define PARALLEL_KEY_IVFFLAT_SHARED UINT64CONST(0xA000000000000001)
|
#define PARALLEL_KEY_IVFFLAT_SHARED UINT64CONST(0xA000000000000001)
|
||||||
#define PARALLEL_KEY_TUPLESORT UINT64CONST(0xA000000000000002)
|
#define PARALLEL_KEY_TUPLESORT UINT64CONST(0xA000000000000002)
|
||||||
#define PARALLEL_KEY_IVFFLAT_CENTERS UINT64CONST(0xA000000000000003)
|
#define PARALLEL_KEY_IVFFLAT_CENTERS UINT64CONST(0xA000000000000003)
|
||||||
@@ -130,8 +150,13 @@ SampleRows(IvfflatBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
BlockNumber targblock = BlockSampler_Next(&buildstate->bs);
|
BlockNumber targblock = BlockSampler_Next(&buildstate->bs);
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
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, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
|
||||||
|
#else
|
||||||
|
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
|
false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,12 +282,16 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
|||||||
IndexTuple itup = NULL; /* silence compiler warning */
|
IndexTuple itup = NULL; /* silence compiler warning */
|
||||||
int64 inserted = 0;
|
int64 inserted = 0;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsMinimalTuple);
|
TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsMinimalTuple);
|
||||||
|
#else
|
||||||
|
TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc);
|
||||||
|
#endif
|
||||||
TupleDesc tupdesc = RelationGetDescr(index);
|
TupleDesc tupdesc = RelationGetDescr(index);
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
|
||||||
|
|
||||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||||
|
|
||||||
@@ -298,7 +327,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
|||||||
|
|
||||||
pfree(itup);
|
pfree(itup);
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
|
||||||
|
|
||||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||||
}
|
}
|
||||||
@@ -346,12 +375,20 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
|||||||
elog(ERROR, "dimensions must be greater than one for this opclass");
|
elog(ERROR, "dimensions must be greater than one for this opclass");
|
||||||
|
|
||||||
/* Create tuple description for sorting */
|
/* Create tuple description for sorting */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
buildstate->tupdesc = CreateTemplateTupleDesc(3);
|
buildstate->tupdesc = CreateTemplateTupleDesc(3);
|
||||||
|
#else
|
||||||
|
buildstate->tupdesc = CreateTemplateTupleDesc(3, false);
|
||||||
|
#endif
|
||||||
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
|
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
|
||||||
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
|
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
|
||||||
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0);
|
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0);
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
|
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
|
||||||
|
#else
|
||||||
|
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc);
|
||||||
|
#endif
|
||||||
|
|
||||||
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions);
|
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions);
|
||||||
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
||||||
@@ -398,7 +435,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
int numSamples;
|
int numSamples;
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
||||||
|
|
||||||
/* Target 50 samples per list, with at least 10000 samples */
|
/* Target 50 samples per list, with at least 10000 samples */
|
||||||
/* The number of samples has a large effect on index build time */
|
/* The number of samples has a large effect on index build time */
|
||||||
@@ -473,7 +510,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
IvfflatList list;
|
IvfflatList list;
|
||||||
|
|
||||||
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
||||||
list = palloc0(listSize);
|
list = palloc(listSize);
|
||||||
|
|
||||||
buf = IvfflatNewBuffer(index, forkNum);
|
buf = IvfflatNewBuffer(index, forkNum);
|
||||||
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
||||||
@@ -594,7 +631,11 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
|
|||||||
{
|
{
|
||||||
SortCoordinate coordinate;
|
SortCoordinate coordinate;
|
||||||
IvfflatBuildState buildstate;
|
IvfflatBuildState buildstate;
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
TableScanDesc scan;
|
TableScanDesc scan;
|
||||||
|
#else
|
||||||
|
HeapScanDesc scan;
|
||||||
|
#endif
|
||||||
double reltuples;
|
double reltuples;
|
||||||
IndexInfo *indexInfo;
|
IndexInfo *indexInfo;
|
||||||
|
|
||||||
@@ -618,11 +659,18 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
|
|||||||
buildstate.centers->length = buildstate.centers->maxlen;
|
buildstate.centers->length = buildstate.centers->maxlen;
|
||||||
ivfspool->sortstate = tuplesort_begin_heap(buildstate.tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, sortmem, coordinate, false);
|
ivfspool->sortstate = tuplesort_begin_heap(buildstate.tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, sortmem, coordinate, false);
|
||||||
buildstate.sortstate = ivfspool->sortstate;
|
buildstate.sortstate = ivfspool->sortstate;
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan = table_beginscan_parallel(ivfspool->heap,
|
scan = table_beginscan_parallel(ivfspool->heap,
|
||||||
ParallelTableScanFromIvfflatShared(ivfshared));
|
ParallelTableScanFromIvfflatShared(ivfshared));
|
||||||
reltuples = table_index_build_scan(ivfspool->heap, ivfspool->index, indexInfo,
|
reltuples = table_index_build_scan(ivfspool->heap, ivfspool->index, indexInfo,
|
||||||
true, progress, BuildCallback,
|
true, progress, BuildCallback,
|
||||||
(void *) &buildstate, scan);
|
(void *) &buildstate, scan);
|
||||||
|
#else
|
||||||
|
scan = heap_beginscan_parallel(ivfspool->heap, &ivfshared->heapdesc);
|
||||||
|
reltuples = IndexBuildHeapScan(ivfspool->heap, ivfspool->index, indexInfo,
|
||||||
|
true, BuildCallback,
|
||||||
|
(void *) &buildstate, scan);
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Execute this worker's part of the sort */
|
/* Execute this worker's part of the sort */
|
||||||
tuplesort_performsort(ivfspool->sortstate);
|
tuplesort_performsort(ivfspool->sortstate);
|
||||||
@@ -692,7 +740,11 @@ IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Open relations within worker */
|
/* Open relations within worker */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
heapRel = table_open(ivfshared->heaprelid, heapLockmode);
|
heapRel = table_open(ivfshared->heaprelid, heapLockmode);
|
||||||
|
#else
|
||||||
|
heapRel = heap_open(ivfshared->heaprelid, heapLockmode);
|
||||||
|
#endif
|
||||||
indexRel = index_open(ivfshared->indexrelid, indexLockmode);
|
indexRel = index_open(ivfshared->indexrelid, indexLockmode);
|
||||||
|
|
||||||
/* Initialize worker's own spool */
|
/* Initialize worker's own spool */
|
||||||
@@ -712,7 +764,11 @@ IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
|||||||
|
|
||||||
/* Close relations within worker */
|
/* Close relations within worker */
|
||||||
index_close(indexRel, indexLockmode);
|
index_close(indexRel, indexLockmode);
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
table_close(heapRel, heapLockmode);
|
table_close(heapRel, heapLockmode);
|
||||||
|
#else
|
||||||
|
heap_close(heapRel, heapLockmode);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -737,7 +793,19 @@ IvfflatEndParallel(IvfflatLeader * ivfleader)
|
|||||||
static Size
|
static Size
|
||||||
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
||||||
{
|
{
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
return add_size(BUFFERALIGN(sizeof(IvfflatShared)), table_parallelscan_estimate(heap, snapshot));
|
return add_size(BUFFERALIGN(sizeof(IvfflatShared)), table_parallelscan_estimate(heap, snapshot));
|
||||||
|
#else
|
||||||
|
if (!IsMVCCSnapshot(snapshot))
|
||||||
|
{
|
||||||
|
Assert(snapshot == SnapshotAny);
|
||||||
|
return sizeof(IvfflatShared);
|
||||||
|
}
|
||||||
|
|
||||||
|
return add_size(offsetof(IvfflatShared, heapdesc) +
|
||||||
|
offsetof(ParallelHeapScanDescData, phs_snapshot_data),
|
||||||
|
EstimateSnapshotSpace(snapshot));
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -788,7 +856,11 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
|
|||||||
/* Enter parallel mode and create context */
|
/* Enter parallel mode and create context */
|
||||||
EnterParallelMode();
|
EnterParallelMode();
|
||||||
Assert(request > 0);
|
Assert(request > 0);
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
pcxt = CreateParallelContext("vector", "IvfflatParallelBuildMain", request);
|
pcxt = CreateParallelContext("vector", "IvfflatParallelBuildMain", request);
|
||||||
|
#else
|
||||||
|
pcxt = CreateParallelContext("vector", "IvfflatParallelBuildMain", request, true);
|
||||||
|
#endif
|
||||||
|
|
||||||
scantuplesortstates = leaderparticipates ? request + 1 : request;
|
scantuplesortstates = leaderparticipates ? request + 1 : request;
|
||||||
|
|
||||||
@@ -846,9 +918,13 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
|
|||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
ivfshared->inertia = 0;
|
ivfshared->inertia = 0;
|
||||||
#endif
|
#endif
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
table_parallelscan_initialize(buildstate->heap,
|
table_parallelscan_initialize(buildstate->heap,
|
||||||
ParallelTableScanFromIvfflatShared(ivfshared),
|
ParallelTableScanFromIvfflatShared(ivfshared),
|
||||||
snapshot);
|
snapshot);
|
||||||
|
#else
|
||||||
|
heap_parallelscan_initialize(&ivfshared->heapdesc, buildstate->heap, snapshot);
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Store shared tuplesort-private state, for which we reserved space */
|
/* Store shared tuplesort-private state, for which we reserved space */
|
||||||
sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
|
sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
|
||||||
@@ -919,7 +995,7 @@ AssignTuples(IvfflatBuildState * buildstate)
|
|||||||
Oid sortCollations[] = {InvalidOid};
|
Oid sortCollations[] = {InvalidOid};
|
||||||
bool nullsFirstFlags[] = {false};
|
bool nullsFirstFlags[] = {false};
|
||||||
|
|
||||||
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_ASSIGN);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_ASSIGN);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
/* Calculate parallel workers */
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
@@ -947,8 +1023,15 @@ AssignTuples(IvfflatBuildState * buildstate)
|
|||||||
if (buildstate->ivfleader)
|
if (buildstate->ivfleader)
|
||||||
buildstate->reltuples = ParallelHeapScan(buildstate);
|
buildstate->reltuples = ParallelHeapScan(buildstate);
|
||||||
else
|
else
|
||||||
|
{
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
true, true, BuildCallback, (void *) buildstate, NULL);
|
true, true, BuildCallback, (void *) buildstate, NULL);
|
||||||
|
#else
|
||||||
|
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
|
true, BuildCallback, (void *) buildstate, NULL);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
PrintKmeansMetrics(buildstate);
|
PrintKmeansMetrics(buildstate);
|
||||||
|
|||||||
@@ -3,16 +3,14 @@
|
|||||||
#include <float.h>
|
#include <float.h>
|
||||||
|
|
||||||
#include "access/amapi.h"
|
#include "access/amapi.h"
|
||||||
#include "access/reloptions.h"
|
|
||||||
#include "commands/progress.h"
|
|
||||||
#include "commands/vacuum.h"
|
#include "commands/vacuum.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "utils/guc.h"
|
#include "utils/guc.h"
|
||||||
#include "utils/selfuncs.h"
|
#include "utils/selfuncs.h"
|
||||||
#include "utils/spccache.h"
|
#include "utils/spccache.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 150000
|
#if PG_VERSION_NUM >= 120000
|
||||||
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
#include "commands/progress.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int ivfflat_probes;
|
int ivfflat_probes;
|
||||||
@@ -35,13 +33,12 @@ IvfflatInit(void)
|
|||||||
DefineCustomIntVariable("ivfflat.probes", "Sets the number of probes",
|
DefineCustomIntVariable("ivfflat.probes", "Sets the number of probes",
|
||||||
"Valid range is 1..lists.", &ivfflat_probes,
|
"Valid range is 1..lists.", &ivfflat_probes,
|
||||||
IVFFLAT_DEFAULT_PROBES, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, 0, NULL, NULL, NULL);
|
IVFFLAT_DEFAULT_PROBES, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||||
|
|
||||||
MarkGUCPrefixReserved("ivfflat");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the name of index build phase
|
* Get the name of index build phase
|
||||||
*/
|
*/
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
static char *
|
static char *
|
||||||
ivfflatbuildphasename(int64 phasenum)
|
ivfflatbuildphasename(int64 phasenum)
|
||||||
{
|
{
|
||||||
@@ -59,6 +56,7 @@ ivfflatbuildphasename(int64 phasenum)
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Estimate the cost of an index scan
|
* Estimate the cost of an index scan
|
||||||
@@ -74,6 +72,9 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
double ratio;
|
double ratio;
|
||||||
double spc_seq_page_cost;
|
double spc_seq_page_cost;
|
||||||
Relation index;
|
Relation index;
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
List *qinfos;
|
||||||
|
#endif
|
||||||
|
|
||||||
/* Never use index without order */
|
/* Never use index without order */
|
||||||
if (path->indexorderbys == NULL)
|
if (path->indexorderbys == NULL)
|
||||||
@@ -104,7 +105,12 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
*/
|
*/
|
||||||
costs.numIndexTuples = path->indexinfo->tuples * ratio;
|
costs.numIndexTuples = path->indexinfo->tuples * ratio;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
genericcostestimate(root, path, loop_count, &costs);
|
genericcostestimate(root, path, loop_count, &costs);
|
||||||
|
#else
|
||||||
|
qinfos = deconstruct_indexquals(path);
|
||||||
|
genericcostestimate(root, path, loop_count, qinfos, &costs);
|
||||||
|
#endif
|
||||||
|
|
||||||
get_tablespace_page_costs(path->indexinfo->reltablespace, NULL, &spc_seq_page_cost);
|
get_tablespace_page_costs(path->indexinfo->reltablespace, NULL, &spc_seq_page_cost);
|
||||||
|
|
||||||
@@ -221,7 +227,9 @@ ivfflathandler(PG_FUNCTION_ARGS)
|
|||||||
amroutine->amcostestimate = ivfflatcostestimate;
|
amroutine->amcostestimate = ivfflatcostestimate;
|
||||||
amroutine->amoptions = ivfflatoptions;
|
amroutine->amoptions = ivfflatoptions;
|
||||||
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
amroutine->ambuildphasename = ivfflatbuildphasename;
|
amroutine->ambuildphasename = ivfflatbuildphasename;
|
||||||
|
#endif
|
||||||
amroutine->amvalidate = ivfflatvalidate;
|
amroutine->amvalidate = ivfflatvalidate;
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
amroutine->amadjustmembers = NULL;
|
amroutine->amadjustmembers = NULL;
|
||||||
|
|||||||
@@ -3,10 +3,9 @@
|
|||||||
|
|
||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/genam.h"
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "access/reloptions.h"
|
||||||
#include "nodes/execnodes.h"
|
#include "nodes/execnodes.h"
|
||||||
#include "port.h" /* for random() */
|
#include "port.h" /* for random() */
|
||||||
#include "utils/sampling.h"
|
#include "utils/sampling.h"
|
||||||
@@ -17,6 +16,10 @@
|
|||||||
#include "common/pg_prng.h"
|
#include "common/pg_prng.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
#include "access/relscan.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifdef IVFFLAT_BENCH
|
#ifdef IVFFLAT_BENCH
|
||||||
#include "portability/instr_time.h"
|
#include "portability/instr_time.h"
|
||||||
#endif
|
#endif
|
||||||
@@ -132,10 +135,16 @@ typedef struct IvfflatShared
|
|||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
double inertia;
|
double inertia;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
ParallelHeapScanDescData heapdesc; /* must come last */
|
||||||
|
#endif
|
||||||
} IvfflatShared;
|
} IvfflatShared;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
#define ParallelTableScanFromIvfflatShared(shared) \
|
#define ParallelTableScanFromIvfflatShared(shared) \
|
||||||
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(IvfflatShared)))
|
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(IvfflatShared)))
|
||||||
|
#endif
|
||||||
|
|
||||||
typedef struct IvfflatLeader
|
typedef struct IvfflatLeader
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
#include <float.h>
|
#include <float.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "storage/lmgr.h"
|
#include "storage/lmgr.h"
|
||||||
|
|||||||
@@ -5,7 +5,6 @@
|
|||||||
#include "access/relscan.h"
|
#include "access/relscan.h"
|
||||||
#include "catalog/pg_operator_d.h"
|
#include "catalog/pg_operator_d.h"
|
||||||
#include "catalog/pg_type_d.h"
|
#include "catalog/pg_type_d.h"
|
||||||
#include "lib/pairingheap.h"
|
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "pgstat.h"
|
#include "pgstat.h"
|
||||||
@@ -106,7 +105,12 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||||
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
|
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
|
||||||
double tuples = 0;
|
double tuples = 0;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual);
|
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual);
|
||||||
|
#else
|
||||||
|
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc);
|
||||||
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Reuse same set of shared buffers for scan
|
* Reuse same set of shared buffers for scan
|
||||||
@@ -212,14 +216,22 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
so->collation = index->rd_indcollation[0];
|
so->collation = index->rd_indcollation[0];
|
||||||
|
|
||||||
/* Create tuple description for sorting */
|
/* Create tuple description for sorting */
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
so->tupdesc = CreateTemplateTupleDesc(2);
|
so->tupdesc = CreateTemplateTupleDesc(2);
|
||||||
|
#else
|
||||||
|
so->tupdesc = CreateTemplateTupleDesc(2, false);
|
||||||
|
#endif
|
||||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
||||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
|
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
|
||||||
|
|
||||||
/* Prep sort */
|
/* Prep sort */
|
||||||
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
|
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
so->slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple);
|
so->slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple);
|
||||||
|
#else
|
||||||
|
so->slot = MakeSingleTupleTableSlot(so->tupdesc);
|
||||||
|
#endif
|
||||||
|
|
||||||
so->listQueue = pairingheap_allocate(CompareLists, scan);
|
so->listQueue = pairingheap_allocate(CompareLists, scan);
|
||||||
|
|
||||||
@@ -309,8 +321,12 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
{
|
{
|
||||||
ItemPointer heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
|
ItemPointer heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan->xs_heaptid = *heaptid;
|
scan->xs_heaptid = *heaptid;
|
||||||
scan->xs_recheck = false;
|
#else
|
||||||
|
scan->xs_ctup.t_self = *heaptid;
|
||||||
|
#endif
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
|
||||||
#include "commands/vacuum.h"
|
#include "commands/vacuum.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
|
|||||||
29
src/vector.c
29
src/vector.c
@@ -3,7 +3,6 @@
|
|||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "catalog/pg_type.h"
|
#include "catalog/pg_type.h"
|
||||||
#include "common/shortest_dec.h"
|
|
||||||
#include "fmgr.h"
|
#include "fmgr.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
@@ -12,7 +11,6 @@
|
|||||||
#include "port.h" /* for strtof() */
|
#include "port.h" /* for strtof() */
|
||||||
#include "utils/array.h"
|
#include "utils/array.h"
|
||||||
#include "utils/builtins.h"
|
#include "utils/builtins.h"
|
||||||
#include "utils/float.h"
|
|
||||||
#include "utils/lsyscache.h"
|
#include "utils/lsyscache.h"
|
||||||
#include "utils/numeric.h"
|
#include "utils/numeric.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
@@ -21,6 +19,13 @@
|
|||||||
#include "varatt.h"
|
#include "varatt.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
|
#include "common/shortest_dec.h"
|
||||||
|
#include "utils/float.h"
|
||||||
|
#else
|
||||||
|
#include <float.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
#if PG_VERSION_NUM < 130000
|
||||||
#define TYPALIGN_DOUBLE 'd'
|
#define TYPALIGN_DOUBLE 'd'
|
||||||
#define TYPALIGN_INT 'i'
|
#define TYPALIGN_INT 'i'
|
||||||
@@ -172,15 +177,14 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_in);
|
|||||||
Datum
|
Datum
|
||||||
vector_in(PG_FUNCTION_ARGS)
|
vector_in(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
char *lit = PG_GETARG_CSTRING(0);
|
char *str = PG_GETARG_CSTRING(0);
|
||||||
int32 typmod = PG_GETARG_INT32(2);
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
float x[VECTOR_MAX_DIM];
|
float x[VECTOR_MAX_DIM];
|
||||||
int dim = 0;
|
int dim = 0;
|
||||||
char *pt;
|
char *pt;
|
||||||
char *stringEnd;
|
char *stringEnd;
|
||||||
Vector *result;
|
Vector *result;
|
||||||
char *litcopy = pstrdup(lit);
|
char *lit = pstrdup(str);
|
||||||
char *str = litcopy;
|
|
||||||
|
|
||||||
while (vector_isspace(*str))
|
while (vector_isspace(*str))
|
||||||
str++;
|
str++;
|
||||||
@@ -264,7 +268,7 @@ vector_in(PG_FUNCTION_ARGS)
|
|||||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
errmsg("vector must have at least 1 dimension")));
|
errmsg("vector must have at least 1 dimension")));
|
||||||
|
|
||||||
pfree(litcopy);
|
pfree(lit);
|
||||||
|
|
||||||
CheckExpectedDim(typmod, dim);
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
@@ -288,6 +292,15 @@ vector_out(PG_FUNCTION_ARGS)
|
|||||||
char *ptr;
|
char *ptr;
|
||||||
int n;
|
int n;
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM < 120000
|
||||||
|
int ndig = FLT_DIG + extra_float_digits;
|
||||||
|
|
||||||
|
if (ndig < 1)
|
||||||
|
ndig = 1;
|
||||||
|
|
||||||
|
#define FLOAT_SHORTEST_DECIMAL_LEN (ndig + 10)
|
||||||
|
#endif
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Need:
|
* Need:
|
||||||
*
|
*
|
||||||
@@ -311,7 +324,11 @@ vector_out(PG_FUNCTION_ARGS)
|
|||||||
ptr++;
|
ptr++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 120000
|
||||||
n = float_to_shortest_decimal_bufn(vector->x[i], ptr);
|
n = float_to_shortest_decimal_bufn(vector->x[i], ptr);
|
||||||
|
#else
|
||||||
|
n = sprintf(ptr, "%.*g", ndig, vector->x[i]);
|
||||||
|
#endif
|
||||||
ptr += n;
|
ptr += n;
|
||||||
}
|
}
|
||||||
*ptr = ']';
|
*ptr = ']';
|
||||||
|
|||||||
@@ -1,114 +0,0 @@
|
|||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use PostgresNode;
|
|
||||||
use TestLib;
|
|
||||||
use Test::More;
|
|
||||||
|
|
||||||
my $dim = 3;
|
|
||||||
my $nc = 50;
|
|
||||||
my $limit = 20;
|
|
||||||
|
|
||||||
my $array_sql = join(",", ('random()') x $dim);
|
|
||||||
|
|
||||||
# Initialize node
|
|
||||||
my $node = get_new_node('node');
|
|
||||||
$node->init;
|
|
||||||
$node->start;
|
|
||||||
|
|
||||||
# Create table and index
|
|
||||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
|
||||||
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim), c int4, t text);");
|
|
||||||
$node->safe_psql("postgres",
|
|
||||||
"INSERT INTO tst SELECT i, ARRAY[$array_sql], i % $nc, 'test ' || i FROM generate_series(1, 10000) i;"
|
|
||||||
);
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v vector_l2_ops);");
|
|
||||||
$node->safe_psql("postgres", "ANALYZE tst;");
|
|
||||||
|
|
||||||
# Generate query
|
|
||||||
my @r = ();
|
|
||||||
for (1 .. $dim)
|
|
||||||
{
|
|
||||||
push(@r, rand());
|
|
||||||
}
|
|
||||||
my $query = "[" . join(",", @r) . "]";
|
|
||||||
my $c = int(rand() * $nc);
|
|
||||||
|
|
||||||
# Test attribute filtering
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c != $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed comparison
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c >= 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with many rows removed comparison
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c < 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed like
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE t LIKE '%%test%%' ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with many rows removed like
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE t LIKE '%%other%%' ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test distance filtering
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test distance filtering greater than distance
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' > 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test distance filtering without order
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test distance filtering without limit
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1 ORDER BY v <-> '$query';
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test attribute index
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX attribute_idx ON tst (c);");
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Use attribute index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test partial index
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX partial_idx ON tst USING hnsw (v vector_l2_ops) WHERE (c = $c);");
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using partial_idx/);
|
|
||||||
|
|
||||||
done_testing();
|
|
||||||
43
test/t/018_ivfflat_deletes.pl
Normal file
43
test/t/018_ivfflat_deletes.pl
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $dim = 3;
|
||||||
|
|
||||||
|
my $array_sql = join(",", ('random()') x $dim);
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
my $node = get_new_node('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",
|
||||||
|
"INSERT INTO tst (v) SELECT ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v vector_l2_ops);");
|
||||||
|
|
||||||
|
# Delete data
|
||||||
|
$node->safe_psql("postgres", "DELETE FROM tst WHERE i % 100 != 0;");
|
||||||
|
|
||||||
|
my $exp = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_indexscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '[0,0,0]';
|
||||||
|
));
|
||||||
|
|
||||||
|
# Run twice to make sure correct tuples marked as dead
|
||||||
|
for (1 .. 2)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SET ivfflat.probes = 100;
|
||||||
|
SELECT i FROM tst ORDER BY v <-> '[0,0,0]';
|
||||||
|
));
|
||||||
|
is($res, $exp);
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use PostgresNode;
|
|
||||||
use TestLib;
|
|
||||||
use Test::More;
|
|
||||||
|
|
||||||
my $dim = 3;
|
|
||||||
my $nc = 50;
|
|
||||||
my $limit = 20;
|
|
||||||
|
|
||||||
my $array_sql = join(",", ('random()') x $dim);
|
|
||||||
|
|
||||||
# Initialize node
|
|
||||||
my $node = get_new_node('node');
|
|
||||||
$node->init;
|
|
||||||
$node->start;
|
|
||||||
|
|
||||||
# Create table and index
|
|
||||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
|
||||||
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim), c int4, t text);");
|
|
||||||
$node->safe_psql("postgres",
|
|
||||||
"INSERT INTO tst SELECT i, ARRAY[$array_sql], i % $nc, 'test ' || i FROM generate_series(1, 10000) i;"
|
|
||||||
);
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING ivfflat (v vector_l2_ops) WITH (lists = 100);");
|
|
||||||
$node->safe_psql("postgres", "ANALYZE tst;");
|
|
||||||
|
|
||||||
# Generate query
|
|
||||||
my @r = ();
|
|
||||||
for (1 .. $dim)
|
|
||||||
{
|
|
||||||
push(@r, rand());
|
|
||||||
}
|
|
||||||
my $query = "[" . join(",", @r) . "]";
|
|
||||||
my $c = int(rand() * $nc);
|
|
||||||
|
|
||||||
# Test attribute filtering
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c != $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed comparison
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c >= 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with many rows removed comparison
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c < 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with few rows removed like
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE t LIKE '%%test%%' ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute filtering with many rows removed like
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE t LIKE '%%other%%' ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test distance filtering
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test distance filtering greater than distance
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' > 1 ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test distance filtering without order
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test distance filtering without limit
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE v <-> '$query' < 1 ORDER BY v <-> '$query';
|
|
||||||
));
|
|
||||||
# TODO Do not use index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test attribute index
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX attribute_idx ON tst (c);");
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Use attribute index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
# Test partial index
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX partial_idx ON tst USING ivfflat (v vector_l2_ops) WITH (lists = 5) WHERE (c = $c);");
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst WHERE c = $c ORDER BY v <-> '$query' LIMIT $limit;
|
|
||||||
));
|
|
||||||
# TODO Use partial index
|
|
||||||
like($explain, qr/Index Scan using idx/);
|
|
||||||
|
|
||||||
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.6.0'
|
default_version = '0.5.1'
|
||||||
module_pathname = '$libdir/vector'
|
module_pathname = '$libdir/vector'
|
||||||
relocatable = true
|
relocatable = true
|
||||||
|
|||||||
Reference in New Issue
Block a user