mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
50 Commits
hnsw-query
...
subscript
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71ee682ed4 | ||
|
|
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 |
22
.github/workflows/build.yml
vendored
22
.github/workflows/build.yml
vendored
@@ -28,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
|
||||||
@@ -49,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() }}
|
||||||
@@ -60,7 +60,9 @@ jobs:
|
|||||||
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_10.tar.gz
|
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_10.tar.gz
|
||||||
tar xf REL_14_10.tar.gz
|
tar xf REL_14_10.tar.gz
|
||||||
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_10/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
|
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_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') }}
|
||||||
@@ -71,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 && ^
|
||||||
@@ -97,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
|
||||||
|
|||||||
12
CHANGELOG.md
12
CHANGELOG.md
@@ -1,6 +1,16 @@
|
|||||||
## 0.6.1 (unreleased)
|
## 0.7.0 (unreleased)
|
||||||
|
|
||||||
|
- Added subscript function 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 `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)
|
## 0.6.0 (2024-01-29)
|
||||||
|
|
||||||
|
|||||||
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.6.0",
|
"version": "0.6.1",
|
||||||
"maintainer": [
|
"maintainer": [
|
||||||
"Andrew Kane <andrew@ankane.org>"
|
"Andrew Kane <andrew@ankane.org>"
|
||||||
],
|
],
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"vector": {
|
"vector": {
|
||||||
"file": "sql/vector.sql",
|
"file": "sql/vector.sql",
|
||||||
"docfile": "README.md",
|
"docfile": "README.md",
|
||||||
"version": "0.6.0",
|
"version": "0.6.1",
|
||||||
"abstract": "Open-source vector similarity search for Postgres"
|
"abstract": "Open-source vector similarity search for Postgres"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
8
Makefile
8
Makefile
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.0
|
EXTVERSION = 0.6.1
|
||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
@@ -71,11 +71,9 @@ PG_MAJOR ?= 16
|
|||||||
.PHONY: docker
|
.PHONY: docker
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
docker build --pull --no-cache --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(PG_MAJOR) .
|
docker build --pull --no-cache --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(PG_MAJOR) -t pgvector/pgvector:$(EXTVERSION)-pg$(PG_MAJOR) .
|
||||||
docker build --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:$(EXTVERSION)-pg$(PG_MAJOR) .
|
|
||||||
|
|
||||||
.PHONY: docker-release
|
.PHONY: docker-release
|
||||||
|
|
||||||
docker-release:
|
docker-release:
|
||||||
docker buildx build --push --pull --no-cache --platform linux/amd64,linux/arm64 --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:pg$(PG_MAJOR) .
|
docker buildx build --push --pull --no-cache --platform linux/amd64,linux/arm64 --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 --build-arg PG_MAJOR=$(PG_MAJOR) -t pgvector/pgvector:$(EXTVERSION)-pg$(PG_MAJOR) .
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.0
|
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
|
||||||
|
|||||||
155
README.md
155
README.md
@@ -20,15 +20,15 @@ Compile and install the extension (supports Postgres 12+)
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone --branch v0.6.0 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
|
### Windows
|
||||||
|
|
||||||
@@ -44,12 +44,15 @@ Then use `nmake` to build:
|
|||||||
|
|
||||||
```cmd
|
```cmd
|
||||||
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
||||||
git clone --branch v0.6.0 https://github.com/pgvector/pgvector.git
|
cd %TEMP%
|
||||||
|
git clone --branch v0.6.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
nmake /F Makefile.win
|
nmake /F Makefile.win
|
||||||
nmake /F Makefile.win install
|
nmake /F Makefile.win install
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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).
|
You can also install it with [Docker](#docker) or [conda-forge](#conda-forge).
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
@@ -102,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
|
||||||
@@ -264,6 +273,8 @@ 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)
|
Starting with 0.6.0, you can also speed up index creation by increasing the number of parallel workers (2 by default)
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -402,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`.
|
||||||
|
|
||||||
@@ -422,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).
|
||||||
|
|
||||||
@@ -430,7 +467,7 @@ 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
|
||||||
|
|
||||||
Vacuuming can take a while for HNSW indexes. Speed it up by reindexing first.
|
Vacuuming can take a while for HNSW indexes. Speed it up by reindexing first.
|
||||||
|
|
||||||
@@ -439,6 +476,41 @@ REINDEX INDEX CONCURRENTLY index_name;
|
|||||||
VACUUM table_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.
|
||||||
@@ -544,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;
|
||||||
@@ -573,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.
|
||||||
@@ -581,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
|
||||||
@@ -616,7 +704,7 @@ 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
|
||||||
|
|
||||||
@@ -656,6 +744,26 @@ Note: Replace `16` with your Postgres server version
|
|||||||
|
|
||||||
If compilation fails and the output includes `warning: no such sysroot directory` on Mac, reinstall Xcode Command Line Tools.
|
If compilation fails and the output includes `warning: no such sysroot directory` on Mac, reinstall Xcode Command Line Tools.
|
||||||
|
|
||||||
|
### Portability
|
||||||
|
|
||||||
|
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=""
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation Notes - Windows
|
||||||
|
|
||||||
|
### Missing Header
|
||||||
|
|
||||||
|
If compilation fails with `Cannot open include file: 'postgres.h': No such file or directory`, make sure `PGROOT` is correct.
|
||||||
|
|
||||||
|
### Permissions
|
||||||
|
|
||||||
|
If installation fails with `Access is denied`, re-run the installation instructions as an administrator.
|
||||||
|
|
||||||
## Additional Installation Methods
|
## Additional Installation Methods
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
@@ -671,7 +779,7 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
|||||||
You can also build the image manually:
|
You can also build the image manually:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone --branch v0.6.0 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.6.1 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
docker build --build-arg PG_MAJOR=16 -t myuser/pgvector .
|
docker build --build-arg PG_MAJOR=16 -t myuser/pgvector .
|
||||||
```
|
```
|
||||||
@@ -716,6 +824,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:
|
||||||
@@ -825,6 +948,12 @@ make installcheck REGRESS=functions # regression test
|
|||||||
make prove_installcheck PROVE_TESTS=test/t/001_ivfflat_wal.pl # TAP test
|
make prove_installcheck PROVE_TESTS=test/t/001_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
|
||||||
@@ -837,12 +966,6 @@ To show memory usage:
|
|||||||
make clean && PG_CFLAGS="-DHNSW_MEMORY -DIVFFLAT_MEMORY" make && make install
|
make clean && PG_CFLAGS="-DHNSW_MEMORY -DIVFFLAT_MEMORY" make && make install
|
||||||
```
|
```
|
||||||
|
|
||||||
To enable assertions:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DUSE_ASSERT_CHECKING" make && make install
|
|
||||||
```
|
|
||||||
|
|
||||||
To get k-means metrics:
|
To get k-means metrics:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
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
|
||||||
|
);
|
||||||
7
sql/vector--0.6.2--0.7.0.sql
Normal file
7
sql/vector--0.6.2--0.7.0.sql
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
-- 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_subscript(internal) RETURNS internal
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
ALTER TYPE vector SET (SUBSCRIPT = vector_subscript);
|
||||||
@@ -20,12 +20,16 @@ CREATE FUNCTION vector_recv(internal, oid, integer) RETURNS vector
|
|||||||
CREATE FUNCTION vector_send(vector) RETURNS bytea
|
CREATE FUNCTION vector_send(vector) RETURNS bytea
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION vector_subscript(internal) RETURNS internal
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE TYPE vector (
|
CREATE TYPE vector (
|
||||||
INPUT = vector_in,
|
INPUT = vector_in,
|
||||||
OUTPUT = vector_out,
|
OUTPUT = vector_out,
|
||||||
TYPMOD_IN = vector_typmod_in,
|
TYPMOD_IN = vector_typmod_in,
|
||||||
RECEIVE = vector_recv,
|
RECEIVE = vector_recv,
|
||||||
SEND = vector_send,
|
SEND = vector_send,
|
||||||
|
SUBSCRIPT = vector_subscript,
|
||||||
STORAGE = external
|
STORAGE = external
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -180,8 +184,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 +198,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 +216,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 > (
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include "commands/progress.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"
|
||||||
|
|
||||||
@@ -28,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;
|
||||||
@@ -53,6 +54,7 @@ HnswInitLockTranche(void)
|
|||||||
void
|
void
|
||||||
HnswInit(void)
|
HnswInit(void)
|
||||||
{
|
{
|
||||||
|
if (!process_shared_preload_libraries_in_progress)
|
||||||
HnswInitLockTranche();
|
HnswInitLockTranche();
|
||||||
|
|
||||||
hnsw_relopt_kind = add_reloption_kind();
|
hnsw_relopt_kind = add_reloption_kind();
|
||||||
|
|||||||
23
src/hnsw.h
23
src/hnsw.h
@@ -80,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)
|
||||||
@@ -129,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];
|
||||||
@@ -144,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;
|
||||||
|
|
||||||
@@ -155,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
|
||||||
{
|
{
|
||||||
@@ -185,6 +185,7 @@ typedef struct HnswGraph
|
|||||||
|
|
||||||
/* Entry state */
|
/* Entry state */
|
||||||
LWLock entryLock;
|
LWLock entryLock;
|
||||||
|
LWLock entryWaitLock;
|
||||||
HnswElementPtr entryPoint;
|
HnswElementPtr entryPoint;
|
||||||
|
|
||||||
/* Allocations state */
|
/* Allocations state */
|
||||||
@@ -362,11 +363,6 @@ typedef struct HnswVacuumState
|
|||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
} HnswVacuumState;
|
} HnswVacuumState;
|
||||||
|
|
||||||
typedef struct HnswQuery
|
|
||||||
{
|
|
||||||
Datum value;
|
|
||||||
} HnswQuery;
|
|
||||||
|
|
||||||
/* Methods */
|
/* Methods */
|
||||||
int HnswGetM(Relation index);
|
int HnswGetM(Relation index);
|
||||||
int HnswGetEfConstruction(Relation index);
|
int HnswGetEfConstruction(Relation index);
|
||||||
@@ -375,14 +371,14 @@ bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * re
|
|||||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||||
void HnswInitPage(Buffer buf, Page page);
|
void HnswInitPage(Buffer buf, Page page);
|
||||||
void HnswInit(void);
|
void HnswInit(void);
|
||||||
List *HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement);
|
List *HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement);
|
||||||
HnswElement HnswGetEntryPoint(Relation index);
|
HnswElement HnswGetEntryPoint(Relation index);
|
||||||
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
||||||
void *HnswAlloc(HnswAllocator * allocator, Size size);
|
void *HnswAlloc(HnswAllocator * allocator, Size size);
|
||||||
HnswElement HnswInitElement(char *base, ItemPointer tid, int m, double ml, int maxLevel, HnswAllocator * alloc);
|
HnswElement HnswInitElement(char *base, ItemPointer tid, int m, double ml, int maxLevel, HnswAllocator * alloc);
|
||||||
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
||||||
void HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, 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, HnswQuery * 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);
|
||||||
@@ -390,10 +386,11 @@ void HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator *
|
|||||||
bool HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building);
|
bool HnswInsertTupleOnDisk(Relation index, Datum value, Datum *values, bool *isnull, ItemPointer heap_tid, bool building);
|
||||||
void HnswUpdateNeighborsOnDisk(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, HnswQuery * q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
||||||
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element);
|
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element);
|
||||||
void HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
void HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int 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 */
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ CreateGraphPages(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;
|
||||||
@@ -431,10 +431,15 @@ InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
|||||||
HnswGraph *graph = buildstate->graph;
|
HnswGraph *graph = buildstate->graph;
|
||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
LWLock *entryLock = &graph->entryLock;
|
LWLock *entryLock = &graph->entryLock;
|
||||||
|
LWLock *entryWaitLock = &graph->entryWaitLock;
|
||||||
int efConstruction = buildstate->efConstruction;
|
int efConstruction = buildstate->efConstruction;
|
||||||
int m = buildstate->m;
|
int m = buildstate->m;
|
||||||
char *base = buildstate->hnswarea;
|
char *base = buildstate->hnswarea;
|
||||||
|
|
||||||
|
/* Wait if another process needs exclusive lock on entry lock */
|
||||||
|
LWLockAcquire(entryWaitLock, LW_EXCLUSIVE);
|
||||||
|
LWLockRelease(entryWaitLock);
|
||||||
|
|
||||||
/* Get entry point */
|
/* Get entry point */
|
||||||
LWLockAcquire(entryLock, LW_SHARED);
|
LWLockAcquire(entryLock, LW_SHARED);
|
||||||
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
||||||
@@ -445,8 +450,10 @@ InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
|||||||
/* Release shared lock */
|
/* Release shared lock */
|
||||||
LWLockRelease(entryLock);
|
LWLockRelease(entryLock);
|
||||||
|
|
||||||
/* Get exclusive lock */
|
/* Tell other processes to wait and get exclusive lock */
|
||||||
|
LWLockAcquire(entryWaitLock, LW_EXCLUSIVE);
|
||||||
LWLockAcquire(entryLock, LW_EXCLUSIVE);
|
LWLockAcquire(entryLock, LW_EXCLUSIVE);
|
||||||
|
LWLockRelease(entryWaitLock);
|
||||||
|
|
||||||
/* Get latest entry point after lock is acquired */
|
/* Get latest entry point after lock is acquired */
|
||||||
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
entryPoint = HnswPtrAccess(base, graph->entryPoint);
|
||||||
@@ -601,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;
|
||||||
@@ -609,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);
|
||||||
}
|
}
|
||||||
@@ -974,6 +985,14 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
/* 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, hnswarea);
|
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_AREA, hnswarea);
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
* Algorithm 5 from paper
|
* Algorithm 5 from paper
|
||||||
*/
|
*/
|
||||||
static List *
|
static List *
|
||||||
GetScanItems(IndexScanDesc scan, Datum value)
|
GetScanItems(IndexScanDesc scan, Datum q)
|
||||||
{
|
{
|
||||||
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
||||||
Relation index = scan->indexRelation;
|
Relation index = scan->indexRelation;
|
||||||
@@ -22,9 +22,6 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
int m;
|
int m;
|
||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
char *base = NULL;
|
char *base = NULL;
|
||||||
HnswQuery q;
|
|
||||||
|
|
||||||
q.value = value;
|
|
||||||
|
|
||||||
/* Get m and entry point */
|
/* Get m and entry point */
|
||||||
HnswGetMetaPageInfo(index, &m, &entryPoint);
|
HnswGetMetaPageInfo(index, &m, &entryPoint);
|
||||||
@@ -32,15 +29,15 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
if (entryPoint == NULL)
|
if (entryPoint == NULL)
|
||||||
return NIL;
|
return NIL;
|
||||||
|
|
||||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, &q, index, procinfo, collation, false));
|
ep = list_make1(HnswEntryCandidate(base, entryPoint, q, index, procinfo, collation, false));
|
||||||
|
|
||||||
for (int lc = entryPoint->level; lc >= 1; lc--)
|
for (int lc = entryPoint->level; lc >= 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(base, &q, ep, 1, lc, index, procinfo, collation, m, false, NULL);
|
w = HnswSearchLayer(base, q, ep, 1, lc, index, procinfo, collation, m, false, NULL);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
return HnswSearchLayer(base, &q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
|
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
|||||||
* Load an element and optionally get its distance from q
|
* Load an element and optionally get its distance from q
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswLoadElement(HnswElement element, float *distance, HnswQuery * q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec)
|
HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -575,7 +575,7 @@ HnswLoadElement(HnswElement element, float *distance, HnswQuery * q, Relation in
|
|||||||
|
|
||||||
/* Calculate distance */
|
/* Calculate distance */
|
||||||
if (distance != NULL)
|
if (distance != NULL)
|
||||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q->value, PointerGetDatum(&etup->data)));
|
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->data)));
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -584,19 +584,19 @@ HnswLoadElement(HnswElement element, float *distance, HnswQuery * q, Relation in
|
|||||||
* Get the distance for a candidate
|
* Get the distance for a candidate
|
||||||
*/
|
*/
|
||||||
static float
|
static float
|
||||||
GetCandidateDistance(char *base, HnswCandidate * hc, HnswQuery * q, FmgrInfo *procinfo, Oid collation)
|
GetCandidateDistance(char *base, HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
HnswElement hce = HnswPtrAccess(base, hc->element);
|
HnswElement hce = HnswPtrAccess(base, hc->element);
|
||||||
Datum value = HnswGetValue(base, hce);
|
Datum value = HnswGetValue(base, hce);
|
||||||
|
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q->value, value));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create a candidate for the entry point
|
* Create a candidate for the entry point
|
||||||
*/
|
*/
|
||||||
HnswCandidate *
|
HnswCandidate *
|
||||||
HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec)
|
HnswEntryCandidate(char *base, HnswElement entryPoint, Datum q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec)
|
||||||
{
|
{
|
||||||
HnswCandidate *hc = palloc(sizeof(HnswCandidate));
|
HnswCandidate *hc = palloc(sizeof(HnswCandidate));
|
||||||
|
|
||||||
@@ -604,7 +604,7 @@ HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation i
|
|||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
hc->distance = GetCandidateDistance(base, hc, q, procinfo, collation);
|
hc->distance = GetCandidateDistance(base, hc, q, procinfo, collation);
|
||||||
else
|
else
|
||||||
HnswLoadElement(entryPoint, &hc->distance, q, index, procinfo, collation, loadVec);
|
HnswLoadElement(entryPoint, &hc->distance, &q, index, procinfo, collation, loadVec);
|
||||||
return hc;
|
return hc;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -722,7 +722,7 @@ CountElement(char *base, HnswElement skipElement, HnswCandidate * hc)
|
|||||||
* Algorithm 2 from paper
|
* Algorithm 2 from paper
|
||||||
*/
|
*/
|
||||||
List *
|
List *
|
||||||
HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement)
|
HnswSearchLayer(char *base, Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement)
|
||||||
{
|
{
|
||||||
List *w = NIL;
|
List *w = NIL;
|
||||||
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||||
@@ -806,7 +806,7 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
eDistance = GetCandidateDistance(base, e, q, procinfo, collation);
|
eDistance = GetCandidateDistance(base, e, q, procinfo, collation);
|
||||||
else
|
else
|
||||||
HnswLoadElement(eElement, &eDistance, q, index, procinfo, collation, inserting);
|
HnswLoadElement(eElement, &eDistance, &q, index, procinfo, collation, inserting);
|
||||||
|
|
||||||
Assert(!eElement->deleted);
|
Assert(!eElement->deleted);
|
||||||
|
|
||||||
@@ -860,12 +860,15 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
|||||||
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;
|
||||||
@@ -888,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;
|
||||||
@@ -952,7 +958,9 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
{
|
{
|
||||||
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;
|
||||||
@@ -961,7 +969,7 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
if (list_length(w) <= lm)
|
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)
|
||||||
@@ -1027,21 +1035,21 @@ SelectNeighbors(char *base, List *c, int lm, int lc, FmgrInfo *procinfo, Oid col
|
|||||||
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) < lm)
|
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);
|
||||||
}
|
}
|
||||||
@@ -1091,9 +1099,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm
|
|||||||
/* Load elements on insert */
|
/* Load elements on insert */
|
||||||
if (index != NULL)
|
if (index != NULL)
|
||||||
{
|
{
|
||||||
HnswQuery q;
|
Datum q = HnswGetValue(base, hce);
|
||||||
|
|
||||||
q.value = HnswGetValue(base, hce);
|
|
||||||
|
|
||||||
for (int i = 0; i < currentNeighbors->length; i++)
|
for (int i = 0; i < currentNeighbors->length; i++)
|
||||||
{
|
{
|
||||||
@@ -1103,7 +1109,7 @@ HnswUpdateConnection(char *base, HnswElement element, HnswCandidate * hc, int lm
|
|||||||
if (HnswPtrIsNull(base, hc3Element->value))
|
if (HnswPtrIsNull(base, hc3Element->value))
|
||||||
HnswLoadElement(hc3Element, &hc3->distance, &q, index, procinfo, collation, true);
|
HnswLoadElement(hc3Element, &hc3->distance, &q, index, procinfo, collation, true);
|
||||||
else
|
else
|
||||||
hc3->distance = GetCandidateDistance(base, hc3, &q, procinfo, collation);
|
hc3->distance = GetCandidateDistance(base, hc3, q, procinfo, collation);
|
||||||
|
|
||||||
/* Prune element if being deleted */
|
/* Prune element if being deleted */
|
||||||
if (hc3Element->heaptidsLength == 0)
|
if (hc3Element->heaptidsLength == 0)
|
||||||
@@ -1203,11 +1209,9 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
List *w;
|
List *w;
|
||||||
int level = element->level;
|
int level = element->level;
|
||||||
int entryLevel;
|
int entryLevel;
|
||||||
HnswQuery q;
|
Datum q = HnswGetValue(base, element);
|
||||||
HnswElement skipElement = existing ? element : NULL;
|
HnswElement skipElement = existing ? element : NULL;
|
||||||
|
|
||||||
q.value = HnswGetValue(base, element);
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
/* Precompute hash */
|
/* Precompute hash */
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
@@ -1219,13 +1223,13 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
/* Get entry point and level */
|
/* Get entry point and level */
|
||||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, &q, index, procinfo, collation, true));
|
ep = list_make1(HnswEntryCandidate(base, entryPoint, q, index, procinfo, collation, true));
|
||||||
entryLevel = entryPoint->level;
|
entryLevel = entryPoint->level;
|
||||||
|
|
||||||
/* 1st phase: greedy search to insert level */
|
/* 1st phase: greedy search to insert level */
|
||||||
for (int lc = entryLevel; lc >= level + 1; lc--)
|
for (int lc = entryLevel; lc >= level + 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(base, &q, ep, 1, lc, index, procinfo, collation, m, true, skipElement);
|
w = HnswSearchLayer(base, q, ep, 1, lc, index, procinfo, collation, m, true, skipElement);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1243,7 +1247,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
|||||||
List *neighbors;
|
List *neighbors;
|
||||||
List *lw;
|
List *lw;
|
||||||
|
|
||||||
w = HnswSearchLayer(base, &q, ep, efConstruction, lc, index, procinfo, collation, m, true, skipElement);
|
w = HnswSearchLayer(base, q, ep, efConstruction, lc, index, procinfo, collation, m, true, skipElement);
|
||||||
|
|
||||||
/* Elements being deleted or skipped can help with search */
|
/* Elements being deleted or skipped can help with search */
|
||||||
/* but should be removed before selecting neighbors */
|
/* but should be removed before selecting neighbors */
|
||||||
|
|||||||
181
src/vector.c
181
src/vector.c
@@ -4,11 +4,18 @@
|
|||||||
|
|
||||||
#include "catalog/pg_type.h"
|
#include "catalog/pg_type.h"
|
||||||
#include "common/shortest_dec.h"
|
#include "common/shortest_dec.h"
|
||||||
|
#include "executor/execExpr.h"
|
||||||
#include "fmgr.h"
|
#include "fmgr.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "lib/stringinfo.h"
|
#include "lib/stringinfo.h"
|
||||||
#include "libpq/pqformat.h"
|
#include "libpq/pqformat.h"
|
||||||
|
#include "nodes/makefuncs.h"
|
||||||
|
#include "nodes/nodeFuncs.h"
|
||||||
|
#include "nodes/subscripting.h"
|
||||||
|
#include "parser/parse_coerce.h"
|
||||||
|
#include "parser/parse_expr.h"
|
||||||
|
#include "parser/parse_node.h"
|
||||||
#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"
|
||||||
@@ -418,6 +425,180 @@ vector_send(PG_FUNCTION_ARGS)
|
|||||||
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Transform the subscript expressions
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
vector_subscript_transform(SubscriptingRef *sbsref, List *indirection, ParseState *pstate, bool isSlice, bool isAssignment)
|
||||||
|
{
|
||||||
|
A_Indices *ai;
|
||||||
|
Node *subexpr;
|
||||||
|
|
||||||
|
if (list_length(indirection) != 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
||||||
|
errmsg("vector allows only one subscript"),
|
||||||
|
parser_errposition(pstate,
|
||||||
|
exprLocation((Node *) indirection))));
|
||||||
|
|
||||||
|
ai = linitial_node(A_Indices, indirection);
|
||||||
|
|
||||||
|
if (isSlice)
|
||||||
|
{
|
||||||
|
if (ai->lidx)
|
||||||
|
{
|
||||||
|
subexpr = transformExpr(pstate, ai->lidx, pstate->p_expr_kind);
|
||||||
|
/* If it's not int4 already, try to coerce */
|
||||||
|
subexpr = coerce_to_target_type(pstate,
|
||||||
|
subexpr, exprType(subexpr),
|
||||||
|
INT4OID, -1,
|
||||||
|
COERCION_ASSIGNMENT,
|
||||||
|
COERCE_IMPLICIT_CAST,
|
||||||
|
-1);
|
||||||
|
if (subexpr == NULL)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATATYPE_MISMATCH),
|
||||||
|
errmsg("vector subscript must have type integer"),
|
||||||
|
parser_errposition(pstate, exprLocation(ai->lidx))));
|
||||||
|
}
|
||||||
|
else if (!ai->is_slice)
|
||||||
|
{
|
||||||
|
/* Make a constant 1 */
|
||||||
|
subexpr = (Node *) makeConst(INT4OID,
|
||||||
|
-1,
|
||||||
|
InvalidOid,
|
||||||
|
sizeof(int32),
|
||||||
|
Int32GetDatum(1),
|
||||||
|
false,
|
||||||
|
true); /* pass by value */
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Slice with omitted lower bound, put NULL into the list */
|
||||||
|
subexpr = NULL;
|
||||||
|
}
|
||||||
|
sbsref->reflowerindexpr = list_make1(subexpr);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
Assert(ai->lidx == NULL && !ai->is_slice);
|
||||||
|
|
||||||
|
if (ai->uidx)
|
||||||
|
{
|
||||||
|
subexpr = transformExpr(pstate, ai->uidx, pstate->p_expr_kind);
|
||||||
|
/* If it's not int4 already, try to coerce */
|
||||||
|
subexpr = coerce_to_target_type(pstate,
|
||||||
|
subexpr, exprType(subexpr),
|
||||||
|
INT4OID, -1,
|
||||||
|
COERCION_ASSIGNMENT,
|
||||||
|
COERCE_IMPLICIT_CAST,
|
||||||
|
-1);
|
||||||
|
if (subexpr == NULL)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATATYPE_MISMATCH),
|
||||||
|
errmsg("array subscript must have type integer"),
|
||||||
|
parser_errposition(pstate, exprLocation(ai->uidx))));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Slice with omitted upper bound, put NULL into the list */
|
||||||
|
Assert(isSlice && ai->is_slice);
|
||||||
|
subexpr = NULL;
|
||||||
|
}
|
||||||
|
sbsref->refupperindexpr = list_make1(subexpr);
|
||||||
|
|
||||||
|
if (isSlice)
|
||||||
|
sbsref->refrestype = sbsref->refcontainertype;
|
||||||
|
else
|
||||||
|
sbsref->refrestype = FLOAT4OID;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Fetch a vector element
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
vector_subscript_fetch(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
|
||||||
|
{
|
||||||
|
SubscriptingRefState *sbsrefstate = op->d.sbsref.state;
|
||||||
|
Vector *vec = DatumGetVector(*op->resvalue);
|
||||||
|
int index = DatumGetInt32(sbsrefstate->upperindex[0]);
|
||||||
|
|
||||||
|
if (index < 1 || index > vec->dim)
|
||||||
|
*op->resnull = true;
|
||||||
|
else
|
||||||
|
*op->resvalue = Float4GetDatum(vec->x[index - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Fetch a vector slice
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
vector_subscript_fetch_slice(ExprState *state, ExprEvalStep *op, ExprContext *econtext)
|
||||||
|
{
|
||||||
|
SubscriptingRefState *sbsrefstate = op->d.sbsref.state;
|
||||||
|
|
||||||
|
if (sbsrefstate->upperprovided[0] && sbsrefstate->upperindexnull[0])
|
||||||
|
*op->resnull = true;
|
||||||
|
else if (sbsrefstate->lowerprovided[0] && sbsrefstate->lowerindexnull[0])
|
||||||
|
*op->resnull = true;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Vector *vec = DatumGetVector(*op->resvalue);
|
||||||
|
int upperindex = sbsrefstate->upperprovided[0] ? DatumGetInt32(sbsrefstate->upperindex[0]) : vec->dim;
|
||||||
|
int lowerindex = sbsrefstate->lowerprovided[0] ? DatumGetInt32(sbsrefstate->lowerindex[0]) : 1;
|
||||||
|
int dim;
|
||||||
|
Vector *result;
|
||||||
|
|
||||||
|
if (upperindex > vec->dim)
|
||||||
|
upperindex = vec->dim;
|
||||||
|
|
||||||
|
if (lowerindex < 1)
|
||||||
|
lowerindex = 1;
|
||||||
|
|
||||||
|
dim = upperindex - lowerindex + 1;
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
|
||||||
|
result = InitVector(dim);
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
result->x[i] = vec->x[lowerindex + i - 1];
|
||||||
|
|
||||||
|
*op->resvalue = PointerGetDatum(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Set up execution state for a vector subscript operation
|
||||||
|
*/
|
||||||
|
static void
|
||||||
|
vector_exec_setup(const SubscriptingRef *sbsref, SubscriptingRefState *sbsrefstate, SubscriptExecSteps *methods)
|
||||||
|
{
|
||||||
|
methods->sbs_check_subscripts = NULL;
|
||||||
|
if (sbsrefstate->numlower != 0)
|
||||||
|
methods->sbs_fetch = vector_subscript_fetch_slice;
|
||||||
|
else
|
||||||
|
methods->sbs_fetch = vector_subscript_fetch;
|
||||||
|
methods->sbs_assign = NULL;
|
||||||
|
methods->sbs_fetch_old = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Subscript handler
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_subscript);
|
||||||
|
Datum
|
||||||
|
vector_subscript(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
static const SubscriptRoutines sbsroutines = {
|
||||||
|
.transform = vector_subscript_transform,
|
||||||
|
.exec_setup = vector_exec_setup,
|
||||||
|
.fetch_strict = true, /* fetch returns NULL for NULL inputs */
|
||||||
|
.fetch_leakproof = true, /* fetch returns NULL for bad subscript */
|
||||||
|
.store_leakproof = false /* ... but assignment throws error */
|
||||||
|
};
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(&sbsroutines);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Convert vector to vector
|
* Convert vector to vector
|
||||||
* This is needed to check the type modifier
|
* This is needed to check the type modifier
|
||||||
|
|||||||
@@ -24,6 +24,112 @@ 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)[0];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[1];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[2];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[3];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[4];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[1:1];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[1]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[1:2];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[1,2]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:4];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[-2:2];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[1,2]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:1];
|
||||||
|
ERROR: vector must have at least 1 dimension
|
||||||
|
SELECT ('[1,2,3]'::vector)[:];
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[:2];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[1,2]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
[2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[:4];
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[-2:];
|
||||||
|
vector
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[NULL];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[NULL:2];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:NULL];
|
||||||
|
vector
|
||||||
|
--------
|
||||||
|
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ('[1,2,3]'::vector)[1][1];
|
||||||
|
ERROR: vector allows only one subscript
|
||||||
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
||||||
?column?
|
?column?
|
||||||
----------
|
----------
|
||||||
|
|||||||
@@ -6,6 +6,26 @@ 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)[0];
|
||||||
|
SELECT ('[1,2,3]'::vector)[1];
|
||||||
|
SELECT ('[1,2,3]'::vector)[2];
|
||||||
|
SELECT ('[1,2,3]'::vector)[3];
|
||||||
|
SELECT ('[1,2,3]'::vector)[4];
|
||||||
|
SELECT ('[1,2,3]'::vector)[1:1];
|
||||||
|
SELECT ('[1,2,3]'::vector)[1:2];
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:4];
|
||||||
|
SELECT ('[1,2,3]'::vector)[-2:2];
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:1];
|
||||||
|
SELECT ('[1,2,3]'::vector)[:];
|
||||||
|
SELECT ('[1,2,3]'::vector)[:2];
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:];
|
||||||
|
SELECT ('[1,2,3]'::vector)[:4];
|
||||||
|
SELECT ('[1,2,3]'::vector)[-2:];
|
||||||
|
SELECT ('[1,2,3]'::vector)[NULL];
|
||||||
|
SELECT ('[1,2,3]'::vector)[NULL:2];
|
||||||
|
SELECT ('[1,2,3]'::vector)[2:NULL];
|
||||||
|
SELECT ('[1,2,3]'::vector)[1][1];
|
||||||
|
|
||||||
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
SELECT '[1,2,3]'::vector = '[1,2,3]';
|
||||||
SELECT '[1,2,3]'::vector = '[1,2]';
|
SELECT '[1,2,3]'::vector = '[1,2]';
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
comment = 'vector data type and ivfflat and hnsw access methods'
|
comment = 'vector data type and ivfflat and hnsw access methods'
|
||||||
default_version = '0.6.0'
|
default_version = '0.6.1'
|
||||||
module_pathname = '$libdir/vector'
|
module_pathname = '$libdir/vector'
|
||||||
relocatable = true
|
relocatable = true
|
||||||
|
|||||||
Reference in New Issue
Block a user