mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 12:07:34 +08:00
Compare commits
121 Commits
hnsw-fast-
...
concat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ece6ed7a0d | ||
|
|
b64a1482d9 | ||
|
|
a5f2d70bc2 | ||
|
|
f3fcb5e005 | ||
|
|
3a6e0afb9c | ||
|
|
183d50bdbd | ||
|
|
bd776fee68 | ||
|
|
d30b113e4b | ||
|
|
fd3200f718 | ||
|
|
02c815d876 | ||
|
|
4b2a7cc49d | ||
|
|
da0ff998e9 | ||
|
|
cb36e24289 | ||
|
|
b1d0d4c7a3 | ||
|
|
1dc6514b66 | ||
|
|
6c53f7ca02 | ||
|
|
0d35a14198 | ||
|
|
3ea2ce89be | ||
|
|
62350b1589 | ||
|
|
dd57309281 | ||
|
|
c6ddf62a29 | ||
|
|
801be04d8b | ||
|
|
587e9ba97c | ||
|
|
d57047a935 | ||
|
|
f1db1f17e3 | ||
|
|
2f48c0fac4 | ||
|
|
84a8aa8176 | ||
|
|
f64ebbef50 | ||
|
|
ac8156509b | ||
|
|
82bf69b479 | ||
|
|
4be2f57916 | ||
|
|
91e3d2905f | ||
|
|
fe2406564f | ||
|
|
fa52511eaa | ||
|
|
447ef4d27a | ||
|
|
b36cd22ccc | ||
|
|
b447ae4989 | ||
|
|
efed873a3e | ||
|
|
14b278dec9 | ||
|
|
133a728e48 | ||
|
|
ca10cbaa7d | ||
|
|
eb29019a14 | ||
|
|
334c386a45 | ||
|
|
1cbd204f52 | ||
|
|
5ba62fca84 | ||
|
|
22cb2a3fe7 | ||
|
|
72b144906a | ||
|
|
a618c1bc78 | ||
|
|
f43cd0ed98 | ||
|
|
51df640961 | ||
|
|
2716a223a6 | ||
|
|
3697043898 | ||
|
|
c22740962c | ||
|
|
a55ecf3281 | ||
|
|
fecdd5794e | ||
|
|
281d4fcf60 | ||
|
|
5b43aaad5a | ||
|
|
797ce8034c | ||
|
|
cad9e22d9a | ||
|
|
a7d43904f7 | ||
|
|
ded649891b | ||
|
|
2d092016fc | ||
|
|
86b31fdf96 | ||
|
|
5023269f0d | ||
|
|
642ee1f423 | ||
|
|
270dd8189a | ||
|
|
ba2776850b | ||
|
|
0cc883b944 | ||
|
|
e8e69278eb | ||
|
|
a4893d9d5f | ||
|
|
10416b841f | ||
|
|
d0f13d4e7f | ||
|
|
705e71015f | ||
|
|
121f53b8ff | ||
|
|
8765e79ec2 | ||
|
|
7fff6cd138 | ||
|
|
571697fee7 | ||
|
|
f7eda7bd20 | ||
|
|
2260e13315 | ||
|
|
90e0a14bda | ||
|
|
c816b5d0d1 | ||
|
|
b7b11cd8d5 | ||
|
|
54c560c5cb | ||
|
|
8a6c52f649 | ||
|
|
c8be3a369b | ||
|
|
e5d1a6bdbb | ||
|
|
f31d708c2b | ||
|
|
a1b1c99ff7 | ||
|
|
3ace98add6 | ||
|
|
083008c21e | ||
|
|
a1e526ef82 | ||
|
|
8ffb3718a4 | ||
|
|
2d0f162bd7 | ||
|
|
4c6928bd3c | ||
|
|
6fd05dd6f6 | ||
|
|
70106f5413 | ||
|
|
44b90be452 | ||
|
|
31572a7b28 | ||
|
|
2427290ea9 | ||
|
|
ca71ef7a51 | ||
|
|
8bd01ff006 | ||
|
|
cdb1c9a6d3 | ||
|
|
bf34ceef7c | ||
|
|
61b1566ea2 | ||
|
|
91acc3c178 | ||
|
|
885dd5b665 | ||
|
|
2a7b38bf1f | ||
|
|
4bd4a0996b | ||
|
|
490522b883 | ||
|
|
a1a38156d7 | ||
|
|
042ddfdc8a | ||
|
|
56870ce04d | ||
|
|
4ab77f3d24 | ||
|
|
cc9e6a6778 | ||
|
|
8f1b669c4f | ||
|
|
1ff9ab5133 | ||
|
|
4894dc5da1 | ||
|
|
7390f31261 | ||
|
|
b7304a3a4a | ||
|
|
018ceb7a46 | ||
|
|
0b2be00622 |
34
.github/workflows/build.yml
vendored
34
.github/workflows/build.yml
vendored
@@ -20,8 +20,6 @@ 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
|
||||||
@@ -30,7 +28,7 @@ jobs:
|
|||||||
dev-files: true
|
dev-files: true
|
||||||
- run: make
|
- run: make
|
||||||
env:
|
env:
|
||||||
PG_CFLAGS: -Wall -Wextra -Werror -Wno-unused-parameter -Wno-sign-compare
|
PG_CFLAGS: -DUSE_ASSERT_CHECKING -Wall -Wextra -Werror -Wno-unused-parameter -Wno-sign-compare
|
||||||
- run: |
|
- run: |
|
||||||
export PG_CONFIG=`which pg_config`
|
export PG_CONFIG=`which pg_config`
|
||||||
sudo --preserve-env=PG_CONFIG make install
|
sudo --preserve-env=PG_CONFIG make install
|
||||||
@@ -51,7 +49,7 @@ jobs:
|
|||||||
postgres-version: 14
|
postgres-version: 14
|
||||||
- run: make
|
- run: make
|
||||||
env:
|
env:
|
||||||
PG_CFLAGS: -Wall -Wextra -Werror -Wno-unused-parameter
|
PG_CFLAGS: -DUSE_ASSERT_CHECKING -Wall -Wextra -Werror -Wno-unused-parameter
|
||||||
- run: make install
|
- run: make install
|
||||||
- run: make installcheck
|
- run: make installcheck
|
||||||
- if: ${{ failure() }}
|
- if: ${{ failure() }}
|
||||||
@@ -59,10 +57,12 @@ 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_5.tar.gz
|
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_10.tar.gz
|
||||||
tar xf REL_14_5.tar.gz
|
tar xf REL_14_10.tar.gz
|
||||||
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
|
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_10/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
|
||||||
|
env:
|
||||||
|
PG_CFLAGS: -DUSE_ASSERT_CHECKING
|
||||||
windows:
|
windows:
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
if: ${{ !startsWith(github.ref_name, 'mac') }}
|
if: ${{ !startsWith(github.ref_name, 'mac') }}
|
||||||
@@ -73,6 +73,7 @@ jobs:
|
|||||||
postgres-version: 14
|
postgres-version: 14
|
||||||
- run: |
|
- run: |
|
||||||
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
|
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
|
||||||
|
cd %TEMP% && ^
|
||||||
nmake /NOLOGO /F Makefile.win && ^
|
nmake /NOLOGO /F Makefile.win && ^
|
||||||
nmake /NOLOGO /F Makefile.win install && ^
|
nmake /NOLOGO /F Makefile.win install && ^
|
||||||
nmake /NOLOGO /F Makefile.win installcheck && ^
|
nmake /NOLOGO /F Makefile.win installcheck && ^
|
||||||
@@ -83,10 +84,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:11
|
image: debian:12
|
||||||
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-13 postgresql-server-dev-13 sudo
|
- run: apt-get update && apt-get install -y build-essential git libipc-run-perl postgresql-15 postgresql-server-dev-15 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
|
||||||
@@ -99,4 +100,15 @@ jobs:
|
|||||||
sudo -u postgres make installcheck
|
sudo -u postgres make installcheck
|
||||||
sudo -u postgres make prove_installcheck
|
sudo -u postgres make prove_installcheck
|
||||||
env:
|
env:
|
||||||
PG_CFLAGS: -Wall -Wextra -Werror -Wno-unused-parameter -Wno-sign-compare
|
PG_CFLAGS: -DUSE_ASSERT_CHECKING -Wall -Wextra -Werror -Wno-unused-parameter -Wno-sign-compare
|
||||||
|
valgrind:
|
||||||
|
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: ankane/setup-postgres-valgrind@v1
|
||||||
|
with:
|
||||||
|
postgres-version: 16
|
||||||
|
- run: make
|
||||||
|
- run: sudo --preserve-env=PG_CONFIG make install
|
||||||
|
- run: make installcheck
|
||||||
|
|||||||
32
CHANGELOG.md
32
CHANGELOG.md
@@ -1,10 +1,32 @@
|
|||||||
## 0.5.2 (unreleased)
|
## 0.7.0 (unreleased)
|
||||||
|
|
||||||
|
- Added concatenate operator for vectors
|
||||||
|
|
||||||
|
## 0.6.2 (unreleased)
|
||||||
|
|
||||||
|
- Reduced lock contention with parallel HNSW index builds
|
||||||
|
|
||||||
|
## 0.6.1 (2024-03-04)
|
||||||
|
|
||||||
|
- Fixed error with `ANALYZE` and vectors with different dimensions
|
||||||
|
- Fixed error with `shared_preload_libraries`
|
||||||
|
- Fixed vector subtraction being marked as commutative
|
||||||
|
|
||||||
|
## 0.6.0 (2024-01-29)
|
||||||
|
|
||||||
|
If upgrading with Postgres 12 or Docker, see [these notes](https://github.com/pgvector/pgvector#060).
|
||||||
|
|
||||||
- Improved performance of HNSW
|
|
||||||
- Added support for parallel index builds for HNSW
|
- Added support for parallel index builds for HNSW
|
||||||
|
- Added validation for GUC parameters
|
||||||
|
- Changed storage for vector from `extended` to `external`
|
||||||
|
- Improved performance of 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 `invalid memory alloc request size` error with HNSW index build
|
- Fixed error with logical replication
|
||||||
|
- 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)
|
||||||
|
|
||||||
@@ -52,7 +74,7 @@
|
|||||||
|
|
||||||
## 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#040).
|
If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgvector/blob/v0.4.0/README.md#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`
|
||||||
@@ -69,7 +91,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#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/blob/v0.3.1/README.md#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=15
|
ARG PG_MAJOR=16
|
||||||
FROM postgres:$PG_MAJOR
|
FROM postgres:$PG_MAJOR
|
||||||
ARG PG_MAJOR
|
ARG PG_MAJOR
|
||||||
|
|
||||||
|
|||||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
|||||||
Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
|
Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
|
||||||
|
|
||||||
Portions Copyright (c) 1994, The Regents of the University of California
|
Portions Copyright (c) 1994, The Regents of the University of California
|
||||||
|
|
||||||
|
|||||||
@@ -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.5.1",
|
"version": "0.6.1",
|
||||||
"maintainer": [
|
"maintainer": [
|
||||||
"Andrew Kane <andrew@ankane.org>"
|
"Andrew Kane <andrew@ankane.org>"
|
||||||
],
|
],
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
"prereqs": {
|
"prereqs": {
|
||||||
"runtime": {
|
"runtime": {
|
||||||
"requires": {
|
"requires": {
|
||||||
"PostgreSQL": "11.0.0"
|
"PostgreSQL": "12.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"vector": {
|
"vector": {
|
||||||
"file": "sql/vector.sql",
|
"file": "sql/vector.sql",
|
||||||
"docfile": "README.md",
|
"docfile": "README.md",
|
||||||
"version": "0.5.1",
|
"version": "0.6.1",
|
||||||
"abstract": "Open-source vector similarity search for Postgres"
|
"abstract": "Open-source vector similarity search for Postgres"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
10
Makefile
10
Makefile
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.5.1
|
EXTVERSION = 0.6.1
|
||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
@@ -65,13 +65,15 @@ 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 --platform linux/amd64 -t ankane/pgvector:latest .
|
docker build --pull --no-cache --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(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 -t ankane/pgvector:latest .
|
docker buildx build --push --pull --no-cache --platform linux/amd64,linux/arm64 --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(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.5.1
|
EXTVERSION = 0.6.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
|
||||||
|
|||||||
273
README.md
273
README.md
@@ -14,19 +14,46 @@ Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recove
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
Compile and install the extension (supports Postgres 11+)
|
### Linux and Mac
|
||||||
|
|
||||||
|
Compile and install the extension (supports Postgres 12+)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.6.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
make
|
make
|
||||||
make install # may need sudo
|
make install # may need sudo
|
||||||
```
|
```
|
||||||
|
|
||||||
See the [installation notes](#installation-notes) if you run into issues
|
See the [installation notes](#installation-notes---linux-and-mac) 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), [pkg](#pkg), 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"
|
||||||
|
cd %TEMP%
|
||||||
|
git clone --branch v0.6.1 https://github.com/pgvector/pgvector.git
|
||||||
|
cd pgvector
|
||||||
|
nmake /F Makefile.win
|
||||||
|
nmake /F Makefile.win install
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [installation notes](#installation-notes---windows) if you run into issues
|
||||||
|
|
||||||
|
You can also install it with [Docker](#docker) or [conda-forge](#conda-forge).
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
@@ -78,6 +105,12 @@ Insert vectors
|
|||||||
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
|
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Or load vectors in bulk using `COPY` ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/bulk_loading.py))
|
||||||
|
|
||||||
|
```sql
|
||||||
|
COPY items (embedding) FROM STDIN WITH (FORMAT BINARY);
|
||||||
|
```
|
||||||
|
|
||||||
Upsert vectors
|
Upsert vectors
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -240,6 +273,16 @@ 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
|
||||||
|
|
||||||
|
Like other index types, it’s faster to create an index after loading your initial data
|
||||||
|
|
||||||
|
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+
|
||||||
@@ -304,6 +347,16 @@ 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+
|
||||||
@@ -360,13 +413,39 @@ You can use [Reciprocal Rank Fusion](https://github.com/pgvector/pgvector-python
|
|||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
|
### Tuning
|
||||||
|
|
||||||
|
Use a tool like [PgTune](https://pgtune.leopard.in.ua/) to set initial values for Postgres server parameters.
|
||||||
|
|
||||||
|
### Loading
|
||||||
|
|
||||||
|
Use `COPY` for bulk loading data ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/bulk_loading.py)).
|
||||||
|
|
||||||
|
```sql
|
||||||
|
COPY items (embedding) FROM STDIN WITH (FORMAT BINARY);
|
||||||
|
```
|
||||||
|
|
||||||
|
Add any indexes *after* loading the initial data for best performance.
|
||||||
|
|
||||||
|
### Indexing
|
||||||
|
|
||||||
|
See index build time for [HNSW](#index-build-time) and [IVFFlat](#index-build-time-1).
|
||||||
|
|
||||||
|
In production environments, create indexes concurrently to avoid blocking writes.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX CONCURRENTLY ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Querying
|
||||||
|
|
||||||
Use `EXPLAIN ANALYZE` to debug performance.
|
Use `EXPLAIN ANALYZE` to debug performance.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
|
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Exact Search
|
#### Exact Search
|
||||||
|
|
||||||
To speed up queries without an index, increase `max_parallel_workers_per_gather`.
|
To speed up queries without an index, increase `max_parallel_workers_per_gather`.
|
||||||
|
|
||||||
@@ -380,7 +459,7 @@ If vectors are normalized to length 1 (like [OpenAI embeddings](https://platform
|
|||||||
SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
|
SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Approximate Search
|
#### Approximate Search
|
||||||
|
|
||||||
To speed up queries with an IVFFlat index, increase the number of inverted lists (at the expense of recall).
|
To speed up queries with an IVFFlat index, increase the number of inverted lists (at the expense of recall).
|
||||||
|
|
||||||
@@ -388,6 +467,50 @@ To speed up queries with an IVFFlat index, increase the number of inverted lists
|
|||||||
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
|
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Vacuuming
|
||||||
|
|
||||||
|
Vacuuming can take a while for HNSW indexes. Speed it up by reindexing first.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
REINDEX INDEX CONCURRENTLY index_name;
|
||||||
|
VACUUM table_name;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
Monitor performance with [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) (be sure to add it to `shared_preload_libraries`).
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE EXTENSION pg_stat_statements;
|
||||||
|
```
|
||||||
|
|
||||||
|
Get the most time-consuming queries with:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT query, calls, ROUND((total_plan_time + total_exec_time) / calls) AS avg_time_ms,
|
||||||
|
ROUND((total_plan_time + total_exec_time) / 60000) AS total_time_min
|
||||||
|
FROM pg_stat_statements ORDER BY total_plan_time + total_exec_time DESC LIMIT 20;
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: Replace `total_plan_time + total_exec_time` with `total_time` for Postgres < 13
|
||||||
|
|
||||||
|
Monitor recall by comparing results from approximate search with exact search.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
BEGIN;
|
||||||
|
SET LOCAL enable_indexscan = off; -- use exact search
|
||||||
|
SELECT ...
|
||||||
|
COMMIT;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scaling
|
||||||
|
|
||||||
|
Scale pgvector the same way you scale Postgres.
|
||||||
|
|
||||||
|
Scale vertically by increasing memory, CPU, and storage on a single instance. Use existing tools to [tune parameters](#tuning) and [monitor performance](#monitoring).
|
||||||
|
|
||||||
|
Scale horizontally with [replicas](https://www.postgresql.org/docs/current/hot-standby.html), or use [Citus](https://github.com/citusdata/citus) or another approach for sharding ([example](https://github.com/pgvector/pgvector-python/blob/master/examples/citus.py)).
|
||||||
|
|
||||||
## Languages
|
## Languages
|
||||||
|
|
||||||
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
|
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
|
||||||
@@ -493,7 +616,17 @@ SELECT pg_size_pretty(pg_relation_size('index_name'));
|
|||||||
|
|
||||||
#### Why isn’t a query using an index?
|
#### Why isn’t a query using an index?
|
||||||
|
|
||||||
The cost estimation in pgvector < 0.4.3 does not always work well with the planner. You can encourage the planner to use an index for a query with:
|
The query needs to have an `ORDER BY` and `LIMIT`, and the `ORDER BY` must be the result of a distance operator, not an expression.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- index
|
||||||
|
ORDER BY embedding <=> '[3,1,2]' LIMIT 5;
|
||||||
|
|
||||||
|
-- no index
|
||||||
|
ORDER BY 1 - (embedding <=> '[3,1,2]') DESC LIMIT 5;
|
||||||
|
```
|
||||||
|
|
||||||
|
You can encourage the planner to use an index for a query with:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
BEGIN;
|
BEGIN;
|
||||||
@@ -522,6 +655,10 @@ or choose to store vectors inline:
|
|||||||
ALTER TABLE items ALTER COLUMN embedding SET STORAGE PLAIN;
|
ALTER TABLE items ALTER COLUMN embedding SET STORAGE PLAIN;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Why are there less results for a query after adding an HNSW index?
|
||||||
|
|
||||||
|
Results are limited by the size of the dynamic candidate list (`hnsw.ef_search`). There may be even less results due to dead tuples or filtering conditions in the query. We recommend setting `hnsw.ef_search` to at least twice the `LIMIT` of the query. If you need more than 500 results, use an IVFFlat index instead.
|
||||||
|
|
||||||
#### Why are there less results for a query after adding an IVFFlat index?
|
#### Why are there less results for a query after adding an IVFFlat index?
|
||||||
|
|
||||||
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
|
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
|
||||||
@@ -530,6 +667,8 @@ The index was likely created with too little data for the number of lists. Drop
|
|||||||
DROP INDEX index_name;
|
DROP INDEX index_name;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Results can also be limited by the number of probes (`ivfflat.probes`).
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
### Vector Type
|
### Vector Type
|
||||||
@@ -543,6 +682,7 @@ Operator | Description | Added
|
|||||||
\+ | element-wise addition |
|
\+ | element-wise addition |
|
||||||
\- | element-wise subtraction |
|
\- | element-wise subtraction |
|
||||||
\* | element-wise multiplication | 0.5.0
|
\* | element-wise multiplication | 0.5.0
|
||||||
|
\|\| | concatenate | 0.7.0
|
||||||
<-> | Euclidean distance |
|
<-> | Euclidean distance |
|
||||||
<#> | negative inner product |
|
<#> | negative inner product |
|
||||||
<=> | cosine distance |
|
<=> | cosine distance |
|
||||||
@@ -565,14 +705,14 @@ Function | Description | Added
|
|||||||
avg(vector) → vector | average |
|
avg(vector) → vector | average |
|
||||||
sum(vector) → vector | sum | 0.5.0
|
sum(vector) → vector | sum | 0.5.0
|
||||||
|
|
||||||
## Installation Notes
|
## Installation Notes - Linux and Mac
|
||||||
|
|
||||||
### Postgres Location
|
### Postgres Location
|
||||||
|
|
||||||
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=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
|
export PG_CONFIG=/Library/PostgreSQL/16/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:
|
||||||
@@ -581,6 +721,14 @@ 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.
|
||||||
@@ -593,44 +741,48 @@ sudo apt install postgresql-server-dev-16
|
|||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `16` with your Postgres server version
|
||||||
|
|
||||||
### Windows
|
### Missing SDK
|
||||||
|
|
||||||
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:
|
If compilation fails and the output includes `warning: no such sysroot directory` on Mac, reinstall Xcode Command Line Tools.
|
||||||
|
|
||||||
```cmd
|
### Portability
|
||||||
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
|
|
||||||
|
By default, pgvector compiles with `-march=native` on some platforms for best performance. However, this can lead to `Illegal instruction` errors if trying to run the compiled extension on a different machine.
|
||||||
|
|
||||||
|
To compile for portability, use:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make OPTFLAGS=""
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: The exact path will vary depending on your Visual Studio version and edition
|
## Installation Notes - Windows
|
||||||
|
|
||||||
Then use `nmake` to build:
|
### Missing Header
|
||||||
|
|
||||||
```cmd
|
If compilation fails with `Cannot open include file: 'postgres.h': No such file or directory`, make sure `PGROOT` is correct.
|
||||||
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
### Permissions
|
||||||
cd pgvector
|
|
||||||
nmake /F Makefile.win
|
If installation fails with `Access is denied`, re-run the installation instructions as an administrator.
|
||||||
nmake /F Makefile.win install
|
|
||||||
```
|
|
||||||
|
|
||||||
## Additional Installation Methods
|
## Additional Installation Methods
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
|
|
||||||
Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
|
Get the [Docker image](https://hub.docker.com/r/pgvector/pgvector) with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker pull ankane/pgvector
|
docker pull pgvector/pgvector:pg16
|
||||||
```
|
```
|
||||||
|
|
||||||
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) (replace `16` with your Postgres server version, and run it the same way).
|
||||||
|
|
||||||
You can also build the image manually:
|
You can also build the image manually:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.6.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
docker build --build-arg PG_MAJOR=15 -t myuser/pgvector .
|
docker build --build-arg PG_MAJOR=16 -t myuser/pgvector .
|
||||||
```
|
```
|
||||||
|
|
||||||
### Homebrew
|
### Homebrew
|
||||||
@@ -673,6 +825,21 @@ sudo dnf install pgvector_16
|
|||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `16` with your Postgres server version
|
||||||
|
|
||||||
|
### pkg
|
||||||
|
|
||||||
|
Install the FreeBSD package with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pkg install postgresql15-pg_vector
|
||||||
|
```
|
||||||
|
|
||||||
|
or the port with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /usr/ports/databases/pgvector
|
||||||
|
make install
|
||||||
|
```
|
||||||
|
|
||||||
### conda-forge
|
### conda-forge
|
||||||
|
|
||||||
With Conda Postgres, install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with:
|
With Conda Postgres, install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with:
|
||||||
@@ -707,28 +874,32 @@ SELECT extversion FROM pg_extension WHERE extname = 'vector';
|
|||||||
|
|
||||||
## Upgrade Notes
|
## Upgrade Notes
|
||||||
|
|
||||||
### 0.4.0
|
### 0.6.0
|
||||||
|
|
||||||
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
|
#### Postgres 12
|
||||||
|
|
||||||
|
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 = extended);
|
ALTER TYPE vector SET (STORAGE = external);
|
||||||
```
|
```
|
||||||
|
|
||||||
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
|
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
|
||||||
|
|
||||||
### 0.3.1
|
#### Docker
|
||||||
|
|
||||||
If upgrading from 0.2.7 or 0.3.0, recreate all `ivfflat` indexes after upgrading to ensure all data is indexed.
|
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).
|
||||||
|
|
||||||
```sql
|
```sh
|
||||||
-- Postgres 12+
|
docker pull pgvector/pgvector:pg16
|
||||||
REINDEX INDEX CONCURRENTLY index_name;
|
# or
|
||||||
|
docker pull pgvector/pgvector:0.6.0-pg16
|
||||||
|
```
|
||||||
|
|
||||||
-- Postgres < 12
|
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.
|
||||||
CREATE INDEX CONCURRENTLY temp_name ON table USING ivfflat (column opclass);
|
|
||||||
DROP INDEX CONCURRENTLY index_name;
|
```sh
|
||||||
ALTER INDEX temp_name RENAME TO index_name;
|
docker run --shm-size=1g ...
|
||||||
```
|
```
|
||||||
|
|
||||||
## Thanks
|
## Thanks
|
||||||
@@ -774,14 +945,32 @@ 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_wal.pl # TAP test
|
make prove_installcheck PROVE_TESTS=test/t/001_ivfflat_wal.pl # TAP test
|
||||||
|
```
|
||||||
|
|
||||||
|
To enable assertions:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make clean && PG_CFLAGS="-DUSE_ASSERT_CHECKING" make && make install
|
||||||
```
|
```
|
||||||
|
|
||||||
To enable benchmarking:
|
To enable benchmarking:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
|
make clean && PG_CFLAGS="-DIVFFLAT_BENCH" make && make install
|
||||||
|
```
|
||||||
|
|
||||||
|
To show memory usage:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make clean && PG_CFLAGS="-DHNSW_MEMORY -DIVFFLAT_MEMORY" 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
|
||||||
|
|||||||
5
sql/vector--0.5.1--0.6.0.sql
Normal file
5
sql/vector--0.5.1--0.6.0.sql
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
-- 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);
|
||||||
16
sql/vector--0.6.0--0.6.1.sql
Normal file
16
sql/vector--0.6.0--0.6.1.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.6.1'" to load this file. \quit
|
||||||
|
|
||||||
|
DROP OPERATOR - (vector, vector);
|
||||||
|
|
||||||
|
CREATE OPERATOR - (
|
||||||
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_sub
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER OPERATOR <= (vector, vector) SET (
|
||||||
|
RESTRICT = scalarlesel, JOIN = scalarlejoinsel
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER OPERATOR >= (vector, vector) SET (
|
||||||
|
RESTRICT = scalargesel, JOIN = scalargejoinsel
|
||||||
|
);
|
||||||
9
sql/vector--0.6.2--0.7.0.sql
Normal file
9
sql/vector--0.6.2--0.7.0.sql
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.7.0'" to load this file. \quit
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_concat(vector, vector) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE OPERATOR || (
|
||||||
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_concat
|
||||||
|
);
|
||||||
@@ -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 = extended
|
STORAGE = external
|
||||||
);
|
);
|
||||||
|
|
||||||
-- functions
|
-- functions
|
||||||
@@ -99,6 +99,9 @@ CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
|
|||||||
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
|
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_concat(vector, vector) RETURNS vector
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
-- aggregates
|
-- aggregates
|
||||||
|
|
||||||
CREATE AGGREGATE avg(vector) (
|
CREATE AGGREGATE avg(vector) (
|
||||||
@@ -180,8 +183,7 @@ CREATE OPERATOR + (
|
|||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR - (
|
CREATE OPERATOR - (
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_sub,
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_sub
|
||||||
COMMUTATOR = -
|
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR * (
|
CREATE OPERATOR * (
|
||||||
@@ -195,11 +197,10 @@ CREATE OPERATOR < (
|
|||||||
RESTRICT = scalarltsel, JOIN = scalarltjoinsel
|
RESTRICT = scalarltsel, JOIN = scalarltjoinsel
|
||||||
);
|
);
|
||||||
|
|
||||||
-- should use scalarlesel and scalarlejoinsel, but not supported in Postgres < 11
|
|
||||||
CREATE OPERATOR <= (
|
CREATE OPERATOR <= (
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_le,
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_le,
|
||||||
COMMUTATOR = >= , NEGATOR = > ,
|
COMMUTATOR = >= , NEGATOR = > ,
|
||||||
RESTRICT = scalarltsel, JOIN = scalarltjoinsel
|
RESTRICT = scalarlesel, JOIN = scalarlejoinsel
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR = (
|
CREATE OPERATOR = (
|
||||||
@@ -214,11 +215,10 @@ CREATE OPERATOR <> (
|
|||||||
RESTRICT = eqsel, JOIN = eqjoinsel
|
RESTRICT = eqsel, JOIN = eqjoinsel
|
||||||
);
|
);
|
||||||
|
|
||||||
-- should use scalargesel and scalargejoinsel, but not supported in Postgres < 11
|
|
||||||
CREATE OPERATOR >= (
|
CREATE OPERATOR >= (
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_ge,
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_ge,
|
||||||
COMMUTATOR = <= , NEGATOR = < ,
|
COMMUTATOR = <= , NEGATOR = < ,
|
||||||
RESTRICT = scalargtsel, JOIN = scalargtjoinsel
|
RESTRICT = scalargesel, JOIN = scalargejoinsel
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR > (
|
CREATE OPERATOR > (
|
||||||
@@ -227,6 +227,10 @@ CREATE OPERATOR > (
|
|||||||
RESTRICT = scalargtsel, JOIN = scalargtjoinsel
|
RESTRICT = scalargtsel, JOIN = scalargtjoinsel
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR || (
|
||||||
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_concat
|
||||||
|
);
|
||||||
|
|
||||||
-- access methods
|
-- access methods
|
||||||
|
|
||||||
CREATE FUNCTION ivfflathandler(internal) RETURNS index_am_handler
|
CREATE FUNCTION ivfflathandler(internal) RETURNS index_am_handler
|
||||||
|
|||||||
26
src/hnsw.c
26
src/hnsw.c
@@ -4,13 +4,16 @@
|
|||||||
#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 "miscadmin.h"
|
||||||
#include "utils/guc.h"
|
#include "utils/guc.h"
|
||||||
#include "utils/selfuncs.h"
|
#include "utils/selfuncs.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM < 150000
|
||||||
#include "commands/progress.h"
|
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int hnsw_ef_search;
|
int hnsw_ef_search;
|
||||||
@@ -26,7 +29,7 @@ static relopt_kind hnsw_relopt_kind;
|
|||||||
* this grows bigger, we should use a shmem_request_hook and
|
* this grows bigger, we should use a shmem_request_hook and
|
||||||
* RequestAddinShmemSpace() to pre-reserve space for this.
|
* RequestAddinShmemSpace() to pre-reserve space for this.
|
||||||
*/
|
*/
|
||||||
static void
|
void
|
||||||
HnswInitLockTranche(void)
|
HnswInitLockTranche(void)
|
||||||
{
|
{
|
||||||
int *tranche_ids;
|
int *tranche_ids;
|
||||||
@@ -51,7 +54,8 @@ HnswInitLockTranche(void)
|
|||||||
void
|
void
|
||||||
HnswInit(void)
|
HnswInit(void)
|
||||||
{
|
{
|
||||||
HnswInitLockTranche();
|
if (!process_shared_preload_libraries_in_progress)
|
||||||
|
HnswInitLockTranche();
|
||||||
|
|
||||||
hnsw_relopt_kind = add_reloption_kind();
|
hnsw_relopt_kind = add_reloption_kind();
|
||||||
add_int_reloption(hnsw_relopt_kind, "m", "Max number of connections",
|
add_int_reloption(hnsw_relopt_kind, "m", "Max number of connections",
|
||||||
@@ -70,12 +74,13 @@ 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)
|
||||||
{
|
{
|
||||||
@@ -89,7 +94,6 @@ hnswbuildphasename(int64 phasenum)
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Estimate the cost of an index scan
|
* Estimate the cost of an index scan
|
||||||
@@ -104,9 +108,6 @@ 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)
|
||||||
@@ -132,12 +133,7 @@ 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;
|
||||||
@@ -231,9 +227,7 @@ 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;
|
||||||
|
|||||||
49
src/hnsw.h
49
src/hnsw.h
@@ -3,21 +3,17 @@
|
|||||||
|
|
||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/genam.h"
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "access/reloptions.h"
|
#include "lib/pairingheap.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
|
||||||
#include "access/relscan.h"
|
#error "Requires PostgreSQL 12+"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define HNSW_MAX_DIM 2000
|
#define HNSW_MAX_DIM 2000
|
||||||
@@ -64,10 +60,13 @@
|
|||||||
#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))
|
||||||
|
|
||||||
@@ -81,7 +80,7 @@
|
|||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
#if PG_VERSION_NUM < 130000
|
||||||
#define list_delete_last(list) list_truncate(list, list_length(list) - 1)
|
#define list_delete_last(list) list_truncate(list, list_length(list) - 1)
|
||||||
#define list_sort(list, cmp) list_qsort(list, cmp)
|
#define list_sort(list, cmp) ((list) = list_qsort(list, cmp))
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define HnswIsElementTuple(tup) ((tup)->type == HNSW_ELEMENT_TUPLE_TYPE)
|
#define HnswIsElementTuple(tup) ((tup)->type == HNSW_ELEMENT_TUPLE_TYPE)
|
||||||
@@ -114,8 +113,6 @@
|
|||||||
|
|
||||||
/* 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;
|
||||||
@@ -132,7 +129,7 @@ HnswPtrDeclare(HnswNeighborArray, HnswNeighborArrayRelptr, HnswNeighborArrayPtr)
|
|||||||
HnswPtrDeclare(HnswNeighborArrayPtr, HnswNeighborsRelptr, HnswNeighborsPtr);
|
HnswPtrDeclare(HnswNeighborArrayPtr, HnswNeighborsRelptr, HnswNeighborsPtr);
|
||||||
HnswPtrDeclare(char, DatumRelptr, DatumPtr);
|
HnswPtrDeclare(char, DatumRelptr, DatumPtr);
|
||||||
|
|
||||||
typedef struct HnswElementData
|
struct HnswElementData
|
||||||
{
|
{
|
||||||
HnswElementPtr next;
|
HnswElementPtr next;
|
||||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
||||||
@@ -147,7 +144,7 @@ typedef struct HnswElementData
|
|||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
DatumPtr value;
|
DatumPtr value;
|
||||||
LWLock lock;
|
LWLock lock;
|
||||||
} HnswElementData;
|
};
|
||||||
|
|
||||||
typedef HnswElementData * HnswElement;
|
typedef HnswElementData * HnswElement;
|
||||||
|
|
||||||
@@ -158,12 +155,12 @@ typedef struct HnswCandidate
|
|||||||
bool closer;
|
bool closer;
|
||||||
} HnswCandidate;
|
} HnswCandidate;
|
||||||
|
|
||||||
typedef struct HnswNeighborArray
|
struct HnswNeighborArray
|
||||||
{
|
{
|
||||||
int length;
|
int length;
|
||||||
bool closerSet;
|
bool closerSet;
|
||||||
HnswCandidate items[FLEXIBLE_ARRAY_MEMBER];
|
HnswCandidate items[FLEXIBLE_ARRAY_MEMBER];
|
||||||
} HnswNeighborArray;
|
};
|
||||||
|
|
||||||
typedef struct HnswPairingHeapNode
|
typedef struct HnswPairingHeapNode
|
||||||
{
|
{
|
||||||
@@ -188,6 +185,7 @@ typedef struct HnswGraph
|
|||||||
|
|
||||||
/* Entry state */
|
/* Entry state */
|
||||||
LWLock entryLock;
|
LWLock entryLock;
|
||||||
|
LWLock entryWaitLock;
|
||||||
HnswElementPtr entryPoint;
|
HnswElementPtr entryPoint;
|
||||||
|
|
||||||
/* Allocations state */
|
/* Allocations state */
|
||||||
@@ -200,20 +198,12 @@ 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;
|
||||||
@@ -225,16 +215,10 @@ 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
|
||||||
{
|
{
|
||||||
@@ -393,19 +377,20 @@ 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 HnswInsertElement(char *base, HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing);
|
void HnswFindElementNeighbors(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, Relation heapRel, bool building);
|
bool HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building);
|
||||||
void HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building);
|
void HnswUpdateNeighborsOnDisk(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 m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
void HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm, 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);
|
||||||
|
void HnswInitLockTranche(void);
|
||||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
||||||
|
|
||||||
/* Index access methods */
|
/* Index access methods */
|
||||||
|
|||||||
393
src/hnswbuild.c
393
src/hnswbuild.c
@@ -1,14 +1,53 @@
|
|||||||
|
/*
|
||||||
|
* 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 "lib/pairingheap.h"
|
#include "optimizer/optimizer.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"
|
||||||
@@ -16,15 +55,8 @@
|
|||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_progress.h"
|
#include "utils/backend_progress.h"
|
||||||
#elif PG_VERSION_NUM >= 120000
|
|
||||||
#include "pgstat.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
#include "access/tableam.h"
|
|
||||||
#include "commands/progress.h"
|
|
||||||
#else
|
#else
|
||||||
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
|
#include "pgstat.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
@@ -33,26 +65,11 @@
|
|||||||
#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)
|
||||||
@@ -124,14 +141,13 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, ForkNumber forkNum)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create element pages
|
* Create graph pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
CreateElementPages(HnswBuildState * buildstate)
|
CreateGraphPages(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;
|
||||||
@@ -143,12 +159,11 @@ CreateElementPages(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(etupAllocSize);
|
etup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
||||||
|
|
||||||
/* Prepare first page */
|
/* Prepare first page */
|
||||||
buf = HnswNewBuffer(index, forkNum);
|
buf = HnswNewBuffer(index, forkNum);
|
||||||
@@ -161,13 +176,13 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
Size etupSize;
|
Size etupSize;
|
||||||
Size ntupSize;
|
Size ntupSize;
|
||||||
Size combinedSize;
|
Size combinedSize;
|
||||||
void *valuePtr = HnswPtrAccess(base, element->value);
|
Pointer valuePtr = HnswPtrAccess(base, element->value);
|
||||||
|
|
||||||
/* Update iterator */
|
/* Update iterator */
|
||||||
iter = element->next;
|
iter = element->next;
|
||||||
|
|
||||||
/* Zero memory for each element */
|
/* Zero memory for each element */
|
||||||
MemSet(etup, 0, etupAllocSize);
|
MemSet(etup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(valuePtr));
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(valuePtr));
|
||||||
@@ -175,7 +190,7 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* Initial size check */
|
/* Initial size check */
|
||||||
if (etupSize > etupAllocSize)
|
if (etupSize > HNSW_TUPLE_ALLOC_SIZE)
|
||||||
elog(ERROR, "index tuple too large");
|
elog(ERROR, "index tuple too large");
|
||||||
|
|
||||||
HnswSetElementTuple(base, etup, element);
|
HnswSetElementTuple(base, etup, element);
|
||||||
@@ -227,10 +242,10 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create neighbor pages
|
* Write neighbor tuples
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
CreateNeighborPages(HnswBuildState * buildstate)
|
WriteNeighborTuples(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
@@ -240,29 +255,32 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
|||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
||||||
|
|
||||||
while (!HnswPtrIsNull(base, iter))
|
while (!HnswPtrIsNull(base, iter))
|
||||||
{
|
{
|
||||||
HnswElement e = HnswPtrAccess(base, iter);
|
HnswElement element = HnswPtrAccess(base, iter);
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, m);
|
||||||
|
|
||||||
/* Update iterator */
|
/* Update iterator */
|
||||||
iter = e->next;
|
iter = element->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, e->neighborPage, RBM_NORMAL, NULL);
|
buf = ReadBufferExtended(index, forkNum, element->neighborPage, RBM_NORMAL, NULL);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
page = BufferGetPage(buf);
|
page = BufferGetPage(buf);
|
||||||
|
|
||||||
HnswSetNeighborTuple(base, ntup, e, m);
|
HnswSetNeighborTuple(base, ntup, element, m);
|
||||||
|
|
||||||
if (!PageIndexTupleOverwrite(page, e->neighborOffno, (Item) ntup, ntupSize))
|
if (!PageIndexTupleOverwrite(page, element->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 */
|
||||||
@@ -284,8 +302,8 @@ FlushPages(HnswBuildState * buildstate)
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
CreateMetaPage(buildstate);
|
CreateMetaPage(buildstate);
|
||||||
CreateElementPages(buildstate);
|
CreateGraphPages(buildstate);
|
||||||
CreateNeighborPages(buildstate);
|
WriteNeighborTuples(buildstate);
|
||||||
|
|
||||||
buildstate->graph->flushed = true;
|
buildstate->graph->flushed = true;
|
||||||
MemoryContextReset(buildstate->graphCtx);
|
MemoryContextReset(buildstate->graphCtx);
|
||||||
@@ -295,7 +313,7 @@ FlushPages(HnswBuildState * buildstate)
|
|||||||
* Add a heap TID to an existing element
|
* Add a heap TID to an existing element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswAddDuplicateInMemory(HnswElement element, HnswElement dup)
|
AddDuplicateInMemory(HnswElement element, HnswElement dup)
|
||||||
{
|
{
|
||||||
LWLockAcquire(&dup->lock, LW_EXCLUSIVE);
|
LWLockAcquire(&dup->lock, LW_EXCLUSIVE);
|
||||||
|
|
||||||
@@ -316,15 +334,15 @@ HnswAddDuplicateInMemory(HnswElement element, HnswElement dup)
|
|||||||
* Find duplicate element
|
* Find duplicate element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswFindDuplicateInMemory(char *base, HnswElement element)
|
FindDuplicateInMemory(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 */
|
||||||
@@ -332,7 +350,7 @@ HnswFindDuplicateInMemory(char *base, HnswElement element)
|
|||||||
return false;
|
return false;
|
||||||
|
|
||||||
/* Check for space */
|
/* Check for space */
|
||||||
if (HnswAddDuplicateInMemory(element, neighborElement))
|
if (AddDuplicateInMemory(element, neighborElement))
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,10 +358,10 @@ HnswFindDuplicateInMemory(char *base, HnswElement element)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add to element and neighbor pages
|
* Add to element list
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteNewElementPagesInMemory(char *base, HnswGraph * graph, HnswElement element)
|
AddElementInMemory(char *base, HnswGraph * graph, HnswElement element)
|
||||||
{
|
{
|
||||||
SpinLockAcquire(&graph->lock);
|
SpinLockAcquire(&graph->lock);
|
||||||
element->next = graph->head;
|
element->next = graph->head;
|
||||||
@@ -355,7 +373,7 @@ WriteNewElementPagesInMemory(char *base, HnswGraph * graph, HnswElement element)
|
|||||||
* Update neighbors
|
* Update neighbors
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswUpdateNeighborPagesInMemory(char *base, FmgrInfo *procinfo, Oid collation, HnswElement e, int m)
|
UpdateNeighborsInMemory(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--)
|
||||||
{
|
{
|
||||||
@@ -379,45 +397,89 @@ HnswUpdateNeighborPagesInMemory(char *base, FmgrInfo *procinfo, Oid collation, H
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Write changes in memory
|
* Update graph in memory
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteElementInMemory(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, HnswBuildState * buildstate, HnswGraph * graph, bool updateEntryPoint)
|
UpdateGraphInMemory(FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
|
HnswGraph *graph = buildstate->graph;
|
||||||
char *base = buildstate->hnswarea;
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
/* Try to add to existing page */
|
/* Look for duplicate */
|
||||||
if (HnswFindDuplicateInMemory(base, element))
|
if (FindDuplicateInMemory(base, element))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Write element and neighbor tuples */
|
/* Add element */
|
||||||
WriteNewElementPagesInMemory(base, graph, element);
|
AddElementInMemory(base, graph, element);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborPagesInMemory(base, procinfo, collation, element, m);
|
UpdateNeighborsInMemory(base, procinfo, collation, element, m);
|
||||||
|
|
||||||
/* Update entry point if needed (already have lock) */
|
/* Update entry point if needed (already have lock) */
|
||||||
if (updateEntryPoint)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
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;
|
||||||
|
LWLock *entryWaitLock = &graph->entryWaitLock;
|
||||||
|
int efConstruction = buildstate->efConstruction;
|
||||||
|
int m = buildstate->m;
|
||||||
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
|
/* Wait if another process needs exclusive lock on entry lock */
|
||||||
|
LWLockAcquire(entryWaitLock, LW_EXCLUSIVE);
|
||||||
|
LWLockRelease(entryWaitLock);
|
||||||
|
|
||||||
|
/* 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);
|
||||||
|
|
||||||
|
/* Tell other processes to wait and get exclusive lock */
|
||||||
|
LWLockAcquire(entryWaitLock, LW_EXCLUSIVE);
|
||||||
|
LWLockAcquire(entryLock, LW_EXCLUSIVE);
|
||||||
|
LWLockRelease(entryWaitLock);
|
||||||
|
|
||||||
|
/* 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;
|
||||||
|
|
||||||
@@ -427,7 +489,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, collation, &value, buildstate->normvec))
|
if (!HnswNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->normvec))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -437,17 +499,24 @@ 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, buildstate->heap, true);
|
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, 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);
|
||||||
@@ -467,41 +536,29 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
|
|
||||||
LWLockRelease(flushLock);
|
LWLockRelease(flushLock);
|
||||||
|
|
||||||
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, buildstate->heap, true);
|
return HnswInsertTupleOnDisk(index, value, values, isnull, heaptid, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Create an element */
|
/* Ok, we can proceed to allocate the 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 datum */
|
/* Copy the datum */
|
||||||
memcpy(valuePtr, DatumGetPointer(value), valueSize);
|
memcpy(valuePtr, DatumGetPointer(value), valueSize);
|
||||||
HnswPtrStore(base, element->value, valuePtr);
|
HnswPtrStore(base, element->value, valuePtr);
|
||||||
|
|
||||||
/* Create element lock */
|
/* Create a lock for the element */
|
||||||
LWLockInitialize(&element->lock, hnsw_lock_tranche_id);
|
LWLockInitialize(&element->lock, hnsw_lock_tranche_id);
|
||||||
|
|
||||||
/* Get entry point */
|
/* Insert tuple */
|
||||||
LWLockAcquire(&graph->entryLock, LW_EXCLUSIVE);
|
InsertTupleInMemory(buildstate, element);
|
||||||
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);
|
||||||
@@ -536,7 +593,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
{
|
{
|
||||||
/* Update progress */
|
/* Update progress */
|
||||||
SpinLockAcquire(&graph->lock);
|
SpinLockAcquire(&graph->lock);
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++graph->indtuples);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE, ++graph->indtuples);
|
||||||
SpinLockRelease(&graph->lock);
|
SpinLockRelease(&graph->lock);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -551,6 +608,9 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
static void
|
static void
|
||||||
InitGraph(HnswGraph * graph, char *base, long memoryTotal)
|
InitGraph(HnswGraph * graph, char *base, long memoryTotal)
|
||||||
{
|
{
|
||||||
|
/* Initialize the lock tranche if needed */
|
||||||
|
HnswInitLockTranche();
|
||||||
|
|
||||||
HnswPtrStore(base, graph->head, (HnswElement) NULL);
|
HnswPtrStore(base, graph->head, (HnswElement) NULL);
|
||||||
HnswPtrStore(base, graph->entryPoint, (HnswElement) NULL);
|
HnswPtrStore(base, graph->entryPoint, (HnswElement) NULL);
|
||||||
graph->memoryUsed = 0;
|
graph->memoryUsed = 0;
|
||||||
@@ -559,6 +619,7 @@ InitGraph(HnswGraph * graph, char *base, long memoryTotal)
|
|||||||
graph->indtuples = 0;
|
graph->indtuples = 0;
|
||||||
SpinLockInit(&graph->lock);
|
SpinLockInit(&graph->lock);
|
||||||
LWLockInitialize(&graph->entryLock, hnsw_lock_tranche_id);
|
LWLockInitialize(&graph->entryLock, hnsw_lock_tranche_id);
|
||||||
|
LWLockInitialize(&graph->entryWaitLock, hnsw_lock_tranche_id);
|
||||||
LWLockInitialize(&graph->allocatorLock, hnsw_lock_tranche_id);
|
LWLockInitialize(&graph->allocatorLock, hnsw_lock_tranche_id);
|
||||||
LWLockInitialize(&graph->flushLock, hnsw_lock_tranche_id);
|
LWLockInitialize(&graph->flushLock, hnsw_lock_tranche_id);
|
||||||
}
|
}
|
||||||
@@ -710,36 +771,25 @@ 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(HnswSpool * hnswspool, HnswShared * hnswshared, char *hnswarea, bool progress)
|
HnswParallelScanAndInsert(Relation heapRel, Relation indexRel, 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(hnswspool->index);
|
indexInfo = BuildIndexInfo(indexRel);
|
||||||
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
||||||
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
InitBuildState(&buildstate, heapRel, indexRel, 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);
|
||||||
#if PG_VERSION_NUM >= 120000
|
scan = table_beginscan_parallel(heapRel,
|
||||||
scan = table_beginscan_parallel(hnswspool->heap,
|
|
||||||
ParallelTableScanFromHnswShared(hnswshared));
|
ParallelTableScanFromHnswShared(hnswshared));
|
||||||
reltuples = table_index_build_scan(hnswspool->heap, hnswspool->index, indexInfo,
|
reltuples = table_index_build_scan(heapRel, indexRel, 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);
|
||||||
@@ -766,10 +816,7 @@ 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;
|
||||||
@@ -799,32 +846,17 @@ 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);
|
||||||
|
|
||||||
/* Initialize worker's own spool */
|
hnswarea = shm_toc_lookup(toc, PARALLEL_KEY_HNSW_AREA, false);
|
||||||
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(hnswspool, hnswshared, hnswarea, false);
|
HnswParallelScanAndInsert(heapRel, indexRel, 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -849,19 +881,7 @@ 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -871,15 +891,9 @@ 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(leaderworker, hnswleader->hnswshared, hnswleader->hnswarea, true);
|
HnswParallelScanAndInsert(buildstate->heap, buildstate->index, hnswleader->hnswshared, hnswleader->hnswarea, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -889,14 +903,11 @@ 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 estdsaspace;
|
Size estother;
|
||||||
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,13 +920,7 @@ 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)
|
||||||
@@ -927,9 +932,15 @@ 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);
|
||||||
|
|
||||||
/* Start with a minimal DSA so InitializeParallelDSM does not fail */
|
/* Leave space for other objects in shared memory */
|
||||||
estdsaspace = dsa_minimum_size();
|
/* Docker has a default limit of 64 MB for shm_size */
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, estdsaspace);
|
/* which happens to be the default value of maintenance_work_mem */
|
||||||
|
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,42 +972,29 @@ 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
|
|
||||||
|
|
||||||
dsaspace = shm_toc_allocate(pcxt->toc, estdsaspace);
|
hnswarea = (char *) shm_toc_allocate(pcxt->toc, esthnswarea);
|
||||||
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);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Avoid base address for relptr for Postgres < 14.5
|
||||||
|
* https://github.com/postgres/postgres/commit/7201cd18627afc64850537806da7f22150d1a83b
|
||||||
|
*/
|
||||||
|
#if PG_VERSION_NUM < 140005
|
||||||
|
hnswshared->graphData.memoryUsed += MAXALIGN(1);
|
||||||
|
#endif
|
||||||
|
|
||||||
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, dsaspace);
|
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_AREA, hnswarea);
|
||||||
|
|
||||||
/* Store query string for workers */
|
/* Store query string for workers */
|
||||||
if (debug_query_string)
|
if (debug_query_string)
|
||||||
@@ -1068,7 +1066,7 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
{
|
{
|
||||||
int parallel_workers = 0;
|
int parallel_workers = 0;
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
/* Calculate parallel workers */
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
@@ -1084,15 +1082,8 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -1106,22 +1097,6 @@ 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,6 +2,7 @@
|
|||||||
|
|
||||||
#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"
|
||||||
@@ -116,7 +117,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
|
||||||
WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage, bool building)
|
AddElementOnDisk(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage, bool building)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -339,7 +340,7 @@ ConnectionExists(HnswElement e, HnswNeighborTuple ntup, int startIdx, int lm)
|
|||||||
* Update neighbors
|
* Update neighbors
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building)
|
HnswUpdateNeighborsOnDisk(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building)
|
||||||
{
|
{
|
||||||
char *base = NULL;
|
char *base = NULL;
|
||||||
|
|
||||||
@@ -354,9 +355,7 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
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);
|
||||||
@@ -395,9 +394,7 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Get tuple */
|
/* Get tuple */
|
||||||
itemid = PageGetItemId(page, offno);
|
ntup = (HnswNeighborTuple) PageGetItem(page, 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;
|
||||||
@@ -426,13 +423,9 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
{
|
{
|
||||||
ItemPointer indextid = &ntup->indextids[idx];
|
ItemPointer indextid = &ntup->indextids[idx];
|
||||||
|
|
||||||
/* Update neighbor */
|
/* Update neighbor on the buffer */
|
||||||
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);
|
||||||
@@ -451,14 +444,12 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
* Add a heap TID to an existing element
|
* Add a heap TID to an existing element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool building)
|
AddDuplicateOnDisk(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 */
|
||||||
@@ -476,9 +467,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool buil
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Find space */
|
/* Find space */
|
||||||
itemid = PageGetItemId(page, dup->offno);
|
etup = (HnswElementTuple) PageGetItem(page, 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]))
|
||||||
@@ -494,13 +483,9 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool buil
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add heap TID */
|
/* Add heap TID, modifying the tuple on the page directly */
|
||||||
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);
|
||||||
@@ -515,23 +500,23 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool buil
|
|||||||
* Find duplicate element
|
* Find duplicate element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswFindDuplicate(Relation index, HnswElement element, bool building)
|
FindDuplicateOnDisk(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 (HnswAddDuplicate(index, element, neighborElement, building))
|
if (AddDuplicateOnDisk(index, element, neighborElement, building))
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -539,26 +524,26 @@ HnswFindDuplicate(Relation index, HnswElement element, bool building)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Write changes to disk
|
* Update graph on disk
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteElement(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, bool building)
|
UpdateGraphOnDisk(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 (HnswFindDuplicate(index, element, building))
|
if (FindDuplicateOnDisk(index, element, building))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Write element and neighbor tuples */
|
/* Add element */
|
||||||
WriteNewElementPages(index, element, m, GetInsertPage(index), &newInsertPage, building);
|
AddElementOnDisk(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 */
|
||||||
HnswUpdateNeighborPages(index, procinfo, collation, element, m, false, building);
|
HnswUpdateNeighborsOnDisk(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)
|
||||||
@@ -569,7 +554,7 @@ WriteElement(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement elem
|
|||||||
* 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, Relation heapRel, bool building)
|
HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building)
|
||||||
{
|
{
|
||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
HnswElement element;
|
HnswElement element;
|
||||||
@@ -608,11 +593,11 @@ HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull,
|
|||||||
entryPoint = HnswGetEntryPoint(index);
|
entryPoint = HnswGetEntryPoint(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Insert element in graph */
|
/* Find neighbors for element */
|
||||||
HnswInsertElement(base, element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
HnswFindElementNeighbors(base, element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
/* Write to disk */
|
/* Update graph on disk */
|
||||||
WriteElement(index, procinfo, collation, element, m, efConstruction, entryPoint, building);
|
UpdateGraphOnDisk(index, procinfo, collation, element, m, efConstruction, entryPoint, building);
|
||||||
|
|
||||||
/* Release lock */
|
/* Release lock */
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||||
@@ -624,7 +609,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, Relation heapRel)
|
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid)
|
||||||
{
|
{
|
||||||
Datum value;
|
Datum value;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
@@ -641,7 +626,7 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
HnswInsertTupleOnDisk(index, value, values, isnull, heap_tid, heapRel, false);
|
HnswInsertTupleOnDisk(index, value, values, isnull, heap_tid, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -670,7 +655,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, heap);
|
HnswInsertTuple(index, values, isnull, heap_tid);
|
||||||
|
|
||||||
/* Delete memory context */
|
/* Delete memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|||||||
@@ -201,12 +201,8 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
scan->xs_heaptid = *heaptid;
|
scan->xs_heaptid = *heaptid;
|
||||||
#else
|
scan->xs_recheck = false;
|
||||||
scan->xs_ctup.t_self = *heaptid;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
199
src/hnswutils.c
199
src/hnswutils.c
@@ -2,9 +2,13 @@
|
|||||||
|
|
||||||
#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
|
||||||
@@ -56,13 +60,6 @@ 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)
|
||||||
@@ -84,15 +81,6 @@ 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)
|
||||||
@@ -215,6 +203,19 @@ 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
|
||||||
*/
|
*/
|
||||||
@@ -222,22 +223,12 @@ 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -325,7 +316,10 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -656,11 +650,25 @@ 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)
|
||||||
{
|
{
|
||||||
@@ -668,16 +676,16 @@ AddToVisited(char *base, visited_hash v, HnswCandidate * hc, Relation index, boo
|
|||||||
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
|
||||||
@@ -685,9 +693,9 @@ AddToVisited(char *base, visited_hash v, HnswCandidate * hc, Relation index, boo
|
|||||||
#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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -725,18 +733,12 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
HnswNeighborArray *neighborhoodData = NULL;
|
HnswNeighborArray *neighborhoodData = NULL;
|
||||||
Size neighborhoodSize;
|
Size neighborhoodSize;
|
||||||
|
|
||||||
/* Create hash table */
|
InitVisited(base, &v, index, ef, 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);
|
|
||||||
|
|
||||||
/* Create local memory for neighborhood if needed */
|
/* Create local memory for neighborhood if needed */
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
{
|
{
|
||||||
neighborhoodSize = offsetof(HnswNeighborArray, items) + sizeof(HnswCandidate) * HnswGetLayerM(m, lc);
|
neighborhoodSize = HNSW_NEIGHBOR_ARRAY_SIZE(HnswGetLayerM(m, lc));
|
||||||
neighborhoodData = palloc(neighborhoodSize);
|
neighborhoodData = palloc(neighborhoodSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -746,7 +748,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));
|
||||||
@@ -781,7 +783,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_EXCLUSIVE);
|
LWLockAcquire(&cElement->lock, LW_SHARED);
|
||||||
memcpy(neighborhoodData, neighborhood, neighborhoodSize);
|
memcpy(neighborhoodData, neighborhood, neighborhoodSize);
|
||||||
LWLockRelease(&cElement->lock);
|
LWLockRelease(&cElement->lock);
|
||||||
neighborhood = neighborhoodData;
|
neighborhood = neighborhoodData;
|
||||||
@@ -792,7 +794,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)
|
||||||
{
|
{
|
||||||
@@ -858,12 +860,15 @@ HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, F
|
|||||||
static int
|
static int
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
||||||
|
{
|
||||||
|
HnswCandidate *hca = lfirst(a);
|
||||||
|
HnswCandidate *hcb = lfirst(b);
|
||||||
#else
|
#else
|
||||||
CompareCandidateDistances(const void *a, const void *b)
|
CompareCandidateDistances(const void *a, const void *b)
|
||||||
#endif
|
|
||||||
{
|
{
|
||||||
HnswCandidate *hca = lfirst((ListCell *) a);
|
HnswCandidate *hca = lfirst(*(ListCell **) a);
|
||||||
HnswCandidate *hcb = lfirst((ListCell *) b);
|
HnswCandidate *hcb = lfirst(*(ListCell **) b);
|
||||||
|
#endif
|
||||||
|
|
||||||
if (hca->distance < hcb->distance)
|
if (hca->distance < hcb->distance)
|
||||||
return 1;
|
return 1;
|
||||||
@@ -886,12 +891,15 @@ CompareCandidateDistances(const void *a, const void *b)
|
|||||||
static int
|
static int
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
CompareCandidateDistancesOffset(const ListCell *a, const ListCell *b)
|
CompareCandidateDistancesOffset(const ListCell *a, const ListCell *b)
|
||||||
|
{
|
||||||
|
HnswCandidate *hca = lfirst(a);
|
||||||
|
HnswCandidate *hcb = lfirst(b);
|
||||||
#else
|
#else
|
||||||
CompareCandidateDistancesOffset(const void *a, const void *b)
|
CompareCandidateDistancesOffset(const void *a, const void *b)
|
||||||
#endif
|
|
||||||
{
|
{
|
||||||
HnswCandidate *hca = lfirst((ListCell *) a);
|
HnswCandidate *hca = lfirst(*(ListCell **) a);
|
||||||
HnswCandidate *hcb = lfirst((ListCell *) b);
|
HnswCandidate *hcb = lfirst(*(ListCell **) b);
|
||||||
|
#endif
|
||||||
|
|
||||||
if (hca->distance < hcb->distance)
|
if (hca->distance < hcb->distance)
|
||||||
return 1;
|
return 1;
|
||||||
@@ -912,40 +920,10 @@ 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, int lc, FmgrInfo *procinfo, Oid collation)
|
HnswGetDistance(char *base, HnswElement a, HnswElement b, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
Datum aValue;
|
Datum aValue = HnswGetValue(base, a);
|
||||||
Datum bValue;
|
Datum bValue = HnswGetValue(base, b);
|
||||||
|
|
||||||
/* 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));
|
||||||
}
|
}
|
||||||
@@ -954,7 +932,7 @@ HnswGetDistance(char *base, HnswElement a, HnswElement b, int lc, FmgrInfo *proc
|
|||||||
* 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, int lc, FmgrInfo *procinfo, Oid collation)
|
CheckElementCloser(char *base, HnswCandidate * e, List *r, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
HnswElement eElement = HnswPtrAccess(base, e->element);
|
HnswElement eElement = HnswPtrAccess(base, e->element);
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
@@ -963,8 +941,7 @@ CheckElementCloser(char *base, HnswCandidate * e, List *r, int lc, FmgrInfo *pro
|
|||||||
{
|
{
|
||||||
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;
|
||||||
@@ -977,20 +954,22 @@ CheckElementCloser(char *base, HnswCandidate * e, List *r, int lc, FmgrInfo *pro
|
|||||||
* Algorithm 4 from paper
|
* Algorithm 4 from paper
|
||||||
*/
|
*/
|
||||||
static List *
|
static List *
|
||||||
SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswElement e2, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
SelectNeighbors(char *base, List *c, int lm, 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);
|
||||||
pairingheap *wd;
|
HnswCandidate **wd;
|
||||||
|
int wdlen = 0;
|
||||||
|
int wdoff = 0;
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(base, e2, lc);
|
HnswNeighborArray *neighbors = HnswGetNeighbors(base, e2, lc);
|
||||||
bool mustCalculate = !neighbors->closerSet;
|
bool mustCalculate = !neighbors->closerSet;
|
||||||
List *added = NIL;
|
List *added = NIL;
|
||||||
bool removedAny = false;
|
bool removedAny = false;
|
||||||
|
|
||||||
if (list_length(w) <= m)
|
if (list_length(w) <= lm)
|
||||||
return w;
|
return w;
|
||||||
|
|
||||||
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
wd = palloc(sizeof(HnswCandidate *) * list_length(w));
|
||||||
|
|
||||||
/* Ensure order of candidates is deterministic for closer caching */
|
/* Ensure order of candidates is deterministic for closer caching */
|
||||||
if (sortCandidates)
|
if (sortCandidates)
|
||||||
@@ -1001,7 +980,7 @@ SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid coll
|
|||||||
list_sort(w, CompareCandidateDistancesOffset);
|
list_sort(w, CompareCandidateDistancesOffset);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (list_length(w) > 0 && list_length(r) < m)
|
while (list_length(w) > 0 && list_length(r) < lm)
|
||||||
{
|
{
|
||||||
/* Assumes w is already ordered desc */
|
/* Assumes w is already ordered desc */
|
||||||
HnswCandidate *e = llast(w);
|
HnswCandidate *e = llast(w);
|
||||||
@@ -1010,16 +989,20 @@ SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid coll
|
|||||||
|
|
||||||
/* 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, lc, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, 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, lc, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, added, procinfo, collation);
|
||||||
|
|
||||||
if (!e->closer)
|
if (!e->closer)
|
||||||
removedAny = true;
|
removedAny = true;
|
||||||
@@ -1032,7 +1015,7 @@ SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid coll
|
|||||||
*/
|
*/
|
||||||
if (removedAny)
|
if (removedAny)
|
||||||
{
|
{
|
||||||
e->closer = CheckElementCloser(base, e, r, lc, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, procinfo, collation);
|
||||||
if (e->closer)
|
if (e->closer)
|
||||||
added = lappend(added, e);
|
added = lappend(added, e);
|
||||||
}
|
}
|
||||||
@@ -1040,29 +1023,33 @@ SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid coll
|
|||||||
}
|
}
|
||||||
else if (e == newCandidate)
|
else if (e == newCandidate)
|
||||||
{
|
{
|
||||||
e->closer = CheckElementCloser(base, e, r, lc, procinfo, collation);
|
e->closer = CheckElementCloser(base, e, r, 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
|
||||||
pairingheap_add(wd, &(CreatePairingHeapNode(e)->ph_node));
|
wd[wdlen++] = e;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Cached value can only be used in future if sorted deterministically */
|
/* Cached value can only be used in future if sorted deterministically */
|
||||||
neighbors->closerSet = sortCandidates;
|
neighbors->closerSet = sortCandidates;
|
||||||
|
|
||||||
/* Keep pruned connections */
|
/* Keep pruned connections */
|
||||||
while (!pairingheap_is_empty(wd) && list_length(r) < m)
|
while (wdoff < wdlen && list_length(r) < lm)
|
||||||
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
r = lappend(r, wd[wdoff++]);
|
||||||
|
|
||||||
/* Return pruned for update connections */
|
/* Return pruned for update connections */
|
||||||
if (pruned != NULL)
|
if (pruned != NULL)
|
||||||
{
|
{
|
||||||
if (!pairingheap_is_empty(wd))
|
if (wdoff < wdlen)
|
||||||
*pruned = ((HnswPairingHeapNode *) pairingheap_first(wd))->inner;
|
*pruned = wd[wdoff];
|
||||||
else
|
else
|
||||||
*pruned = linitial(w);
|
*pruned = linitial(w);
|
||||||
}
|
}
|
||||||
@@ -1074,7 +1061,7 @@ SelectNeighbors(char *base, List *c, int m, int lc, FmgrInfo *procinfo, Oid coll
|
|||||||
* Add connections
|
* Add connections
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
AddConnections(char *base, HnswElement element, List *neighbors, int m, int lc)
|
AddConnections(char *base, HnswElement element, List *neighbors, int lc)
|
||||||
{
|
{
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
HnswNeighborArray *a = HnswGetNeighbors(base, element, lc);
|
HnswNeighborArray *a = HnswGetNeighbors(base, element, lc);
|
||||||
@@ -1087,7 +1074,7 @@ AddConnections(char *base, HnswElement element, List *neighbors, int m, int lc)
|
|||||||
* Update connections
|
* Update connections
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation)
|
HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm, 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);
|
||||||
@@ -1096,7 +1083,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int m,
|
|||||||
HnswPtrStore(base, hc2.element, element);
|
HnswPtrStore(base, hc2.element, element);
|
||||||
hc2.distance = hc->distance;
|
hc2.distance = hc->distance;
|
||||||
|
|
||||||
if (currentNeighbors->length < m)
|
if (currentNeighbors->length < lm)
|
||||||
{
|
{
|
||||||
currentNeighbors->items[currentNeighbors->length++] = hc2;
|
currentNeighbors->items[currentNeighbors->length++] = hc2;
|
||||||
|
|
||||||
@@ -1142,7 +1129,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int m,
|
|||||||
c = lappend(c, ¤tNeighbors->items[i]);
|
c = lappend(c, ¤tNeighbors->items[i]);
|
||||||
c = lappend(c, &hc2);
|
c = lappend(c, &hc2);
|
||||||
|
|
||||||
SelectNeighbors(base, c, m, lc, procinfo, collation, hce, &hc2, &pruned, true);
|
SelectNeighbors(base, c, lm, lc, procinfo, collation, hce, &hc2, &pruned, true);
|
||||||
|
|
||||||
/* Should not happen */
|
/* Should not happen */
|
||||||
if (pruned == NULL)
|
if (pruned == NULL)
|
||||||
@@ -1216,7 +1203,7 @@ PrecomputeHash(char *base, HnswElement element)
|
|||||||
* Algorithm 1 from paper
|
* Algorithm 1 from paper
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswInsertElement(char *base, HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing)
|
HnswFindElementNeighbors(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;
|
||||||
@@ -1276,7 +1263,7 @@ HnswInsertElement(char *base, HnswElement element, HnswElement entryPoint, Relat
|
|||||||
*/
|
*/
|
||||||
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, lm, lc);
|
AddConnections(base, element, neighbors, lc);
|
||||||
|
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#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"
|
||||||
@@ -59,8 +60,7 @@ 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))
|
||||||
{
|
{
|
||||||
ItemId itemid = PageGetItemId(page, offno);
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
|
||||||
int idx = 0;
|
int idx = 0;
|
||||||
bool itemUpdated = false;
|
bool itemUpdated = false;
|
||||||
|
|
||||||
@@ -91,15 +91,10 @@ 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,21 +194,25 @@ 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(NULL, element, m, NULL);
|
HnswInitNeighbors(base, element, m, NULL);
|
||||||
element->heaptidsLength = 0;
|
element->heaptidsLength = 0;
|
||||||
|
|
||||||
/* Add element to graph, skipping itself */
|
/* Find neighbors for element, skipping itself */
|
||||||
HnswInsertElement(NULL, element, entryPoint, index, procinfo, collation, m, efConstruction, true);
|
HnswFindElementNeighbors(base, 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(NULL, ntup, element, m);
|
HnswSetNeighborTuple(base, 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);
|
||||||
@@ -230,7 +229,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborPages(index, procinfo, collation, element, m, true, false);
|
HnswUpdateNeighborsOnDisk(index, procinfo, collation, element, m, true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -477,11 +476,8 @@ 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))
|
||||||
{
|
{
|
||||||
ItemId itemid = PageGetItemId(page, offno);
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, 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;
|
||||||
@@ -505,10 +501,6 @@ 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);
|
||||||
@@ -535,13 +527,10 @@ 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 */
|
/*
|
||||||
if (!PageIndexTupleOverwrite(page, offno, (Item) etup, etupSize))
|
* We modified the tuples in place, no need to call
|
||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
* PageIndexTupleOverwrite
|
||||||
|
*/
|
||||||
/* 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);
|
||||||
@@ -586,7 +575,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(BLCKSZ);
|
vacuumstate->ntup = palloc0(HNSW_TUPLE_ALLOC_SIZE);
|
||||||
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,30 +2,25 @@
|
|||||||
|
|
||||||
#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"
|
||||||
#elif PG_VERSION_NUM >= 120000
|
|
||||||
#include "pgstat.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
#include "access/tableam.h"
|
|
||||||
#include "commands/progress.h"
|
|
||||||
#else
|
#else
|
||||||
#define PROGRESS_CREATEIDX_SUBPHASE 0
|
#include "pgstat.h"
|
||||||
#define PROGRESS_CREATEIDX_TUPLES_TOTAL 0
|
|
||||||
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
@@ -34,26 +29,11 @@
|
|||||||
#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)
|
||||||
@@ -150,13 +130,8 @@ 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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,16 +257,12 @@ 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);
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
|
||||||
|
|
||||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||||
|
|
||||||
@@ -327,7 +298,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
|||||||
|
|
||||||
pfree(itup);
|
pfree(itup);
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
|
||||||
|
|
||||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||||
}
|
}
|
||||||
@@ -375,20 +346,12 @@ 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);
|
||||||
@@ -435,7 +398,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
int numSamples;
|
int numSamples;
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
||||||
|
|
||||||
/* Target 50 samples per list, with at least 10000 samples */
|
/* 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 */
|
||||||
@@ -510,7 +473,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 = palloc(listSize);
|
list = palloc0(listSize);
|
||||||
|
|
||||||
buf = IvfflatNewBuffer(index, forkNum);
|
buf = IvfflatNewBuffer(index, forkNum);
|
||||||
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
||||||
@@ -631,11 +594,7 @@ 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;
|
||||||
|
|
||||||
@@ -659,18 +618,11 @@ 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);
|
||||||
@@ -740,11 +692,7 @@ 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 */
|
||||||
@@ -764,11 +712,7 @@ 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -793,19 +737,7 @@ 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -856,11 +788,7 @@ 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;
|
||||||
|
|
||||||
@@ -918,13 +846,9 @@ 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);
|
||||||
@@ -995,7 +919,7 @@ AssignTuples(IvfflatBuildState * buildstate)
|
|||||||
Oid sortCollations[] = {InvalidOid};
|
Oid sortCollations[] = {InvalidOid};
|
||||||
bool nullsFirstFlags[] = {false};
|
bool nullsFirstFlags[] = {false};
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_ASSIGN);
|
pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_ASSIGN);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
/* Calculate parallel workers */
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->heap != NULL)
|
||||||
@@ -1023,15 +947,8 @@ 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,14 +3,16 @@
|
|||||||
#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 >= 120000
|
#if PG_VERSION_NUM < 150000
|
||||||
#include "commands/progress.h"
|
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int ivfflat_probes;
|
int ivfflat_probes;
|
||||||
@@ -33,12 +35,13 @@ 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)
|
||||||
{
|
{
|
||||||
@@ -56,7 +59,6 @@ ivfflatbuildphasename(int64 phasenum)
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Estimate the cost of an index scan
|
* Estimate the cost of an index scan
|
||||||
@@ -72,9 +74,6 @@ 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)
|
||||||
@@ -105,12 +104,7 @@ 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);
|
||||||
|
|
||||||
@@ -227,9 +221,7 @@ 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,9 +3,10 @@
|
|||||||
|
|
||||||
#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 "access/reloptions.h"
|
#include "lib/pairingheap.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"
|
||||||
@@ -16,10 +17,6 @@
|
|||||||
#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
|
||||||
@@ -135,16 +132,10 @@ 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,6 +2,7 @@
|
|||||||
|
|
||||||
#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,6 +5,7 @@
|
|||||||
#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"
|
||||||
@@ -105,12 +106,7 @@ 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
|
||||||
@@ -216,22 +212,14 @@ 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);
|
||||||
|
|
||||||
@@ -321,12 +309,8 @@ 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;
|
||||||
#else
|
scan->xs_recheck = false;
|
||||||
scan->xs_ctup.t_self = *heaptid;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#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,5 +1,6 @@
|
|||||||
#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"
|
||||||
|
|||||||
84
src/vector.c
84
src/vector.c
@@ -3,6 +3,7 @@
|
|||||||
#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"
|
||||||
@@ -11,6 +12,7 @@
|
|||||||
#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"
|
||||||
@@ -19,13 +21,6 @@
|
|||||||
#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'
|
||||||
@@ -177,14 +172,15 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_in);
|
|||||||
Datum
|
Datum
|
||||||
vector_in(PG_FUNCTION_ARGS)
|
vector_in(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
char *str = PG_GETARG_CSTRING(0);
|
char *lit = 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 *lit = pstrdup(str);
|
char *litcopy = pstrdup(lit);
|
||||||
|
char *str = litcopy;
|
||||||
|
|
||||||
while (vector_isspace(*str))
|
while (vector_isspace(*str))
|
||||||
str++;
|
str++;
|
||||||
@@ -268,7 +264,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(lit);
|
pfree(litcopy);
|
||||||
|
|
||||||
CheckExpectedDim(typmod, dim);
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
@@ -292,15 +288,6 @@ 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:
|
||||||
*
|
*
|
||||||
@@ -324,11 +311,7 @@ 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 = ']';
|
||||||
@@ -883,9 +866,10 @@ vector_mul(PG_FUNCTION_ARGS)
|
|||||||
int
|
int
|
||||||
vector_cmp_internal(Vector * a, Vector * b)
|
vector_cmp_internal(Vector * a, Vector * b)
|
||||||
{
|
{
|
||||||
CheckDims(a, b);
|
int dim = Min(a->dim, b->dim);
|
||||||
|
|
||||||
for (int i = 0; i < a->dim; i++)
|
/* Check values before dimensions to be consistent with Postgres arrays */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
{
|
{
|
||||||
if (a->x[i] < b->x[i])
|
if (a->x[i] < b->x[i])
|
||||||
return -1;
|
return -1;
|
||||||
@@ -893,6 +877,13 @@ vector_cmp_internal(Vector * a, Vector * b)
|
|||||||
if (a->x[i] > b->x[i])
|
if (a->x[i] > b->x[i])
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (a->dim < b->dim)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
if (a->dim > b->dim)
|
||||||
|
return 1;
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -906,6 +897,9 @@ vector_lt(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) < 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) < 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -919,6 +913,9 @@ vector_le(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) <= 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) <= 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -932,6 +929,9 @@ vector_eq(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) == 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -945,6 +945,9 @@ vector_ne(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) != 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -958,6 +961,9 @@ vector_ge(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) >= 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) >= 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -971,6 +977,9 @@ vector_gt(PG_FUNCTION_ARGS)
|
|||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
|
/* TODO Remove in 0.7.0 */
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) > 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1151,3 +1160,28 @@ vector_avg(PG_FUNCTION_ARGS)
|
|||||||
|
|
||||||
PG_RETURN_POINTER(result);
|
PG_RETURN_POINTER(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Concat vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_concat);
|
||||||
|
Datum
|
||||||
|
vector_concat(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
|
Vector *result;
|
||||||
|
int dim = a->dim + b->dim;
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
|
||||||
|
result = InitVector(dim);
|
||||||
|
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
result->x[i] = a->x[i];
|
||||||
|
|
||||||
|
for (int i = 0; i < b->dim; i++)
|
||||||
|
result->x[i + a->dim] = b->x[i];
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,6 +24,64 @@ SELECT '[1e37]'::vector * '[1e37]';
|
|||||||
ERROR: value out of range: overflow
|
ERROR: value out of range: overflow
|
||||||
SELECT '[1e-37]'::vector * '[1e-37]';
|
SELECT '[1e-37]'::vector * '[1e-37]';
|
||||||
ERROR: value out of range: underflow
|
ERROR: value out of range: underflow
|
||||||
|
SELECT '[1,2,3]'::vector || '[4,5]'::vector;
|
||||||
|
?column?
|
||||||
|
-------------
|
||||||
|
[1,2,3,4,5]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT array_fill(0, ARRAY[16000])::vector || '[1]'::vector;
|
||||||
|
ERROR: vector cannot have more than 16000 dimensions
|
||||||
|
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
t
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector = '[1,2]';
|
||||||
|
ERROR: different vector dimensions 3 and 2
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[1,2,3]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[0,0,0]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[0,0,0]', '[1,2,3]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
-1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[1,2]', '[1,2,3]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
-1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[1,2]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[1,2]', '[2,3,4]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
-1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT vector_cmp('[2,3]', '[1,2,3]');
|
||||||
|
vector_cmp
|
||||||
|
------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
SELECT vector_dims('[1,2,3]');
|
SELECT vector_dims('[1,2,3]');
|
||||||
vector_dims
|
vector_dims
|
||||||
-------------
|
-------------
|
||||||
|
|||||||
@@ -6,6 +6,20 @@ SELECT '[1,2,3]'::vector * '[4,5,6]';
|
|||||||
SELECT '[1e37]'::vector * '[1e37]';
|
SELECT '[1e37]'::vector * '[1e37]';
|
||||||
SELECT '[1e-37]'::vector * '[1e-37]';
|
SELECT '[1e-37]'::vector * '[1e-37]';
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector || '[4,5]'::vector;
|
||||||
|
SELECT array_fill(0, ARRAY[16000])::vector || '[1]'::vector;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
||||||
|
SELECT '[1,2,3]'::vector = '[1,2]';
|
||||||
|
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[1,2,3]');
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[0,0,0]');
|
||||||
|
SELECT vector_cmp('[0,0,0]', '[1,2,3]');
|
||||||
|
SELECT vector_cmp('[1,2]', '[1,2,3]');
|
||||||
|
SELECT vector_cmp('[1,2,3]', '[1,2]');
|
||||||
|
SELECT vector_cmp('[1,2]', '[2,3,4]');
|
||||||
|
SELECT vector_cmp('[2,3]', '[1,2,3]');
|
||||||
|
|
||||||
SELECT vector_dims('[1,2,3]');
|
SELECT vector_dims('[1,2,3]');
|
||||||
|
|
||||||
SELECT round(vector_norm('[1,1]')::numeric, 5);
|
SELECT round(vector_norm('[1,1]')::numeric, 5);
|
||||||
|
|||||||
114
test/t/018_hnsw_filtering.pl
Normal file
114
test/t/018_hnsw_filtering.pl
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
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();
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
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();
|
|
||||||
116
test/t/019_ivfflat_filtering.pl
Normal file
116
test/t/019_ivfflat_filtering.pl
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
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.5.1'
|
default_version = '0.6.1'
|
||||||
module_pathname = '$libdir/vector'
|
module_pathname = '$libdir/vector'
|
||||||
relocatable = true
|
relocatable = true
|
||||||
|
|||||||
Reference in New Issue
Block a user