mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 03:57:34 +08:00
Compare commits
89 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f52127bee | ||
|
|
4778039ffa | ||
|
|
e3c9d70acc | ||
|
|
5971e28f8c | ||
|
|
2da27e2f01 | ||
|
|
7dd934913d | ||
|
|
9b46987e73 | ||
|
|
868e1f99a4 | ||
|
|
354271178f | ||
|
|
fe9b218903 | ||
|
|
3cdd1c16fb | ||
|
|
4f7a5c92da | ||
|
|
9399575e02 | ||
|
|
e7539fe548 | ||
|
|
61860ee6d9 | ||
|
|
eb99730d87 | ||
|
|
e5da5cc532 | ||
|
|
f59b1184fc | ||
|
|
cab103a2e7 | ||
|
|
0094b70a36 | ||
|
|
46ed56d80f | ||
|
|
d390cc9fa6 | ||
|
|
02ae98791c | ||
|
|
b64c7d6228 | ||
|
|
76f117c81c | ||
|
|
5414b2bc9e | ||
|
|
6ba583b587 | ||
|
|
da88217fd8 | ||
|
|
d5da22f24b | ||
|
|
062e220936 | ||
|
|
3d2b867a58 | ||
|
|
5aeabc3648 | ||
|
|
687ec6d8d7 | ||
|
|
51dc18d5b7 | ||
|
|
cb108ebfd2 | ||
|
|
12bc4eb036 | ||
|
|
fd0e472316 | ||
|
|
9b11b05cd7 | ||
|
|
ab079c1911 | ||
|
|
f4eaa3de1f | ||
|
|
e47675d6ae | ||
|
|
20167ddc33 | ||
|
|
e14fa82626 | ||
|
|
2ae4de83fe | ||
|
|
5d2c4883dc | ||
|
|
fc1de9806a | ||
|
|
e375dd33f3 | ||
|
|
b643ef637a | ||
|
|
0ee5bfda65 | ||
|
|
c5bec2a534 | ||
|
|
40f65dc8ba | ||
|
|
9ec174137f | ||
|
|
423e478a85 | ||
|
|
8b301197fe | ||
|
|
c02feaa9ad | ||
|
|
729374a9b8 | ||
|
|
a8245d6cda | ||
|
|
5220a6ec7e | ||
|
|
ddd873f369 | ||
|
|
8735c4782a | ||
|
|
17ec3f3852 | ||
|
|
8df12a62e7 | ||
|
|
647c9002be | ||
|
|
3e6345f02a | ||
|
|
2b3484ddcd | ||
|
|
1a6debf281 | ||
|
|
bff4d7ea68 | ||
|
|
d5b979e4fa | ||
|
|
d52426b3fa | ||
|
|
b125b2debb | ||
|
|
3d7186a17c | ||
|
|
58ba2139ce | ||
|
|
fd93c9db86 | ||
|
|
8dde26920c | ||
|
|
9153a545a7 | ||
|
|
9c20f04a11 | ||
|
|
7c12d100ce | ||
|
|
d97d9a6561 | ||
|
|
f15ea301c5 | ||
|
|
cfa23f2c7a | ||
|
|
b5b7035edc | ||
|
|
478d62cdbd | ||
|
|
c7df9ef3a1 | ||
|
|
ea1b094d8e | ||
|
|
63d2965e8e | ||
|
|
e5e7a6ec15 | ||
|
|
ede572d80b | ||
|
|
154e4334fb | ||
|
|
77d54333f6 |
@@ -1,6 +1,6 @@
|
||||
root = true
|
||||
|
||||
[*.{c,h}]
|
||||
[*.{c,h,pl}]
|
||||
indent_style = tab
|
||||
indent_size = tab
|
||||
tab_width = 4
|
||||
|
||||
11
.github/workflows/build.yml
vendored
11
.github/workflows/build.yml
vendored
@@ -2,16 +2,15 @@ name: build
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
build:
|
||||
if: "!contains(github.event.head_commit.message, '[skip ci]')"
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
postgres: [13, 12, 11, 10, 9.6]
|
||||
postgres: [14, 13, 12, 11, 10, 9.6]
|
||||
include:
|
||||
- os: macos-latest
|
||||
postgres: 13
|
||||
postgres: 14
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: ankane/setup-postgres@v1
|
||||
@@ -34,6 +33,6 @@ jobs:
|
||||
- if: ${{ startsWith(matrix.os, 'macos') }}
|
||||
run: |
|
||||
brew install cpanm && cpanm IPC::Run
|
||||
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_13_2.tar.gz
|
||||
tar xf REL_13_2.tar.gz
|
||||
make prove_installcheck PROVE=prove PERL5LIB=postgres-REL_13_2/src/test/perl
|
||||
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_1.tar.gz
|
||||
tar xf REL_14_1.tar.gz
|
||||
make prove_installcheck PROVE=prove PERL5LIB=postgres-REL_14_1/src/test/perl
|
||||
|
||||
36
CHANGELOG.md
36
CHANGELOG.md
@@ -1,3 +1,39 @@
|
||||
## 0.2.5 (2022-02-11)
|
||||
|
||||
- Reduced memory usage during index creation
|
||||
- Fixed index creation exceeding `maintenance_work_mem`
|
||||
- Fixed error with index creation when lists > 1600
|
||||
|
||||
## 0.2.4 (2022-02-06)
|
||||
|
||||
- Added support for parallel vacuum
|
||||
- Fixed issue with index not reusing space
|
||||
|
||||
## 0.2.3 (2022-01-30)
|
||||
|
||||
- Added indexing progress for Postgres 12+
|
||||
- Improved interrupt handling during index creation
|
||||
|
||||
## 0.2.2 (2022-01-15)
|
||||
|
||||
- Fixed compilation error on Mac ARM
|
||||
|
||||
## 0.2.1 (2022-01-02)
|
||||
|
||||
- Fixed `operator is not unique` error
|
||||
|
||||
## 0.2.0 (2021-10-03)
|
||||
|
||||
- Added support for Postgres 14
|
||||
|
||||
## 0.1.8 (2021-09-07)
|
||||
|
||||
- Added cast for `vector` to `real[]`
|
||||
|
||||
## 0.1.7 (2021-06-13)
|
||||
|
||||
- Added cast for `numeric[]` to `vector`
|
||||
|
||||
## 0.1.6 (2021-06-09)
|
||||
|
||||
- Fixed segmentation fault with `COUNT`
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
FROM postgres
|
||||
FROM postgres:14
|
||||
|
||||
COPY . /tmp/pgvector
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-13 && \
|
||||
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-14 && \
|
||||
cd /tmp/pgvector && \
|
||||
make clean && \
|
||||
make OPTFLAGS="" && \
|
||||
@@ -11,6 +11,6 @@ RUN apt-get update && \
|
||||
mkdir /usr/share/doc/pgvector && \
|
||||
cp LICENSE README.md /usr/share/doc/pgvector && \
|
||||
rm -r /tmp/pgvector && \
|
||||
apt-get remove -y build-essential postgresql-server-dev-13 && \
|
||||
apt-get remove -y build-essential postgresql-server-dev-14 && \
|
||||
apt-get autoremove -y && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
12
META.json
12
META.json
@@ -2,7 +2,7 @@
|
||||
"name": "vector",
|
||||
"abstract": "Open-source vector similarity search for Postgres",
|
||||
"description": "Supports L2 distance, inner product, and cosine distance",
|
||||
"version": "0.1.6",
|
||||
"version": "0.2.5",
|
||||
"maintainer": [
|
||||
"Andrew Kane <andrew@ankane.org>"
|
||||
],
|
||||
@@ -20,18 +20,18 @@
|
||||
"vector": {
|
||||
"file": "sql/vector.sql",
|
||||
"docfile": "README.md",
|
||||
"version": "0.1.6",
|
||||
"version": "0.2.5",
|
||||
"abstract": "Open-source vector similarity search for Postgres"
|
||||
}
|
||||
},
|
||||
"resources": {
|
||||
"homepage": "https://github.com/ankane/pgvector",
|
||||
"homepage": "https://github.com/pgvector/pgvector",
|
||||
"bugtracker": {
|
||||
"web": "https://github.com/ankane/pgvector/issues"
|
||||
"web": "https://github.com/pgvector/pgvector/issues"
|
||||
},
|
||||
"repository": {
|
||||
"url": "https://github.com/ankane/pgvector.git",
|
||||
"web": "https://github.com/ankane/pgvector",
|
||||
"url": "https://github.com/pgvector/pgvector.git",
|
||||
"web": "https://github.com/pgvector/pgvector",
|
||||
"type": "git"
|
||||
}
|
||||
},
|
||||
|
||||
16
Makefile
16
Makefile
@@ -1,5 +1,5 @@
|
||||
EXTENSION = vector
|
||||
EXTVERSION = 0.1.6
|
||||
EXTVERSION = 0.2.5
|
||||
|
||||
MODULE_big = vector
|
||||
DATA = $(wildcard sql/*--*.sql)
|
||||
@@ -11,10 +11,17 @@ REGRESS_OPTS = --inputdir=test
|
||||
|
||||
OPTFLAGS = -march=native
|
||||
|
||||
# Mac ARM doesn't support -march=native
|
||||
ifeq ($(shell uname -s), Darwin)
|
||||
ifeq ($(shell uname -p), arm)
|
||||
OPTFLAGS =
|
||||
endif
|
||||
endif
|
||||
|
||||
# For auto-vectorization:
|
||||
# - GCC (needs -ftree-vectorize OR -O3) - https://gcc.gnu.org/projects/tree-ssa/vectorization.html
|
||||
# - Clang (could use pragma instead) - https://llvm.org/docs/Vectorizers.html
|
||||
PG_CFLAGS = $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math
|
||||
PG_CFLAGS += $(OPTFLAGS) -ftree-vectorize -fassociative-math -fno-signed-zeros -fno-trapping-math
|
||||
|
||||
# Debug GCC auto-vectorization
|
||||
# PG_CFLAGS += -fopt-info-vec
|
||||
@@ -42,3 +49,8 @@ prove_installcheck:
|
||||
dist:
|
||||
mkdir -p dist
|
||||
git archive --format zip --prefix=$(EXTENSION)-$(EXTVERSION)/ --output dist/$(EXTENSION)-$(EXTVERSION).zip master
|
||||
|
||||
.PHONY: docker
|
||||
|
||||
docker:
|
||||
docker build --pull --no-cache -t ankane/pgvector:latest .
|
||||
|
||||
102
README.md
102
README.md
@@ -4,20 +4,20 @@ Open-source vector similarity search for Postgres
|
||||
|
||||
```sql
|
||||
CREATE TABLE table (column vector(3));
|
||||
CREATE INDEX ON table USING ivfflat (column);
|
||||
CREATE INDEX ON table USING ivfflat (column vector_l2_ops);
|
||||
SELECT * FROM table ORDER BY column <-> '[1,2,3]' LIMIT 5;
|
||||
```
|
||||
|
||||
Supports L2 distance, inner product, and cosine distance
|
||||
|
||||
[](https://github.com/ankane/pgvector/actions)
|
||||
[](https://github.com/pgvector/pgvector/actions)
|
||||
|
||||
## Installation
|
||||
|
||||
Compile and install the extension (supports Postgres 9.6+)
|
||||
|
||||
```sh
|
||||
git clone --branch v0.1.6 https://github.com/ankane/pgvector.git
|
||||
git clone --branch v0.2.5 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
make install # may need sudo
|
||||
@@ -62,7 +62,7 @@ Speed up queries with an approximate index. Add an index for each distance funct
|
||||
L2 distance
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON table USING ivfflat (column);
|
||||
CREATE INDEX ON table USING ivfflat (column vector_l2_ops);
|
||||
```
|
||||
|
||||
Inner product
|
||||
@@ -77,16 +77,18 @@ Cosine distance
|
||||
CREATE INDEX ON table USING ivfflat (column vector_cosine_ops);
|
||||
```
|
||||
|
||||
Indexes should be created after the table has data for optimal clustering. Also, unlike typical indexes which only affect performance, you may see different results for queries after adding an approximate index.
|
||||
Indexes should be created after the table has some data for optimal clustering. Also, unlike typical indexes which only affect performance, you may see different results for queries after adding an approximate index.
|
||||
|
||||
### Index Options
|
||||
|
||||
Specify the number of inverted lists (100 by default)
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON table USING ivfflat (column) WITH (lists = 100);
|
||||
CREATE INDEX ON table USING ivfflat (column opclass) WITH (lists = 100);
|
||||
```
|
||||
|
||||
A [good place to start](https://github.com/facebookresearch/faiss/issues/112) is `4 * sqrt(rows)`
|
||||
|
||||
### Query Options
|
||||
|
||||
Specify the number of probes (1 by default)
|
||||
@@ -106,6 +108,48 @@ SELECT ...
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
### Indexing Progress
|
||||
|
||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||
|
||||
```sql
|
||||
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
|
||||
```
|
||||
|
||||
The phases are:
|
||||
|
||||
1. `initializing`
|
||||
2. `sampling table`
|
||||
3. `performing k-means`
|
||||
4. `sorting tuples`
|
||||
5. `loading tuples`
|
||||
|
||||
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
|
||||
|
||||
### Partial Indexes
|
||||
|
||||
Consider [partial indexes](https://www.postgresql.org/docs/current/indexes-partial.html) for queries with a `WHERE` clause
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON table USING ivfflat (column opclass) WHERE (other_column = 123);
|
||||
```
|
||||
|
||||
To index many different values of `other_column`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `other_column`.
|
||||
|
||||
## Performance
|
||||
|
||||
To speed up queries without an index, increase `max_parallel_workers_per_gather`.
|
||||
|
||||
```sql
|
||||
SET max_parallel_workers_per_gather = 4;
|
||||
```
|
||||
|
||||
To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON table USING ivfflat (column opclass) WITH (lists = 1000);
|
||||
```
|
||||
|
||||
## Reference
|
||||
|
||||
### Vector Type
|
||||
@@ -136,14 +180,36 @@ vector_norm(vector) | Euclidean norm
|
||||
|
||||
Libraries that use pgvector:
|
||||
|
||||
- [pgvector-python](https://github.com/pgvector/pgvector-python) (Python)
|
||||
- [Neighbor](https://github.com/ankane/neighbor) (Ruby)
|
||||
- [pgvector.rs](https://github.com/ankane/pgvector.rs) (Rust)
|
||||
- [pgvector-ruby](https://github.com/pgvector/pgvector-ruby) (Ruby)
|
||||
- [pgvector-node](https://github.com/pgvector/pgvector-node) (Node.js)
|
||||
- [pgvector-go](https://github.com/pgvector/pgvector-go) (Go)
|
||||
- [pgvector-rust](https://github.com/pgvector/pgvector-rust) (Rust)
|
||||
- [pgvector-cpp](https://github.com/pgvector/pgvector-cpp) (C++)
|
||||
|
||||
## Frequently Asked Questions
|
||||
|
||||
#### How many vectors can be stored in a single table?
|
||||
|
||||
A non-partitioned table has a limit of 32 TB by default in Postgres. A partitioned table can have thousands of partitions of that size.
|
||||
|
||||
#### Is replication supported?
|
||||
|
||||
Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
|
||||
|
||||
#### What if my data has more than 1024 dimensions?
|
||||
|
||||
Two things you can try are:
|
||||
|
||||
1. use dimensionality reduction
|
||||
2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/vector.h`
|
||||
|
||||
## Additional Installation Methods
|
||||
|
||||
### Docker
|
||||
|
||||
Get the [Docker image](https://hub.docker.com/repository/docker/ankane/pgvector) with:
|
||||
Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
|
||||
|
||||
```sh
|
||||
docker pull ankane/pgvector
|
||||
@@ -154,7 +220,7 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres).
|
||||
You can also build the image manually
|
||||
|
||||
```sh
|
||||
git clone --branch v0.1.6 https://github.com/ankane/pgvector.git
|
||||
git clone --branch v0.2.5 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
docker build -t pgvector .
|
||||
```
|
||||
@@ -164,7 +230,7 @@ docker build -t pgvector .
|
||||
On Mac with Homebrew Postgres, you can use:
|
||||
|
||||
```sh
|
||||
brew install ankane/brew/pgvector
|
||||
brew install pgvector/brew/pgvector
|
||||
```
|
||||
|
||||
### PGXN
|
||||
@@ -181,7 +247,7 @@ Some Postgres providers only support specific extensions. To request a new exten
|
||||
|
||||
- Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/)
|
||||
- Google Cloud SQL - follow the instructions on [this page](https://cloud.google.com/sql/docs/postgres/extensions#requesting-support-for-a-new-extension)
|
||||
- DigitalOcean Managed Databases - follow the instructions on [this page](https://docs.digitalocean.com/products/databases/postgresql/resources/supported-extensions/#supported-extensions)
|
||||
- DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql)
|
||||
- Azure Database for PostgreSQL - follow the instructions on [this page](https://docs.microsoft.com/en-us/azure/postgresql/concepts-extensions#next-steps)
|
||||
|
||||
## Upgrading
|
||||
@@ -204,21 +270,21 @@ Thanks to:
|
||||
|
||||
## History
|
||||
|
||||
View the [changelog](https://github.com/ankane/pgvector/blob/master/CHANGELOG.md)
|
||||
View the [changelog](https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
Everyone is encouraged to help improve this project. Here are a few ways you can help:
|
||||
|
||||
- [Report bugs](https://github.com/ankane/pgvector/issues)
|
||||
- Fix bugs and [submit pull requests](https://github.com/ankane/pgvector/pulls)
|
||||
- [Report bugs](https://github.com/pgvector/pgvector/issues)
|
||||
- Fix bugs and [submit pull requests](https://github.com/pgvector/pgvector/pulls)
|
||||
- Write, clarify, or fix documentation
|
||||
- Suggest or add new features
|
||||
|
||||
To get started with development:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ankane/pgvector.git
|
||||
git clone https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
make install
|
||||
@@ -238,6 +304,12 @@ make installcheck REGRESS=functions # regression test
|
||||
make prove_installcheck PROVE_TESTS=test/t/001_wal.pl # TAP test
|
||||
```
|
||||
|
||||
To enable benchmarking:
|
||||
|
||||
```sh
|
||||
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
|
||||
```
|
||||
|
||||
Resources for contributors
|
||||
|
||||
- [Extension Building Infrastructure](https://www.postgresql.org/docs/current/extend-pgxs.html)
|
||||
|
||||
8
sql/vector--0.1.6--0.1.7.sql
Normal file
8
sql/vector--0.1.6--0.1.7.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.1.7'" to load this file. \quit
|
||||
|
||||
CREATE FUNCTION array_to_vector(numeric[], integer, boolean) RETURNS vector
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE CAST (numeric[] AS vector)
|
||||
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS IMPLICIT;
|
||||
8
sql/vector--0.1.7--0.1.8.sql
Normal file
8
sql/vector--0.1.7--0.1.8.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.1.8'" to load this file. \quit
|
||||
|
||||
CREATE FUNCTION vector_to_float4(vector, integer, boolean) RETURNS real[]
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE CAST (vector AS real[])
|
||||
WITH FUNCTION vector_to_float4(vector, integer, boolean) AS IMPLICIT;
|
||||
2
sql/vector--0.1.8--0.2.0.sql
Normal file
2
sql/vector--0.1.8--0.2.0.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.0'" to load this file. \quit
|
||||
19
sql/vector--0.2.0--0.2.1.sql
Normal file
19
sql/vector--0.2.0--0.2.1.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.1'" to load this file. \quit
|
||||
|
||||
DROP CAST (integer[] AS vector);
|
||||
DROP CAST (real[] AS vector);
|
||||
DROP CAST (double precision[] AS vector);
|
||||
DROP CAST (numeric[] AS vector);
|
||||
|
||||
CREATE CAST (integer[] AS vector)
|
||||
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (real[] AS vector)
|
||||
WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (double precision[] AS vector)
|
||||
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (numeric[] AS vector)
|
||||
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;
|
||||
2
sql/vector--0.2.1--0.2.2.sql
Normal file
2
sql/vector--0.2.1--0.2.2.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.2'" to load this file. \quit
|
||||
2
sql/vector--0.2.2--0.2.3.sql
Normal file
2
sql/vector--0.2.2--0.2.3.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.3'" to load this file. \quit
|
||||
2
sql/vector--0.2.3--0.2.4.sql
Normal file
2
sql/vector--0.2.3--0.2.4.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.4'" to load this file. \quit
|
||||
2
sql/vector--0.2.4--0.2.5.sql
Normal file
2
sql/vector--0.2.4--0.2.5.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.2.5'" to load this file. \quit
|
||||
@@ -97,19 +97,31 @@ CREATE FUNCTION array_to_vector(real[], integer, boolean) RETURNS vector
|
||||
CREATE FUNCTION array_to_vector(double precision[], integer, boolean) RETURNS vector
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION array_to_vector(numeric[], integer, boolean) RETURNS vector
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE FUNCTION vector_to_float4(vector, integer, boolean) RETURNS real[]
|
||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
-- casts
|
||||
|
||||
CREATE CAST (vector AS vector)
|
||||
WITH FUNCTION vector(vector, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (vector AS real[])
|
||||
WITH FUNCTION vector_to_float4(vector, integer, boolean) AS IMPLICIT;
|
||||
|
||||
CREATE CAST (integer[] AS vector)
|
||||
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS IMPLICIT;
|
||||
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (real[] AS vector)
|
||||
WITH FUNCTION array_to_vector(real[], integer, boolean) AS IMPLICIT;
|
||||
WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (double precision[] AS vector)
|
||||
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS IMPLICIT;
|
||||
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
CREATE CAST (numeric[] AS vector)
|
||||
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;
|
||||
|
||||
-- operators
|
||||
|
||||
|
||||
@@ -7,8 +7,19 @@
|
||||
#include "miscadmin.h"
|
||||
#include "storage/bufmgr.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
#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
|
||||
#define PROGRESS_CREATEIDX_SUBPHASE 0
|
||||
#define PROGRESS_CREATEIDX_TUPLES_TOTAL 0
|
||||
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 110000
|
||||
@@ -25,6 +36,17 @@
|
||||
#define CALLBACK_ITEM_POINTER HeapTuple hup
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Update build phase progress
|
||||
*/
|
||||
static inline void
|
||||
UpdateProgress(int index, int64 val)
|
||||
{
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
pgstat_progress_update_param(index, val);
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Callback for sampling
|
||||
*/
|
||||
@@ -82,6 +104,8 @@ SampleRows(IvfflatBuildState * buildstate)
|
||||
int targsamples = buildstate->samples->maxlen;
|
||||
BlockNumber totalblocks = RelationGetNumberOfBlocks(buildstate->heap);
|
||||
|
||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_SAMPLE);
|
||||
|
||||
buildstate->rowstoskip = -1;
|
||||
|
||||
BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, random());
|
||||
@@ -165,6 +189,8 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
||||
* need not save it.
|
||||
*/
|
||||
tuplesort_puttupleslot(buildstate->sortstate, slot);
|
||||
|
||||
buildstate->indtuples++;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -212,6 +238,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
||||
BlockNumber insertPage = InvalidBlockNumber;
|
||||
Size itemsz;
|
||||
int i;
|
||||
int64 inserted = 0;
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsMinimalTuple);
|
||||
@@ -220,10 +247,18 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
||||
#endif
|
||||
TupleDesc tupdesc = RelationGetDescr(index);
|
||||
|
||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
|
||||
|
||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_TOTAL, buildstate->indtuples);
|
||||
|
||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||
|
||||
for (i = 0; i < buildstate->centers->length; i++)
|
||||
{
|
||||
/* Can take a while, so ensure we can interrupt */
|
||||
/* Needs to be called when no buffer locks are held */
|
||||
CHECK_FOR_INTERRUPTS();
|
||||
|
||||
buf = IvfflatNewBuffer(index, forkNum);
|
||||
IvfflatInitPage(index, &buf, &page, &state);
|
||||
|
||||
@@ -243,7 +278,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
||||
|
||||
pfree(itup);
|
||||
|
||||
buildstate->indtuples += 1;
|
||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++inserted);
|
||||
|
||||
GetNextTuple(buildstate->sortstate, tupdesc, slot, &itup, &list);
|
||||
}
|
||||
@@ -253,7 +288,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
|
||||
IvfflatCommitBuffer(buf, state);
|
||||
|
||||
/* Set the start and insert pages */
|
||||
IvfflatUpdateList(index, state, buildstate->listInfo[i], insertPage, startPage, forkNum);
|
||||
IvfflatUpdateList(index, state, buildstate->listInfo[i], insertPage, InvalidBlockNumber, startPage, forkNum);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +318,12 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
||||
buildstate->kmeansnormprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||
buildstate->collation = index->rd_indcollation[0];
|
||||
|
||||
/* Require more than one dimension for spherical k-means */
|
||||
/* Lists check for backwards compatibility */
|
||||
/* TODO Remove lists check in 0.3.0 */
|
||||
if (buildstate->kmeansnormprocinfo != NULL && buildstate->dimensions == 1 && buildstate->lists > 1)
|
||||
elog(ERROR, "dimensions must be greater than one for this opclass");
|
||||
|
||||
/* Create tuple description for sorting */
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
buildstate->tupdesc = CreateTemplateTupleDesc(4);
|
||||
@@ -336,13 +377,19 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
||||
if (numSamples < 10000)
|
||||
numSamples = 10000;
|
||||
|
||||
/* Sample samples */
|
||||
/* Skip samples for unlogged table */
|
||||
if (buildstate->heap == NULL)
|
||||
numSamples = 1;
|
||||
|
||||
/* Sample rows */
|
||||
/* TODO Ensure within maintenance_work_mem */
|
||||
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions);
|
||||
if (buildstate->heap != NULL)
|
||||
SampleRows(buildstate);
|
||||
|
||||
/* Calculate centers */
|
||||
IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers);
|
||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
|
||||
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers));
|
||||
|
||||
/* Free samples before we allocate more memory */
|
||||
pfree(buildstate->samples);
|
||||
@@ -432,6 +479,8 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
|
||||
Oid sortCollations[] = {InvalidOid};
|
||||
bool nullsFirstFlags[] = {false};
|
||||
|
||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_SORT);
|
||||
|
||||
#if PG_VERSION_NUM >= 110000
|
||||
buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, NULL, false);
|
||||
#else
|
||||
@@ -473,7 +522,7 @@ BuildIndex(Relation heap, Relation index, IndexInfo *indexInfo,
|
||||
/* Create pages */
|
||||
CreateMetaPage(index, buildstate->dimensions, buildstate->lists, forkNum);
|
||||
CreateListPages(index, buildstate->centers, buildstate->dimensions, buildstate->lists, forkNum, &buildstate->listInfo);
|
||||
CreateEntryPages(buildstate, forkNum);
|
||||
IvfflatBench("CreateEntryPages", CreateEntryPages(buildstate, forkNum));
|
||||
|
||||
FreeBuildState(buildstate);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
#include "utils/guc.h"
|
||||
#include "utils/selfuncs.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
#include "commands/progress.h"
|
||||
#endif
|
||||
|
||||
int ivfflat_probes;
|
||||
static relopt_kind ivfflat_relopt_kind;
|
||||
|
||||
@@ -30,6 +34,31 @@ _PG_init(void)
|
||||
1, 1, IVFFLAT_MAX_LISTS, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the name of index build phase
|
||||
*/
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
static char *
|
||||
ivfflatbuildphasename(int64 phasenum)
|
||||
{
|
||||
switch (phasenum)
|
||||
{
|
||||
case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
|
||||
return "initializing";
|
||||
case PROGRESS_IVFFLAT_PHASE_SAMPLE:
|
||||
return "sampling table";
|
||||
case PROGRESS_IVFFLAT_PHASE_KMEANS:
|
||||
return "performing k-means";
|
||||
case PROGRESS_IVFFLAT_PHASE_SORT:
|
||||
return "sorting tuples";
|
||||
case PROGRESS_IVFFLAT_PHASE_LOAD:
|
||||
return "loading tuples";
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Estimate the cost of an index scan
|
||||
*/
|
||||
@@ -130,6 +159,11 @@ ivfflatvalidate(Oid opclassoid)
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Define index handler
|
||||
*
|
||||
* See https://www.postgresql.org/docs/current/index-api.html
|
||||
*/
|
||||
PG_FUNCTION_INFO_V1(ivfflathandler);
|
||||
Datum
|
||||
ivfflathandler(PG_FUNCTION_ARGS)
|
||||
@@ -160,23 +194,27 @@ ivfflathandler(PG_FUNCTION_ARGS)
|
||||
#endif
|
||||
#if PG_VERSION_NUM >= 130000
|
||||
amroutine->amusemaintenanceworkmem = false; /* not used during VACUUM */
|
||||
amroutine->amparallelvacuumoptions = VACUUM_OPTION_NO_PARALLEL; /* TODO support parallel */
|
||||
amroutine->amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL;
|
||||
#endif
|
||||
amroutine->amkeytype = InvalidOid;
|
||||
|
||||
/* Interface functions */
|
||||
amroutine->ambuild = ivfflatbuild;
|
||||
amroutine->ambuildempty = ivfflatbuildempty;
|
||||
amroutine->aminsert = ivfflatinsert;
|
||||
amroutine->ambulkdelete = ivfflatbulkdelete;
|
||||
amroutine->amvacuumcleanup = ivfflatvacuumcleanup;
|
||||
amroutine->amcanreturn = NULL;
|
||||
amroutine->amcanreturn = NULL; /* tuple not included in heapsort */
|
||||
amroutine->amcostestimate = ivfflatcostestimate;
|
||||
amroutine->amoptions = ivfflatoptions;
|
||||
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
amroutine->ambuildphasename = NULL;
|
||||
amroutine->ambuildphasename = ivfflatbuildphasename;
|
||||
#endif
|
||||
amroutine->amvalidate = ivfflatvalidate;
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
amroutine->amadjustmembers = NULL;
|
||||
#endif
|
||||
amroutine->ambeginscan = ivfflatbeginscan;
|
||||
amroutine->amrescan = ivfflatrescan;
|
||||
amroutine->amgettuple = ivfflatgettuple;
|
||||
@@ -184,6 +222,8 @@ ivfflathandler(PG_FUNCTION_ARGS)
|
||||
amroutine->amendscan = ivfflatendscan;
|
||||
amroutine->ammarkpos = NULL;
|
||||
amroutine->amrestrpos = NULL;
|
||||
|
||||
/* Interface functions to support parallel index scans */
|
||||
#if PG_VERSION_NUM >= 100000
|
||||
amroutine->amestimateparallelscan = NULL;
|
||||
amroutine->aminitparallelscan = NULL;
|
||||
|
||||
@@ -10,6 +10,14 @@
|
||||
#include "utils/tuplesort.h"
|
||||
#include "vector.h"
|
||||
|
||||
#ifdef IVFFLAT_BENCH
|
||||
#include "portability/instr_time.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM < 90600
|
||||
#error "Requires PostgreSQL 9.6+"
|
||||
#endif
|
||||
|
||||
/* Support functions */
|
||||
#define IVFFLAT_DISTANCE_PROC 1
|
||||
#define IVFFLAT_NORM_PROC 2
|
||||
@@ -27,11 +35,33 @@
|
||||
#define IVFFLAT_DEFAULT_LISTS 100
|
||||
#define IVFFLAT_MAX_LISTS 32768
|
||||
|
||||
/* Build phases */
|
||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||
#define PROGRESS_IVFFLAT_PHASE_SAMPLE 2
|
||||
#define PROGRESS_IVFFLAT_PHASE_KMEANS 3
|
||||
#define PROGRESS_IVFFLAT_PHASE_SORT 4
|
||||
#define PROGRESS_IVFFLAT_PHASE_LOAD 5
|
||||
|
||||
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
|
||||
|
||||
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
|
||||
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
|
||||
|
||||
#ifdef IVFFLAT_BENCH
|
||||
#define IvfflatBench(name, code) \
|
||||
do { \
|
||||
instr_time start; \
|
||||
instr_time duration; \
|
||||
INSTR_TIME_SET_CURRENT(start); \
|
||||
(code); \
|
||||
INSTR_TIME_SET_CURRENT(duration); \
|
||||
INSTR_TIME_SUBTRACT(duration, start); \
|
||||
elog(INFO, "%s: %.3f ms", name, INSTR_TIME_GET_MILLISEC(duration)); \
|
||||
} while (0)
|
||||
#else
|
||||
#define IvfflatBench(name, code) (code)
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM < 100000
|
||||
#define ItemPointerGetBlockNumberNoCheck ItemPointerGetBlockNumber
|
||||
#define ItemPointerGetOffsetNumberNoCheck ItemPointerGetOffsetNumber
|
||||
@@ -170,7 +200,7 @@ void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
||||
FmgrInfo *IvfflatOptionalProcInfo(Relation rel, uint16 procnum);
|
||||
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||
int IvfflatGetLists(Relation index);
|
||||
void IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo, BlockNumber insertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||
void IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||
void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
|
||||
void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
|
||||
Buffer IvfflatNewBuffer(Relation index, ForkNumber forkNum);
|
||||
@@ -180,6 +210,9 @@ void IvfflatInitPage(Relation index, Buffer *buf, Page *page, GenericXLogState
|
||||
IndexBuildResult *ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo);
|
||||
void ivfflatbuildempty(Relation index);
|
||||
bool ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heap, IndexUniqueCheck checkUnique
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
,bool indexUnchanged
|
||||
#endif
|
||||
#if PG_VERSION_NUM >= 100000
|
||||
,IndexInfo *indexInfo
|
||||
#endif
|
||||
|
||||
@@ -77,11 +77,12 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
|
||||
Size itemsz;
|
||||
BlockNumber insertPage = InvalidBlockNumber;
|
||||
ListInfo listInfo;
|
||||
bool newPage = false;
|
||||
BlockNumber originalInsertPage;
|
||||
|
||||
/* Find the insert page - sets the page and list info */
|
||||
FindInsertPage(rel, values, &insertPage, &listInfo);
|
||||
Assert(BlockNumberIsValid(insertPage));
|
||||
originalInsertPage = insertPage;
|
||||
|
||||
itemsz = MAXALIGN(IndexTupleSize(itup));
|
||||
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
|
||||
@@ -107,7 +108,6 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
|
||||
IvfflatAppendPage(rel, &buf, &page, &state, MAIN_FORKNUM);
|
||||
|
||||
insertPage = BufferGetBlockNumber(buf);
|
||||
newPage = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,8 +118,8 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
|
||||
IvfflatCommitBuffer(buf, state);
|
||||
|
||||
/* Update the insert page */
|
||||
if (newPage)
|
||||
IvfflatUpdateList(rel, state, listInfo, insertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
if (insertPage != originalInsertPage)
|
||||
IvfflatUpdateList(rel, state, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -128,6 +128,9 @@ InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
|
||||
bool
|
||||
ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid,
|
||||
Relation heap, IndexUniqueCheck checkUnique
|
||||
#if PG_VERSION_NUM >= 140000
|
||||
,bool indexUnchanged
|
||||
#endif
|
||||
#if PG_VERSION_NUM >= 100000
|
||||
,IndexInfo *indexInfo
|
||||
#endif
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* https://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf
|
||||
*/
|
||||
static void
|
||||
InitCenters(Relation index, VectorArray samples, VectorArray centers, double *lowerBound)
|
||||
InitCenters(Relation index, VectorArray samples, VectorArray centers, float *lowerBound)
|
||||
{
|
||||
FmgrInfo *procinfo;
|
||||
Oid collation;
|
||||
@@ -21,7 +21,7 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, double *lo
|
||||
double sum;
|
||||
double choice;
|
||||
Vector *vec;
|
||||
double *weight = palloc(samples->length * sizeof(double));
|
||||
float *weight = palloc(samples->length * sizeof(float));
|
||||
int numCenters = centers->maxlen;
|
||||
int numSamples = samples->length;
|
||||
|
||||
@@ -121,15 +121,18 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
||||
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||
|
||||
/* Copy existing vectors while avoiding duplicates */
|
||||
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
||||
for (i = 0; i < samples->length; i++)
|
||||
if (samples->length > 0)
|
||||
{
|
||||
vec = VectorArrayGet(samples, i);
|
||||
|
||||
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
||||
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
||||
for (i = 0; i < samples->length; i++)
|
||||
{
|
||||
VectorArraySet(centers, centers->length, vec);
|
||||
centers->length++;
|
||||
vec = VectorArrayGet(samples, i);
|
||||
|
||||
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
||||
{
|
||||
VectorArraySet(centers, centers->length, vec);
|
||||
centers->length++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,11 +180,11 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
VectorArray newCenters;
|
||||
int *centerCounts;
|
||||
int *closestCenters;
|
||||
double *lowerBound;
|
||||
double *upperBound;
|
||||
double *s;
|
||||
double *halfcdist;
|
||||
double *newcdist;
|
||||
float *lowerBound;
|
||||
float *upperBound;
|
||||
float *s;
|
||||
float *halfcdist;
|
||||
float *newcdist;
|
||||
int changes;
|
||||
double minDistance;
|
||||
int closestCenter;
|
||||
@@ -191,19 +194,43 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
||||
double dxcx;
|
||||
double dxc;
|
||||
|
||||
/* Calculate allocation sizes */
|
||||
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
|
||||
Size centersSize = VECTOR_ARRAY_SIZE(centers->maxlen, centers->dim);
|
||||
Size newCentersSize = VECTOR_ARRAY_SIZE(numCenters, dimensions);
|
||||
Size centerCountsSize = sizeof(int) * numCenters;
|
||||
Size closestCentersSize = sizeof(int) * numSamples;
|
||||
Size lowerBoundSize = sizeof(float) * numSamples * numCenters;
|
||||
Size upperBoundSize = sizeof(float) * numSamples;
|
||||
Size sSize = sizeof(float) * numCenters;
|
||||
Size halfcdistSize = sizeof(float) * numCenters * numCenters;
|
||||
Size newcdistSize = sizeof(float) * numCenters;
|
||||
|
||||
/* Calculate total size */
|
||||
Size totalSize = samplesSize + centersSize + newCentersSize + centerCountsSize + closestCentersSize + lowerBoundSize + upperBoundSize + sSize + halfcdistSize + newcdistSize;
|
||||
|
||||
/* Check memory requirements */
|
||||
/* Add one to error message to ceil */
|
||||
if (totalSize / 1024 > maintenance_work_mem)
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||
errmsg("memory required is %zu MB, maintenance_work_mem is %d MB",
|
||||
totalSize / (1024 * 1024) + 1, maintenance_work_mem / 1024)));
|
||||
|
||||
/* Set support functions */
|
||||
procinfo = index_getprocinfo(index, 1, IVFFLAT_KMEANS_DISTANCE_PROC);
|
||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||
collation = index->rd_indcollation[0];
|
||||
|
||||
/* Allocate space */
|
||||
centerCounts = palloc(sizeof(int) * numCenters);
|
||||
closestCenters = palloc(sizeof(int) * numSamples);
|
||||
lowerBound = palloc(sizeof(double) * numSamples * numCenters);
|
||||
upperBound = palloc(sizeof(double) * numSamples);
|
||||
s = palloc(sizeof(double) * numCenters);
|
||||
halfcdist = palloc(sizeof(double) * numCenters * numCenters);
|
||||
newcdist = palloc(sizeof(double) * numCenters);
|
||||
/* Use float instead of double to save memory */
|
||||
centerCounts = palloc(centerCountsSize);
|
||||
closestCenters = palloc(closestCentersSize);
|
||||
lowerBound = palloc_extended(lowerBoundSize, MCXT_ALLOC_HUGE);
|
||||
upperBound = palloc(upperBoundSize);
|
||||
s = palloc(sSize);
|
||||
halfcdist = palloc(halfcdistSize);
|
||||
newcdist = palloc(newcdistSize);
|
||||
|
||||
newCenters = VectorArrayInit(numCenters, dimensions);
|
||||
for (j = 0; j < numCenters; j++)
|
||||
|
||||
@@ -73,6 +73,7 @@ GetScanLists(IndexScanDesc scan, Datum value)
|
||||
}
|
||||
|
||||
/* Sort by distance */
|
||||
/* TODO Use heap for performance */
|
||||
qsort(so->lists, listCount, sizeof(IvfflatScanList), CompareLists);
|
||||
|
||||
if (so->probes > listCount)
|
||||
@@ -153,6 +154,8 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
}
|
||||
|
||||
tuplesort_performsort(so->sortstate);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -268,9 +271,8 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
return false;
|
||||
}
|
||||
|
||||
GetScanLists(scan, value);
|
||||
GetScanItems(scan, value);
|
||||
tuplesort_performsort(so->sortstate);
|
||||
IvfflatBench("GetScanLists", GetScanLists(scan, value));
|
||||
IvfflatBench("GetScanItems", GetScanItems(scan, value));
|
||||
so->first = false;
|
||||
|
||||
/* Clean up if we allocated a new value */
|
||||
|
||||
@@ -153,11 +153,13 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
|
||||
*/
|
||||
void
|
||||
IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo,
|
||||
BlockNumber insertPage, BlockNumber startPage, ForkNumber forkNum)
|
||||
BlockNumber insertPage, BlockNumber originalInsertPage,
|
||||
BlockNumber startPage, ForkNumber forkNum)
|
||||
{
|
||||
Buffer buf;
|
||||
Page page;
|
||||
IvfflatList list;
|
||||
bool changed = false;
|
||||
|
||||
buf = ReadBufferExtended(index, forkNum, listInfo.blkno, RBM_NORMAL, NULL);
|
||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||
@@ -165,12 +167,29 @@ IvfflatUpdateList(Relation index, GenericXLogState *state, ListInfo listInfo,
|
||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||
list = (IvfflatList) PageGetItem(page, PageGetItemId(page, listInfo.offno));
|
||||
|
||||
if (BlockNumberIsValid(insertPage))
|
||||
list->insertPage = insertPage;
|
||||
if (BlockNumberIsValid(insertPage) && insertPage != list->insertPage)
|
||||
{
|
||||
/* Skip update if insert page is lower than original insert page */
|
||||
/* This is needed to prevent insert from overwriting vacuum */
|
||||
if (!BlockNumberIsValid(originalInsertPage) || insertPage >= originalInsertPage)
|
||||
{
|
||||
list->insertPage = insertPage;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (BlockNumberIsValid(startPage))
|
||||
if (BlockNumberIsValid(startPage) && startPage != list->startPage)
|
||||
{
|
||||
list->startPage = startPage;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
/* Could only commit if changed, but extra complexity isn't needed */
|
||||
IvfflatCommitBuffer(buf, state);
|
||||
/* Only commit if changed */
|
||||
if (changed)
|
||||
IvfflatCommitBuffer(buf, state);
|
||||
else
|
||||
{
|
||||
GenericXLogAbort(state);
|
||||
UnlockReleaseBuffer(buf);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
ItemPointer htup;
|
||||
OffsetNumber deletable[MaxOffsetNumber];
|
||||
int ndeletable;
|
||||
OffsetNumber startPages[MaxOffsetNumber];
|
||||
BlockNumber startPages[MaxOffsetNumber];
|
||||
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
||||
BlockNumber searchPage;
|
||||
BlockNumber insertPage;
|
||||
@@ -98,6 +98,11 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
stats->num_index_tuples++;
|
||||
}
|
||||
|
||||
/* Set to first free page */
|
||||
/* Must be set before searchPage is updated */
|
||||
if (!BlockNumberIsValid(insertPage) && ndeletable > 0)
|
||||
insertPage = searchPage;
|
||||
|
||||
searchPage = IvfflatPageGetOpaque(page)->nextblkno;
|
||||
|
||||
if (ndeletable > 0)
|
||||
@@ -106,10 +111,6 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
PageIndexMultiDelete(page, deletable, ndeletable);
|
||||
MarkBufferDirty(buf);
|
||||
GenericXLogFinish(state);
|
||||
|
||||
/* Set to first free page */
|
||||
if (!BlockNumberIsValid(insertPage))
|
||||
insertPage = searchPage;
|
||||
}
|
||||
else
|
||||
GenericXLogAbort(state);
|
||||
@@ -123,10 +124,10 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
||||
* We don't add or delete items from lists pages, so offset won't
|
||||
* change.
|
||||
*/
|
||||
if (!BlockNumberIsValid(insertPage))
|
||||
if (BlockNumberIsValid(insertPage))
|
||||
{
|
||||
listInfo.offno = coffno;
|
||||
IvfflatUpdateList(index, state, listInfo, insertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
IvfflatUpdateList(index, state, listInfo, insertPage, InvalidBlockNumber, InvalidBlockNumber, MAIN_FORKNUM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
30
src/vector.c
30
src/vector.c
@@ -10,11 +10,16 @@
|
||||
#include "utils/array.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/lsyscache.h"
|
||||
#include "utils/numeric.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 120000
|
||||
#include "utils/float.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM < 130000
|
||||
#define TYPALIGN_INT 'i'
|
||||
#endif
|
||||
|
||||
PG_MODULE_MAGIC;
|
||||
|
||||
/*
|
||||
@@ -345,6 +350,8 @@ array_to_vector(PG_FUNCTION_ARGS)
|
||||
result->x[i] = DatumGetFloat8(elemsp[i]);
|
||||
else if (ARR_ELEMTYPE(array) == FLOAT4OID)
|
||||
result->x[i] = DatumGetFloat4(elemsp[i]);
|
||||
else if (ARR_ELEMTYPE(array) == NUMERICOID)
|
||||
result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(elemsp[i])));
|
||||
else
|
||||
ereport(ERROR,
|
||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||
@@ -356,6 +363,29 @@ array_to_vector(PG_FUNCTION_ARGS)
|
||||
PG_RETURN_POINTER(result);
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert vector to float4[]
|
||||
*/
|
||||
PG_FUNCTION_INFO_V1(vector_to_float4);
|
||||
Datum
|
||||
vector_to_float4(PG_FUNCTION_ARGS)
|
||||
{
|
||||
Vector *vec = PG_GETARG_VECTOR_P(0);
|
||||
Datum *d;
|
||||
ArrayType *result;
|
||||
int i;
|
||||
|
||||
d = (Datum *) palloc(sizeof(Datum) * vec->dim);
|
||||
|
||||
for (i = 0; i < vec->dim; i++)
|
||||
d[i] = Float4GetDatum(vec->x[i]);
|
||||
|
||||
/* Use TYPALIGN_INT for float4 */
|
||||
result = construct_array(d, vec->dim, FLOAT4OID, sizeof(float4), true, TYPALIGN_INT);
|
||||
|
||||
PG_RETURN_POINTER(result);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the L2 distance between vectors
|
||||
*/
|
||||
|
||||
@@ -6,6 +6,12 @@ SELECT ARRAY[1,2,3]::vector;
|
||||
[1,2,3]
|
||||
(1 row)
|
||||
|
||||
SELECT ARRAY[1.0,2.0,3.0]::vector;
|
||||
array
|
||||
---------
|
||||
[1,2,3]
|
||||
(1 row)
|
||||
|
||||
SELECT ARRAY[1,2,3]::float4[]::vector;
|
||||
array
|
||||
---------
|
||||
@@ -28,5 +34,18 @@ SELECT '{-Infinity}'::real[]::vector;
|
||||
ERROR: infinite value not allowed in vector
|
||||
SELECT '{}'::real[]::vector;
|
||||
ERROR: vector must have at least 1 dimension
|
||||
SELECT '[1,2,3]'::vector::real[];
|
||||
float4
|
||||
---------
|
||||
{1,2,3}
|
||||
(1 row)
|
||||
|
||||
SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
|
||||
ERROR: vector cannot have more than 1024 dimensions
|
||||
-- ensure no error
|
||||
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
|
||||
?column?
|
||||
----------
|
||||
t
|
||||
(1 row)
|
||||
|
||||
|
||||
@@ -53,3 +53,12 @@ LINE 1: SELECT '[1,]'::vector;
|
||||
^
|
||||
SELECT '[1,2,3]'::vector(2);
|
||||
ERROR: expected 2 dimensions, not 3
|
||||
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::vector[]);
|
||||
unnest
|
||||
---------
|
||||
[1,2,3]
|
||||
[4,5,6]
|
||||
(2 rows)
|
||||
|
||||
SELECT '{"[1,2,3]"}'::vector(2)[];
|
||||
ERROR: expected 2 dimensions, not 3
|
||||
|
||||
@@ -2,6 +2,7 @@ SET client_min_messages = warning;
|
||||
CREATE EXTENSION IF NOT EXISTS vector;
|
||||
|
||||
SELECT ARRAY[1,2,3]::vector;
|
||||
SELECT ARRAY[1.0,2.0,3.0]::vector;
|
||||
SELECT ARRAY[1,2,3]::float4[]::vector;
|
||||
SELECT ARRAY[1,2,3]::float8[]::vector;
|
||||
SELECT '{NULL}'::real[]::vector;
|
||||
@@ -9,4 +10,8 @@ SELECT '{NaN}'::real[]::vector;
|
||||
SELECT '{Infinity}'::real[]::vector;
|
||||
SELECT '{-Infinity}'::real[]::vector;
|
||||
SELECT '{}'::real[]::vector;
|
||||
SELECT '[1,2,3]'::vector::real[];
|
||||
SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
|
||||
|
||||
-- ensure no error
|
||||
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
|
||||
|
||||
@@ -13,3 +13,6 @@ SELECT '1,2,3'::vector;
|
||||
SELECT '[]'::vector;
|
||||
SELECT '[1,]'::vector;
|
||||
SELECT '[1,2,3]'::vector(2);
|
||||
|
||||
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::vector[]);
|
||||
SELECT '{"[1,2,3]"}'::vector(2)[];
|
||||
|
||||
@@ -34,9 +34,10 @@ sub test_index_replay
|
||||
my $r2 = rand();
|
||||
my $r3 = rand();
|
||||
|
||||
my $queries = qq(SET enable_seqscan=off;
|
||||
SELECT * FROM tst ORDER BY v <-> '[$r1,$r2,$r3]' LIMIT 10;
|
||||
);
|
||||
my $queries = qq(
|
||||
SET enable_seqscan = off;
|
||||
SELECT * FROM tst ORDER BY v <-> '[$r1,$r2,$r3]' LIMIT 10;
|
||||
);
|
||||
|
||||
# Run test queries and compare their result
|
||||
my $primary_result = $node_primary->safe_psql("postgres", $queries);
|
||||
@@ -65,10 +66,9 @@ $node_replica->start;
|
||||
$node_primary->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||
$node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
|
||||
$node_primary->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i%10, ARRAY[random(), random(), random()] FROM generate_series(1,100000) i;"
|
||||
"INSERT INTO tst SELECT i % 10, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
|
||||
);
|
||||
$node_primary->safe_psql("postgres",
|
||||
"CREATE INDEX ON tst USING ivfflat (v);");
|
||||
$node_primary->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
|
||||
|
||||
# Test that queries give same result
|
||||
test_index_replay('initial');
|
||||
@@ -82,7 +82,7 @@ for my $i (1 .. 10)
|
||||
test_index_replay("vacuum $i");
|
||||
my ($start, $end) = (100001 + ($i - 1) * 10000, 100000 + $i * 10000);
|
||||
$node_primary->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i%10, ARRAY[random(), random(), random()] FROM generate_series($start,$end) i;"
|
||||
"INSERT INTO tst SELECT i % 10, ARRAY[random(), random(), random()] FROM generate_series($start, $end) i;"
|
||||
);
|
||||
test_index_replay("insert $i");
|
||||
}
|
||||
|
||||
32
test/t/002_vacuum.pl
Normal file
32
test/t/002_vacuum.pl
Normal file
@@ -0,0 +1,32 @@
|
||||
use strict;
|
||||
use warnings;
|
||||
use PostgresNode;
|
||||
use TestLib;
|
||||
use Test::More tests => 1;
|
||||
|
||||
# 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(3));");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i%10, ARRAY[i%1000, i%333, i%55] FROM generate_series(1, 100000) i;"
|
||||
);
|
||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
|
||||
|
||||
# Get size
|
||||
my $size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
|
||||
|
||||
# Delete all, vacuum, and insert same data
|
||||
$node->safe_psql("postgres", "DELETE FROM tst;");
|
||||
$node->safe_psql("postgres", "VACUUM tst;");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i % 10, ARRAY[i % 1000, i % 333, i % 55] FROM generate_series(1, 100000) i;"
|
||||
);
|
||||
|
||||
# Check size
|
||||
my $new_size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_idx');");
|
||||
is($size, $new_size, "size does not change");
|
||||
72
test/t/003_recall.pl
Normal file
72
test/t/003_recall.pl
Normal file
@@ -0,0 +1,72 @@
|
||||
use strict;
|
||||
use warnings;
|
||||
use PostgresNode;
|
||||
use TestLib;
|
||||
use Test::More tests => 2;
|
||||
|
||||
my $node;
|
||||
my @queries = ();
|
||||
my @expected = ();
|
||||
|
||||
sub test_recall
|
||||
{
|
||||
my ($probes, $min) = @_;
|
||||
my $correct = 0;
|
||||
my $total = 0;
|
||||
|
||||
for my $i (0 .. $#queries) {
|
||||
my $actual = $node->safe_psql("postgres", qq(
|
||||
SET enable_seqscan = off;
|
||||
SET ivfflat.probes = $probes;
|
||||
SELECT i FROM tst ORDER BY v <-> '$queries[$i]' LIMIT 10;
|
||||
));
|
||||
my @actual_ids = split("\n", $actual);
|
||||
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||
|
||||
my @expected_ids = split("\n", $expected[$i]);
|
||||
|
||||
foreach (@expected_ids) {
|
||||
if (exists($actual_set{$_})) {
|
||||
$correct++;
|
||||
}
|
||||
$total++;
|
||||
}
|
||||
}
|
||||
|
||||
cmp_ok($correct / $total, ">=", $min);
|
||||
}
|
||||
|
||||
# Initialize node
|
||||
$node = get_new_node('node');
|
||||
$node->init;
|
||||
$node->start;
|
||||
|
||||
# Create table
|
||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
|
||||
);
|
||||
|
||||
# Generate queries
|
||||
for (1..20) {
|
||||
my $r1 = rand();
|
||||
my $r2 = rand();
|
||||
my $r3 = rand();
|
||||
push(@queries, "[$r1,$r2,$r3]");
|
||||
}
|
||||
|
||||
# Get exact results
|
||||
foreach (@queries) {
|
||||
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v <-> '$_' LIMIT 10;");
|
||||
push(@expected, $res);
|
||||
}
|
||||
|
||||
# Add index
|
||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
|
||||
|
||||
# Test approximate results
|
||||
test_recall(1, 0.8);
|
||||
|
||||
# Test probes
|
||||
test_recall(100, 1.0);
|
||||
@@ -1,4 +1,4 @@
|
||||
comment = 'vector data type and ivfflat access method'
|
||||
default_version = '0.1.6'
|
||||
default_version = '0.2.5'
|
||||
module_pathname = '$libdir/vector'
|
||||
relocatable = true
|
||||
|
||||
Reference in New Issue
Block a user