Compare commits

..

8 Commits

Author SHA1 Message Date
Andrew Kane
bb127fce8d Try again 2022-12-09 02:01:39 -08:00
Andrew Kane
7ce4e1f53e Skip IPC::Run 2022-12-09 01:57:10 -08:00
Andrew Kane
6e41c81412 Skip tests 2022-12-09 01:06:03 -08:00
Andrew Kane
98ec05145b Install IPC::Run 2022-12-09 00:57:28 -08:00
Andrew Kane
e302c99d4a Extract tar 2022-12-09 00:52:34 -08:00
Andrew Kane
d6ab29e772 Try again 2022-12-09 00:47:45 -08:00
Andrew Kane
6ad96fe8ca Use set 2022-12-08 23:05:11 -08:00
Andrew Kane
e52ef4f2b5 Added prove_installcheck for Windows 2022-12-08 22:57:46 -08:00
33 changed files with 302 additions and 1031 deletions

View File

@@ -1,6 +1,6 @@
root = true root = true
[*.{c,h,pl,pm,sql}] [*.{c,h,pl,pm}]
indent_style = tab indent_style = tab
indent_size = tab indent_size = tab
tab_width = 4 tab_width = 4

View File

@@ -2,22 +2,12 @@ name: build
on: [push, pull_request] on: [push, pull_request]
jobs: jobs:
ubuntu: ubuntu:
runs-on: ${{ matrix.os }} runs-on: ubuntu-latest
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }} if: ${{ !startsWith(github.ref_name, 'windows') }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
include: postgres: [15, 14, 13, 12, 11, 10]
- postgres: 15
os: ubuntu-22.04
- postgres: 14
os: ubuntu-22.04
- postgres: 13
os: ubuntu-20.04
- postgres: 12
os: ubuntu-20.04
- postgres: 11
os: ubuntu-20.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1 - uses: ankane/setup-postgres@v1
@@ -34,7 +24,7 @@ jobs:
- run: | - run: |
sudo apt-get update sudo apt-get update
sudo apt-get install libipc-run-perl sudo apt-get install libipc-run-perl
- run: make prove_installcheck make prove_installcheck
mac: mac:
runs-on: macos-latest runs-on: macos-latest
if: ${{ !startsWith(github.ref_name, 'windows') }} if: ${{ !startsWith(github.ref_name, 'windows') }}
@@ -50,23 +40,26 @@ jobs:
run: cat regression.diffs run: cat regression.diffs
- run: | - run: |
brew install cpanm brew install cpanm
cpanm --notest IPC::Run cpanm IPC::Run
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz
tar xf REL_14_5.tar.gz tar xf REL_14_5.tar.gz
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5" make prove_installcheck PROVE=prove PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
windows: windows:
runs-on: windows-latest runs-on: windows-latest
if: ${{ !startsWith(github.ref_name, 'mac') }}
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1 - uses: ankane/setup-postgres@v1
with: with:
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"
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 && ^ curl -Ls -o REL_14_5.tar.gz https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz
nmake /NOLOGO /F Makefile.win clean && ^ 7z x REL_14_5.tar.gz
nmake /NOLOGO /F Makefile.win uninstall 7z x REL_14_5.tar
ls ./postgres-REL_14_5/src/test/perl
set PROVE=prove
set PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl"
nmake /NOLOGO /F Makefile.win prove_installcheck
shell: cmd shell: cmd

6
.gitignore vendored
View File

@@ -1,5 +1,4 @@
/dist/ /dist/
/log/
/results/ /results/
/tmp_check/ /tmp_check/
/sql/vector--?.?.?.sql /sql/vector--?.?.?.sql
@@ -7,8 +6,3 @@ regression.*
*.o *.o
*.so *.so
*.bc *.bc
*.dll
*.dylib
*.obj
*.lib
*.exp

View File

@@ -1,25 +1,8 @@
## 0.4.2 (unreleased) ## 0.4.0 (unreleased)
- Added notice when index created with little data
- Fixed installation error with Postgres 12.0-12.2
## 0.4.1 (2023-03-21)
- Improved performance of cosine distance
- Fixed index scan count
## 0.4.0 (2023-01-11)
If upgrading with Postgres < 13, see [this note](https://github.com/pgvector/pgvector#040).
- Changed text representation for vector elements to match `real` - Changed text representation for vector elements to match `real`
- Changed storage for vector from `plain` to `extended`
- Increased max dimensions for vector from 1024 to 16000
- Increased max dimensions for index from 1024 to 2000
- Improved accuracy of text parsing for certain inputs - Improved accuracy of text parsing for certain inputs
- Added `avg` aggregate for vector
- Added experimental support for Windows - Added experimental support for Windows
- Dropped support for Postgres 10
## 0.3.2 (2022-11-22) ## 0.3.2 (2022-11-22)

View File

@@ -1,11 +1,9 @@
ARG PG_MAJOR=15 FROM postgres:15
FROM postgres:$PG_MAJOR
ARG PG_MAJOR
COPY . /tmp/pgvector COPY . /tmp/pgvector
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-$PG_MAJOR && \ apt-get install -y --no-install-recommends build-essential postgresql-server-dev-15 && \
cd /tmp/pgvector && \ cd /tmp/pgvector && \
make clean && \ make clean && \
make OPTFLAGS="" && \ make OPTFLAGS="" && \
@@ -13,6 +11,6 @@ RUN apt-get update && \
mkdir /usr/share/doc/pgvector && \ mkdir /usr/share/doc/pgvector && \
cp LICENSE README.md /usr/share/doc/pgvector && \ cp LICENSE README.md /usr/share/doc/pgvector && \
rm -r /tmp/pgvector && \ rm -r /tmp/pgvector && \
apt-get remove -y build-essential postgresql-server-dev-$PG_MAJOR && \ apt-get remove -y build-essential postgresql-server-dev-15 && \
apt-get autoremove -y && \ apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*

View File

@@ -1,4 +1,4 @@
Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group Portions Copyright (c) 1996-2021, 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

View File

@@ -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.4.1", "version": "0.3.2",
"maintainer": [ "maintainer": [
"Andrew Kane <andrew@ankane.org>" "Andrew Kane <andrew@ankane.org>"
], ],
@@ -12,7 +12,7 @@
"prereqs": { "prereqs": {
"runtime": { "runtime": {
"requires": { "requires": {
"PostgreSQL": "11.0.0" "PostgreSQL": "10.0.0"
} }
} }
}, },
@@ -20,7 +20,7 @@
"vector": { "vector": {
"file": "sql/vector.sql", "file": "sql/vector.sql",
"docfile": "README.md", "docfile": "README.md",
"version": "0.4.1", "version": "0.3.2",
"abstract": "Open-source vector similarity search for Postgres" "abstract": "Open-source vector similarity search for Postgres"
} }
}, },

View File

@@ -1,5 +1,5 @@
EXTENSION = vector EXTENSION = vector
EXTVERSION = 0.4.1 EXTVERSION = 0.3.2
MODULE_big = vector MODULE_big = vector
DATA = $(wildcard sql/*--*.sql) DATA = $(wildcard sql/*--*.sql)
@@ -14,7 +14,6 @@ OPTFLAGS = -march=native
# Mac ARM doesn't support -march=native # Mac ARM doesn't support -march=native
ifeq ($(shell uname -s), Darwin) ifeq ($(shell uname -s), Darwin)
ifeq ($(shell uname -p), arm) ifeq ($(shell uname -p), arm)
# no difference with -march=armv8.5-a
OPTFLAGS = OPTFLAGS =
endif endif
endif endif
@@ -41,11 +40,6 @@ PG_CONFIG ?= pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs) PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS) include $(PGXS)
# for Mac
ifeq ($(PROVE),)
PROVE = prove
endif
# for Postgres 15 # for Postgres 15
PROVE_FLAGS += -I ./test/perl PROVE_FLAGS += -I ./test/perl
@@ -62,4 +56,4 @@ dist:
.PHONY: docker .PHONY: docker
docker: docker:
docker build --pull --no-cache --platform linux/amd64 -t ankane/pgvector:latest . docker build --pull --no-cache -t ankane/pgvector:latest .

View File

@@ -1,5 +1,5 @@
EXTENSION = vector EXTENSION = vector
EXTVERSION = 0.4.1 EXTVERSION = 0.3.2
OBJS = 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\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
@@ -24,9 +24,6 @@ sql\$(EXTENSION)--$(EXTVERSION).sql: sql\$(EXTENSION).sql
copy sql\$(EXTENSION).sql $@ copy sql\$(EXTENSION).sql $@
# TODO use pg_config # TODO use pg_config
!ifndef PGROOT
!error PGROOT is not set
!endif
BINDIR = $(PGROOT)\bin BINDIR = $(PGROOT)\bin
INCLUDEDIR = $(PGROOT)\include INCLUDEDIR = $(PGROOT)\include
INCLUDEDIR_SERVER = $(PGROOT)\include\server INCLUDEDIR_SERVER = $(PGROOT)\include\server
@@ -38,7 +35,7 @@ CFLAGS = /nologo /I"$(INCLUDEDIR_SERVER)\port\win32_msvc" /I"$(INCLUDEDIR_SERVER
CFLAGS = $(CFLAGS) $(PG_CFLAGS) CFLAGS = $(CFLAGS) $(PG_CFLAGS)
SHLIB = $(EXTENSION).dll SHLIB = src\$(EXTENSION).dll
LIBS = "$(LIBDIR)\postgres.lib" LIBS = "$(LIBDIR)\postgres.lib"
@@ -58,13 +55,8 @@ install:
installcheck: installcheck:
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS) "$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
uninstall: prove_installcheck:
del /f "$(PKGLIBDIR)\$(SHLIB)" rm -rf tmp_check
del /f "$(SHAREDIR)\extension\$(EXTENSION).control" set PGPORT=65432
del /f "$(SHAREDIR)\extension\vector--*.sql" set PG_REGRESS="$(BINDIR)\pg_regress"
$(PROVE) $(PG_PROVE_FLAGS) $(PROVE_FLAGS) test/t/*.pl
clean:
del /f $(SHLIB) $(EXTENSION).lib $(EXTENSION).exp
del /f $(OBJS)
del /f sql\$(EXTENSION)--$(EXTVERSION).sql
del /f /s /q results regression.diffs regression.out tmp_check tmp_check_iso log output_iso

338
README.md
View File

@@ -2,21 +2,22 @@
Open-source vector similarity search for Postgres Open-source vector similarity search for Postgres
Supports ```sql
CREATE TABLE items (embedding vector(3));
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops);
SELECT * FROM items ORDER BY embedding <-> '[1,2,3]' LIMIT 5;
```
- exact and approximate nearest neighbor search Supports L2 distance, inner product, and cosine distance
- L2 distance, inner product, and cosine distance
- any [language](#languages) with a Postgres client
[![Build Status](https://github.com/pgvector/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/pgvector/pgvector/actions) [![Build Status](https://github.com/pgvector/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/pgvector/pgvector/actions)
## Installation ## Installation
Compile and install the extension (supports Postgres 11+) Compile and install the extension (supports Postgres 10+)
```sh ```sh
cd /tmp git clone --branch v0.3.2 https://github.com/pgvector/pgvector.git
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector cd pgvector
make make
make install # may need sudo make install # may need sudo
@@ -28,178 +29,81 @@ Then load it in databases where you want to use it
CREATE EXTENSION vector; CREATE EXTENSION vector;
``` ```
See the [installation notes](#installation-notes) if you run into issues You can also install it with [Docker](#docker), [Homebrew](#homebrew), or [PGXN](#pgxn)
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [Yum](#yum), or [conda-forge](#conda-forge)
## Getting Started ## Getting Started
Create a vector column with 3 dimensions Create a vector column with 3 dimensions
```sql ```sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3)); CREATE TABLE items (embedding vector(3));
``` ```
Insert vectors Insert values
```sql ```sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]'); INSERT INTO items VALUES ('[1,2,3]'), ('[4,5,6]');
``` ```
Get the nearest neighbors by L2 distance Get the nearest neighbor by L2 distance
```sql ```sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5; SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 1;
``` ```
Also supports inner product (`<#>`) and cosine distance (`<=>`) Also supports inner product (`<#>`) and cosine distance (`<=>`)
Note: `<#>` returns the negative inner product since Postgres only supports `ASC` order index scans on operators Note: `<#>` returns the negative inner product since Postgres only supports `ASC` order index scans on operators
## Storing
Create a new table with a vector column
```sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
```
Or add a vector column to an existing table
```sql
ALTER TABLE items ADD COLUMN embedding vector(3);
```
Insert vectors
```sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
```
Upsert vectors
```sql
INSERT INTO items (id, embedding) VALUES (1, '[1,2,3]'), (2, '[4,5,6]')
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
```
Update vectors
```sql
UPDATE items SET embedding = '[1,2,3]' WHERE id = 1;
```
Delete vectors
```sql
DELETE FROM items WHERE id = 1;
```
## Querying
Get the nearest neighbors to a vector
```sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
Get the nearest neighbors to a row
```sql
SELECT * FROM items WHERE id != 1 ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1) LIMIT 5;
```
Get rows within a certain distance
```sql
SELECT * FROM items WHERE embedding <-> '[3,1,2]' < 5;
```
Note: Combine with `ORDER BY` and `LIMIT` to use an index
#### Distances
Get the distance
```sql
SELECT embedding <-> '[3,1,2]' AS distance FROM items;
```
For inner product, multiply by -1 (since `<#>` returns the negative inner product)
```sql
SELECT (embedding <#> '[3,1,2]') * -1 AS inner_product FROM items;
```
For cosine similarity, use 1 - cosine distance
```sql
SELECT 1 - (embedding <=> '[3,1,2]') AS cosine_similarity FROM items;
```
#### Aggregates
Average vectors
```sql
SELECT AVG(embedding) FROM items;
```
Average groups of vectors
```sql
SELECT category_id, AVG(embedding) FROM items GROUP BY category_id;
```
## Indexing ## Indexing
By default, pgvector performs exact nearest neighbor search, which provides perfect recall. Speed up queries with an approximate index. Add an index for each distance function you want to use.
You can add an index to use approximate nearest neighbor search, which trades some recall for performance. Unlike typical indexes, you will see different results for queries after adding an approximate index.
Three keys to achieving good recall are:
1. Create the index *after* the table has some data
2. Choose an appropriate number of lists - a good place to start is `rows / 1000` for up to 1M rows and `sqrt(rows)` for over 1M rows
3. When querying, specify an appropriate number of [probes](#query-options) (higher is better for recall, lower is better for speed) - a good place to start is `lists / 10` for up to 1M rows and `sqrt(lists)` for over 1M rows
Add an index for each distance function you want to use.
L2 distance L2 distance
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100); CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops);
``` ```
Inner product Inner product
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100); CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops);
``` ```
Cosine distance Cosine distance
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops);
``` ```
Vectors with up to 2,000 dimensions can be indexed. 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 items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
```
A [good place to start](https://github.com/facebookresearch/faiss/issues/112) is `4 * sqrt(rows)`
### Query Options ### Query Options
Specify the number of probes (1 by default) Specify the number of probes (1 by default)
```sql ```sql
SET ivfflat.probes = 10; SET ivfflat.probes = 1;
``` ```
A higher value provides better recall at the cost of speed, and it can be set to the number of lists for exact nearest neighbor search (at which point the planner wont use the index) A higher value improves recall at the cost of speed.
Use `SET LOCAL` inside a transaction to set it for a single query Use `SET LOCAL` inside a transaction to set it for a single query
```sql ```sql
BEGIN; BEGIN;
SET LOCAL ivfflat.probes = 10; SET LOCAL ivfflat.probes = 1;
SELECT ... SELECT ...
COMMIT; COMMIT;
``` ```
@@ -215,9 +119,10 @@ SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
The phases are: The phases are:
1. `initializing` 1. `initializing`
2. `performing k-means` 2. `sampling table`
3. `sorting tuples` 3. `performing k-means`
4. `loading tuples` 4. `sorting tuples`
5. `loading tuples`
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
@@ -232,7 +137,7 @@ SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIM
can be indexed with: can be indexed with:
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100) WHERE (category_id = 123); CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WHERE (category_id = 123);
``` ```
To index many different values of `category_id`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `category_id`. To index many different values of `category_id`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `category_id`.
@@ -243,80 +148,23 @@ CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(cate
## Performance ## Performance
Use `EXPLAIN ANALYZE` to debug performance.
```sql
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
### 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`.
```sql ```sql
SET max_parallel_workers_per_gather = 4; SET max_parallel_workers_per_gather = 4;
``` ```
If vectors are normalized to length 1 (like [OpenAI embeddings](https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use)), use inner product for best performance.
```sql
SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
```
### Approximate Search
To speed up queries with an index, increase the number of inverted lists (at the expense of recall). To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
```sql ```sql
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);
``` ```
## 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.
Language | Libraries / Examples
--- | ---
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
C# | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
Haskell | [pgvector-haskell](https://github.com/pgvector/pgvector-haskell)
Java, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
Node.js | [pgvector-node](https://github.com/pgvector/pgvector-node)
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
R | [pgvector-r](https://github.com/pgvector/pgvector-r)
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
## 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 I want to index vectors with more than 2,000 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/ivfflat.h`
## Reference ## Reference
### Vector Type ### Vector Type
Each vector takes `4 * dimensions + 8` bytes of storage. Each element is a single precision floating-point number (like the `real` type in Postgres), and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Vectors can have up to 16,000 dimensions. Each vector takes `4 * dimensions + 8` bytes of storage. Each element is a single precision floating-point number (like the `real` type in Postgres), and all elements must be finite (no `NaN`, `Infinity` or `-Infinity`). Vectors can have up to 1024 dimensions.
### Vector Operators ### Vector Operators
@@ -332,53 +180,42 @@ Operator | Description
Function | Description Function | Description
--- | --- --- | ---
cosine_distance(vector, vector) → double precision | cosine distance cosine_distance(vector, vector) | cosine distance
inner_product(vector, vector) → double precision | inner product inner_product(vector, vector) | inner product
l2_distance(vector, vector) → double precision | Euclidean distance l2_distance(vector, vector) | Euclidean distance
vector_dims(vector) → integer | number of dimensions vector_dims(vector) | number of dimensions
vector_norm(vector) → double precision | Euclidean norm vector_norm(vector) | Euclidean norm
### Aggregate Functions ## Libraries
Function | Description Libraries that use pgvector:
--- | ---
avg(vector) → vector | arithmetic mean
## Installation Notes - [pgvector-python](https://github.com/pgvector/pgvector-python) (Python)
- [Neighbor](https://github.com/ankane/neighbor) (Ruby)
- [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-php](https://github.com/pgvector/pgvector-php) (PHP)
- [pgvector-rust](https://github.com/pgvector/pgvector-rust) (Rust)
- [pgvector-cpp](https://github.com/pgvector/pgvector-cpp) (C++)
- [pgvector-elixir](https://github.com/pgvector/pgvector-elixir) (Elixir)
### Postgres Location ## Frequently Asked Questions
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with: #### How many vectors can be stored in a single table?
```sh 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.
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
```
Then re-run the installation instructions (run `make clean` before `make` if needed) #### Is replication supported?
### Missing Header Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server. #### What if my data has more than 1024 dimensions?
For Ubuntu and Debian, use: Two things you can try are:
```sh 1. use dimensionality reduction
sudo apt-get install postgresql-server-dev-15 2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/vector.h`
```
Note: Replace `15` with your Postgres server version
### Windows
Support for Windows is currently experimental. Use `nmake` to build:
```cmd
set "PGROOT=C:\Program Files\PostgreSQL\15"
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector
nmake /F Makefile.win
nmake /F Makefile.win install
```
## Additional Installation Methods ## Additional Installation Methods
@@ -390,12 +227,12 @@ Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
docker pull ankane/pgvector docker pull ankane/pgvector
``` ```
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (run it the same way). This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres).
You can also build the image manually: You can also build the image manually
```sh ```sh
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git git clone --branch v0.3.2 https://github.com/pgvector/pgvector.git
cd pgvector cd pgvector
docker build -t pgvector . docker build -t pgvector .
``` ```
@@ -405,7 +242,7 @@ docker build -t pgvector .
With Homebrew Postgres, you can use: With Homebrew Postgres, you can use:
```sh ```sh
brew install pgvector brew install pgvector/brew/pgvector
``` ```
### PGXN ### PGXN
@@ -416,39 +253,14 @@ Install from the [PostgreSQL Extension Network](https://pgxn.org/dist/vector) wi
pgxn install vector pgxn install vector
``` ```
### Yum
RPM packages are available from the [PostgreSQL Yum Repository](https://yum.postgresql.org/). Follow the [setup instructions](https://www.postgresql.org/download/linux/redhat/) for your distribution and run:
```sh
sudo yum install pgvector_15
# or
sudo dnf install pgvector_15
```
Note: Replace `15` with your Postgres server version
### conda-forge
With Conda Postgres, install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with:
```sh
conda install -c conda-forge pgvector
```
This method is [community-maintained](https://github.com/conda-forge/pgvector-feedstock) by [@mmcauliffe](https://github.com/mmcauliffe)
## Hosted Postgres ## Hosted Postgres
pgvector is available on [these providers](https://github.com/pgvector/pgvector/issues/54). Some Postgres providers only support specific extensions. To request a new extension:
To request a new extension on other providers:
- Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/) - Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/)
- Google Cloud SQL - vote or comment on [this page](https://issuetracker.google.com/issues/265172065) - Google Cloud SQL - follow the instructions on [this page](https://cloud.google.com/sql/docs/postgres/extensions#requesting-support-for-a-new-extension)
- Azure Database - vote or comment on [this page](https://feedback.azure.com/d365community/idea/7b423322-6189-ed11-a81b-000d3ae49307)
- DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql) - DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql)
- Heroku Postgres - vote or comment on [this page](https://github.com/heroku/roadmap/issues/156) - Azure Database for PostgreSQL - follow the instructions on [this page](https://docs.microsoft.com/en-us/azure/postgresql/concepts-extensions#next-steps)
## Upgrading ## Upgrading
@@ -460,16 +272,6 @@ ALTER EXTENSION vector UPDATE;
## Upgrade Notes ## Upgrade Notes
### 0.4.0
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
```sql
ALTER TYPE vector SET (STORAGE = extended);
```
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
### 0.3.1 ### 0.3.1
If upgrading from 0.2.7 or 0.3.0, recreate all `ivfflat` indexes after upgrading to ensure all data is indexed. If upgrading from 0.2.7 or 0.3.0, recreate all `ivfflat` indexes after upgrading to ensure all data is indexed.

View File

@@ -7,13 +7,13 @@ DROP CAST (double precision[] AS vector);
DROP CAST (numeric[] AS vector); DROP CAST (numeric[] AS vector);
CREATE CAST (integer[] AS vector) CREATE CAST (integer[] AS vector)
WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT; WITH FUNCTION array_to_vector(integer[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (real[] AS vector) CREATE CAST (real[] AS vector)
WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT; WITH FUNCTION array_to_vector(real[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (double precision[] AS vector) CREATE CAST (double precision[] AS vector)
WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT; WITH FUNCTION array_to_vector(double precision[], integer, boolean) AS ASSIGNMENT;
CREATE CAST (numeric[] AS vector) CREATE CAST (numeric[] AS vector)
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT; WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;

View File

@@ -1,23 +0,0 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.4.0'" to load this file. \quit
-- remove this single line for Postgres < 13
ALTER TYPE vector SET (STORAGE = extended);
CREATE FUNCTION vector_accum(double precision[], vector) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE AGGREGATE avg(vector) (
SFUNC = vector_accum,
STYPE = double precision[],
FINALFUNC = vector_avg,
COMBINEFUNC = vector_combine,
INITCOND = '{0}',
PARALLEL = SAFE
);

View File

@@ -1,2 +0,0 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.4.1'" to load this file. \quit

View File

@@ -25,8 +25,7 @@ CREATE TYPE vector (
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
STORAGE = extended
); );
-- functions -- functions
@@ -84,26 +83,6 @@ CREATE FUNCTION vector_negative_inner_product(vector, vector) RETURNS float8
CREATE FUNCTION vector_spherical_distance(vector, vector) RETURNS float8 CREATE FUNCTION vector_spherical_distance(vector, vector) RETURNS float8
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_accum(double precision[], vector) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_avg(double precision[]) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION vector_combine(double precision[], double precision[]) RETURNS double precision[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
-- aggregates
CREATE AGGREGATE avg(vector) (
SFUNC = vector_accum,
STYPE = double precision[],
FINALFUNC = vector_avg,
COMBINEFUNC = vector_combine,
INITCOND = '{0}',
PARALLEL = SAFE
);
-- cast functions -- cast functions
CREATE FUNCTION vector(vector, integer, boolean) RETURNS vector CREATE FUNCTION vector(vector, integer, boolean) RETURNS vector

View File

@@ -6,7 +6,6 @@
#include "ivfflat.h" #include "ivfflat.h"
#include "miscadmin.h" #include "miscadmin.h"
#include "storage/bufmgr.h" #include "storage/bufmgr.h"
#include "utils/memutils.h"
#if PG_VERSION_NUM >= 140000 #if PG_VERSION_NUM >= 140000
#include "utils/backend_progress.h" #include "utils/backend_progress.h"
@@ -23,8 +22,13 @@
#define PROGRESS_CREATEIDX_TUPLES_DONE 0 #define PROGRESS_CREATEIDX_TUPLES_DONE 0
#endif #endif
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_d.h" #include "catalog/pg_operator_d.h"
#include "catalog/pg_type_d.h" #include "catalog/pg_type_d.h"
#else
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#endif
#if PG_VERSION_NUM >= 130000 #if PG_VERSION_NUM >= 130000
#define CALLBACK_ITEM_POINTER ItemPointer tid #define CALLBACK_ITEM_POINTER ItemPointer tid
@@ -39,16 +43,20 @@
#endif #endif
/* /*
* Add sample * Callback for sampling
*/ */
static void static void
AddSample(Datum *values, IvfflatBuildState * buildstate) SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{ {
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
VectorArray samples = buildstate->samples; VectorArray samples = buildstate->samples;
int targsamples = samples->maxlen; int targsamples = samples->maxlen;
Datum value = values[0];
/* Detoast once for all calls */ /* Skip nulls */
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0])); if (isnull[0])
return;
/* /*
* Normalize with KMEANS_NORM_PROC since spherical distance function * Normalize with KMEANS_NORM_PROC since spherical distance function
@@ -86,31 +94,6 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
} }
} }
/*
* Callback for sampling
*/
static void
SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
MemoryContext oldCtx;
/* Skip nulls */
if (isnull[0])
return;
/* Use memory context since detoast can allocate */
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
/* Add sample */
AddSample(values, state);
/* Reset memory context */
MemoryContextSwitchTo(oldCtx);
MemoryContextReset(buildstate->tmpCtx);
}
/* /*
* Sample rows with same logic as ANALYZE * Sample rows with same logic as ANALYZE
*/ */
@@ -120,6 +103,8 @@ SampleRows(IvfflatBuildState * buildstate)
int targsamples = buildstate->samples->maxlen; int targsamples = buildstate->samples->maxlen;
BlockNumber totalblocks = RelationGetNumberOfBlocks(buildstate->heap); BlockNumber totalblocks = RelationGetNumberOfBlocks(buildstate->heap);
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_SAMPLE);
buildstate->rowstoskip = -1; buildstate->rowstoskip = -1;
BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, RandomInt()); BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, RandomInt());
@@ -132,28 +117,38 @@ SampleRows(IvfflatBuildState * buildstate)
#if PG_VERSION_NUM >= 120000 #if PG_VERSION_NUM >= 120000
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo, table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL); false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#else #elif PG_VERSION_NUM >= 110000
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo, IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL); false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#else
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, targblock, 1, SampleCallback, (void *) buildstate);
#endif #endif
} }
} }
/* /*
* Add tuple to sort * Callback for table_index_build_scan
*/ */
static void static void
AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState * buildstate) BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{ {
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
double distance; double distance;
double minDistance = DBL_MAX; double minDistance = DBL_MAX;
int closestCenter = -1; int closestCenter = -1;
VectorArray centers = buildstate->centers; VectorArray centers = buildstate->centers;
TupleTableSlot *slot = buildstate->slot; TupleTableSlot *slot = buildstate->slot;
Datum value = values[0];
int i; int i;
/* Detoast once for all calls */ #if PG_VERSION_NUM < 130000
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0])); ItemPointer tid = &hup->t_self;
#endif
if (isnull[0])
return;
/* Normalize if needed */ /* Normalize if needed */
if (buildstate->normprocinfo != NULL) if (buildstate->normprocinfo != NULL)
@@ -201,35 +196,6 @@ AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState
buildstate->indtuples++; buildstate->indtuples++;
} }
/*
* Callback for table_index_build_scan
*/
static void
BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
MemoryContext oldCtx;
#if PG_VERSION_NUM < 130000
ItemPointer tid = &hup->t_self;
#endif
/* Skip nulls */
if (isnull[0])
return;
/* Use memory context since detoast can allocate */
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
/* Add tuple to sort */
AddTupleToSort(index, tid, values, buildstate);
/* Reset memory context */
MemoryContextSwitchTo(oldCtx);
MemoryContextReset(buildstate->tmpCtx);
}
/* /*
* Get index tuple from sort state * Get index tuple from sort state
*/ */
@@ -239,7 +205,11 @@ GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot,
Datum value; Datum value;
bool isnull; bool isnull;
#if PG_VERSION_NUM >= 100000
if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL)) if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL))
#else
if (tuplesort_gettupleslot(sortstate, true, slot, NULL))
#endif
{ {
*list = DatumGetInt32(slot_getattr(slot, 1, &isnull)); *list = DatumGetInt32(slot_getattr(slot, 1, &isnull));
value = slot_getattr(slot, 3, &isnull); value = slot_getattr(slot, 3, &isnull);
@@ -338,9 +308,6 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
if (buildstate->dimensions < 0) if (buildstate->dimensions < 0)
elog(ERROR, "column does not have dimensions"); elog(ERROR, "column does not have dimensions");
if (buildstate->dimensions > IVFFLAT_MAX_DIM)
elog(ERROR, "column cannot have more than %d dimensions for ivfflat index", IVFFLAT_MAX_DIM);
buildstate->reltuples = 0; buildstate->reltuples = 0;
buildstate->indtuples = 0; buildstate->indtuples = 0;
@@ -364,7 +331,11 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
#endif #endif
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -1, 0); TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0); TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
#if PG_VERSION_NUM >= 110000
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0); TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0].atttypid, -1, 0);
#else
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0]->atttypid, -1, 0);
#endif
#if PG_VERSION_NUM >= 120000 #if PG_VERSION_NUM >= 120000
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual); buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
@@ -378,10 +349,6 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
/* Reuse for each tuple */ /* Reuse for each tuple */
buildstate->normvec = InitVector(buildstate->dimensions); buildstate->normvec = InitVector(buildstate->dimensions);
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
"Ivfflat build temporary context",
ALLOCSET_DEFAULT_SIZES);
#ifdef IVFFLAT_KMEANS_DEBUG #ifdef IVFFLAT_KMEANS_DEBUG
buildstate->inertia = 0; buildstate->inertia = 0;
buildstate->listSums = palloc0(sizeof(double) * buildstate->lists); buildstate->listSums = palloc0(sizeof(double) * buildstate->lists);
@@ -403,8 +370,6 @@ FreeBuildState(IvfflatBuildState * buildstate)
pfree(buildstate->listSums); pfree(buildstate->listSums);
pfree(buildstate->listCounts); pfree(buildstate->listCounts);
#endif #endif
MemoryContextDelete(buildstate->tmpCtx);
} }
/* /*
@@ -415,8 +380,6 @@ ComputeCenters(IvfflatBuildState * buildstate)
{ {
int numSamples; int numSamples;
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
/* Target 50 samples per list, with at least 10000 samples */ /* Target 50 samples per list, with at least 10000 samples */
/* The number of samples has a large effect on index build time */ /* The number of samples has a large effect on index build time */
numSamples = buildstate->lists * 50; numSamples = buildstate->lists * 50;
@@ -431,19 +394,10 @@ ComputeCenters(IvfflatBuildState * buildstate)
/* TODO Ensure within maintenance_work_mem */ /* TODO Ensure within maintenance_work_mem */
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions); buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions);
if (buildstate->heap != NULL) if (buildstate->heap != NULL)
{
SampleRows(buildstate); SampleRows(buildstate);
if (buildstate->samples->length < buildstate->lists)
{
ereport(NOTICE,
(errmsg("ivfflat index created with little data"),
errdetail("this will cause poor recall"),
errhint("drop the index until the table has more data")));
}
}
/* Calculate centers */ /* Calculate centers */
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers)); IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers));
/* Free samples before we allocate more memory */ /* Free samples before we allocate more memory */
@@ -581,7 +535,11 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_SORT); 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); buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, NULL, false);
#else
buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, false);
#endif
/* Add tuples to sort */ /* Add tuples to sort */
if (buildstate->heap != NULL) if (buildstate->heap != NULL)
@@ -589,9 +547,12 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
#if PG_VERSION_NUM >= 120000 #if PG_VERSION_NUM >= 120000
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo, buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, true, BuildCallback, (void *) buildstate, NULL); true, true, BuildCallback, (void *) buildstate, NULL);
#else #elif PG_VERSION_NUM >= 110000
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo, buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate, NULL); true, BuildCallback, (void *) buildstate, NULL);
#else
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate);
#endif #endif
} }

View File

@@ -45,6 +45,8 @@ ivfflatbuildphasename(int64 phasenum)
{ {
case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE: case PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE:
return "initializing"; return "initializing";
case PROGRESS_IVFFLAT_PHASE_SAMPLE:
return "sampling table";
case PROGRESS_IVFFLAT_PHASE_KMEANS: case PROGRESS_IVFFLAT_PHASE_KMEANS:
return "performing k-means"; return "performing k-means";
case PROGRESS_IVFFLAT_PHASE_SORT: case PROGRESS_IVFFLAT_PHASE_SORT:
@@ -64,7 +66,9 @@ static void
ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
Cost *indexStartupCost, Cost *indexTotalCost, Cost *indexStartupCost, Cost *indexTotalCost,
Selectivity *indexSelectivity, double *indexCorrelation Selectivity *indexSelectivity, double *indexCorrelation
#if PG_VERSION_NUM >= 100000
,double *indexPages ,double *indexPages
#endif
) )
{ {
GenericCosts costs; GenericCosts costs;
@@ -82,7 +86,9 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
*indexTotalCost = DBL_MAX; *indexTotalCost = DBL_MAX;
*indexSelectivity = 0; *indexSelectivity = 0;
*indexCorrelation = 0; *indexCorrelation = 0;
#if PG_VERSION_NUM >= 100000
*indexPages = 0; *indexPages = 0;
#endif
return; return;
} }
@@ -110,7 +116,9 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
*indexTotalCost = costs.indexTotalCost; *indexTotalCost = costs.indexTotalCost;
*indexSelectivity = costs.indexSelectivity; *indexSelectivity = costs.indexSelectivity;
*indexCorrelation = costs.indexCorrelation; *indexCorrelation = costs.indexCorrelation;
#if PG_VERSION_NUM >= 100000
*indexPages = costs.numIndexPages; *indexPages = costs.numIndexPages;
#endif
} }
/* /*
@@ -178,8 +186,12 @@ ivfflathandler(PG_FUNCTION_ARGS)
amroutine->amstorage = false; amroutine->amstorage = false;
amroutine->amclusterable = false; amroutine->amclusterable = false;
amroutine->ampredlocks = false; amroutine->ampredlocks = false;
#if PG_VERSION_NUM >= 100000
amroutine->amcanparallel = false; amroutine->amcanparallel = false;
#endif
#if PG_VERSION_NUM >= 110000
amroutine->amcaninclude = false; amroutine->amcaninclude = false;
#endif
#if PG_VERSION_NUM >= 130000 #if PG_VERSION_NUM >= 130000
amroutine->amusemaintenanceworkmem = false; /* not used during VACUUM */ amroutine->amusemaintenanceworkmem = false; /* not used during VACUUM */
amroutine->amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL; amroutine->amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL;
@@ -212,9 +224,11 @@ ivfflathandler(PG_FUNCTION_ARGS)
amroutine->amrestrpos = NULL; amroutine->amrestrpos = NULL;
/* Interface functions to support parallel index scans */ /* Interface functions to support parallel index scans */
#if PG_VERSION_NUM >= 100000
amroutine->amestimateparallelscan = NULL; amroutine->amestimateparallelscan = NULL;
amroutine->aminitparallelscan = NULL; amroutine->aminitparallelscan = NULL;
amroutine->amparallelrescan = NULL; amroutine->amparallelrescan = NULL;
#endif
PG_RETURN_POINTER(amroutine); PG_RETURN_POINTER(amroutine);
} }

View File

@@ -3,8 +3,8 @@
#include "postgres.h" #include "postgres.h"
#if PG_VERSION_NUM < 110000 #if PG_VERSION_NUM < 100000
#error "Requires PostgreSQL 11+" #error "Requires PostgreSQL 10+"
#endif #endif
#include "access/generic_xlog.h" #include "access/generic_xlog.h"
@@ -23,8 +23,6 @@
#include "portability/instr_time.h" #include "portability/instr_time.h"
#endif #endif
#define IVFFLAT_MAX_DIM 2000
/* Support functions */ /* Support functions */
#define IVFFLAT_DISTANCE_PROC 1 #define IVFFLAT_DISTANCE_PROC 1
#define IVFFLAT_NORM_PROC 2 #define IVFFLAT_NORM_PROC 2
@@ -44,9 +42,10 @@
/* Build phases */ /* Build phases */
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */ /* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
#define PROGRESS_IVFFLAT_PHASE_KMEANS 2 #define PROGRESS_IVFFLAT_PHASE_SAMPLE 2
#define PROGRESS_IVFFLAT_PHASE_SORT 3 #define PROGRESS_IVFFLAT_PHASE_KMEANS 3
#define PROGRESS_IVFFLAT_PHASE_LOAD 4 #define PROGRESS_IVFFLAT_PHASE_SORT 4
#define PROGRESS_IVFFLAT_PHASE_LOAD 5
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim)) #define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
@@ -147,9 +146,6 @@ typedef struct IvfflatBuildState
Tuplesortstate *sortstate; Tuplesortstate *sortstate;
TupleDesc tupdesc; TupleDesc tupdesc;
TupleTableSlot *slot; TupleTableSlot *slot;
/* Memory */
MemoryContext tmpCtx;
} IvfflatBuildState; } IvfflatBuildState;
typedef struct IvfflatMetaPageData typedef struct IvfflatMetaPageData
@@ -187,14 +183,6 @@ typedef struct IvfflatScanList
double distance; double distance;
} IvfflatScanList; } IvfflatScanList;
typedef struct IvfflatScanItem
{
pairingheap_node ph_node;
BlockNumber searchPage;
double distance;
ItemPointerData tid;
} IvfflatScanItem;
typedef struct IvfflatScanOpaqueData typedef struct IvfflatScanOpaqueData
{ {
int probes; int probes;
@@ -212,13 +200,6 @@ typedef struct IvfflatScanOpaqueData
FmgrInfo *normprocinfo; FmgrInfo *normprocinfo;
Oid collation; Oid collation;
/* Items */
int maxItems;
int itemCount;
pairingheap *itemQueue;
IvfflatScanItem *items;
IvfflatScanItem **sortedItems;
/* Lists */ /* Lists */
pairingheap *listQueue; pairingheap *listQueue;
IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER]; /* must come last */ IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER]; /* must come last */
@@ -253,7 +234,9 @@ bool ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer hea
#if PG_VERSION_NUM >= 140000 #if PG_VERSION_NUM >= 140000
,bool indexUnchanged ,bool indexUnchanged
#endif #endif
#if PG_VERSION_NUM >= 100000
,IndexInfo *indexInfo ,IndexInfo *indexInfo
#endif
); );
IndexBulkDeleteResult *ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state); IndexBulkDeleteResult *ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
IndexBulkDeleteResult *ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats); IndexBulkDeleteResult *ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats);

View File

@@ -4,7 +4,6 @@
#include "ivfflat.h" #include "ivfflat.h"
#include "storage/bufmgr.h" #include "storage/bufmgr.h"
#include "utils/memutils.h"
/* /*
* Find the list that minimizes the distance function * Find the list that minimizes the distance function
@@ -58,11 +57,8 @@ FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo *
* Insert a tuple into the index * Insert a tuple into the index
*/ */
static void static void
InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel) InsertTuple(Relation rel, IndexTuple itup, Relation heapRel, Datum *values)
{ {
IndexTuple itup;
Datum value;
FmgrInfo *normprocinfo;
Buffer buf; Buffer buf;
Page page; Page page;
GenericXLogState *state; GenericXLogState *state;
@@ -71,27 +67,11 @@ InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Rel
ListInfo listInfo; ListInfo listInfo;
BlockNumber originalInsertPage; BlockNumber originalInsertPage;
/* Detoast once for all calls */
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/* Normalize if needed */
normprocinfo = IvfflatOptionalProcInfo(rel, IVFFLAT_NORM_PROC);
if (normprocinfo != NULL)
{
if (!IvfflatNormValue(normprocinfo, rel->rd_indcollation[0], &value, NULL))
return;
}
/* Find the insert page - sets the page and list info */ /* Find the insert page - sets the page and list info */
FindInsertPage(rel, values, &insertPage, &listInfo); FindInsertPage(rel, values, &insertPage, &listInfo);
Assert(BlockNumberIsValid(insertPage)); Assert(BlockNumberIsValid(insertPage));
originalInsertPage = insertPage; originalInsertPage = insertPage;
/* Form tuple */
itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
itup->t_tid = *heap_tid;
/* Get tuple size */
itemsz = MAXALIGN(IndexTupleSize(itup)); itemsz = MAXALIGN(IndexTupleSize(itup));
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData))); Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
@@ -150,14 +130,9 @@ InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Rel
/* Unlock extend relation lock as early as possible */ /* Unlock extend relation lock as early as possible */
UnlockReleaseBuffer(metabuf); UnlockReleaseBuffer(metabuf);
/* Unlock previous buffer */ /* Unlock rest */
UnlockReleaseBuffer(newbuf);
UnlockReleaseBuffer(buf); UnlockReleaseBuffer(buf);
/* Prepare new buffer */
state = GenericXLogStart(rel);
buf = newbuf;
page = GenericXLogRegisterBuffer(state, buf, 0);
break;
} }
} }
@@ -181,31 +156,36 @@ ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid,
#if PG_VERSION_NUM >= 140000 #if PG_VERSION_NUM >= 140000
,bool indexUnchanged ,bool indexUnchanged
#endif #endif
#if PG_VERSION_NUM >= 100000
,IndexInfo *indexInfo ,IndexInfo *indexInfo
#endif
) )
{ {
MemoryContext oldCtx; IndexTuple itup;
MemoryContext insertCtx; Datum value;
FmgrInfo *normprocinfo;
/* Skip nulls */
if (isnull[0]) if (isnull[0])
return false; return false;
/* value = values[0];
* Use memory context since detoast, IvfflatNormValue, and
* index_form_tuple can allocate
*/
insertCtx = AllocSetContextCreate(CurrentMemoryContext,
"Ivfflat insert temporary context",
ALLOCSET_DEFAULT_SIZES);
oldCtx = MemoryContextSwitchTo(insertCtx);
/* Insert tuple */ /* Normalize if needed */
InsertTuple(index, values, isnull, heap_tid, heap); normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
if (normprocinfo != NULL)
{
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, NULL))
return false;
}
/* Delete memory context */ itup = index_form_tuple(RelationGetDescr(index), &value, isnull);
MemoryContextSwitchTo(oldCtx); itup->t_tid = *heap_tid;
MemoryContextDelete(insertCtx); InsertTuple(index, itup, heap, &value);
pfree(itup);
/* Clean up if we allocated a new value */
if (value != values[0])
pfree(DatumGetPointer(value));
return false; return false;
} }

View File

@@ -5,11 +5,15 @@
#include "access/relscan.h" #include "access/relscan.h"
#include "ivfflat.h" #include "ivfflat.h"
#include "miscadmin.h" #include "miscadmin.h"
#include "pgstat.h"
#include "storage/bufmgr.h" #include "storage/bufmgr.h"
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_d.h" #include "catalog/pg_operator_d.h"
#include "catalog/pg_type_d.h" #include "catalog/pg_type_d.h"
#else
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#endif
/* /*
* Compare list distances * Compare list distances
@@ -26,21 +30,6 @@ CompareLists(const pairingheap_node *a, const pairingheap_node *b, void *arg)
return 0; return 0;
} }
/*
* Compare item distances
*/
static int
CompareItems(const pairingheap_node *a, const pairingheap_node *b, void *arg)
{
if (((const IvfflatScanItem *) a)->distance > ((const IvfflatScanItem *) b)->distance)
return 1;
if (((const IvfflatScanItem *) a)->distance < ((const IvfflatScanItem *) b)->distance)
return -1;
return 0;
}
/* /*
* Get lists and sort by distance * Get lists and sort by distance
*/ */
@@ -126,10 +115,12 @@ GetScanItems(IndexScanDesc scan, Datum value)
Datum datum; Datum datum;
bool isnull; bool isnull;
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation); TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
int i;
double distance; #if PG_VERSION_NUM >= 120000
IvfflatScanItem *scanitem; TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual);
double maxDistance = DBL_MAX; #else
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc);
#endif
/* /*
* Reuse same set of shared buffers for scan * Reuse same set of shared buffers for scan
@@ -155,40 +146,23 @@ GetScanItems(IndexScanDesc scan, Datum value)
{ {
itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno)); itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno));
datum = index_getattr(itup, 1, tupdesc, &isnull); datum = index_getattr(itup, 1, tupdesc, &isnull);
distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, datum, value));
if (so->itemCount < so->maxItems) /*
{ * Add virtual tuple
scanitem = &so->items[so->itemCount]; *
scanitem->searchPage = searchPage; * Use procinfo from the index instead of scan key for
scanitem->tid = itup->t_tid; * performance
scanitem->distance = distance; */
so->itemCount++; ExecClearTuple(slot);
slot->tts_values[0] = FunctionCall2Coll(so->procinfo, so->collation, datum, value);
slot->tts_isnull[0] = false;
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
slot->tts_isnull[1] = false;
slot->tts_values[2] = Int32GetDatum((int) searchPage);
slot->tts_isnull[2] = false;
ExecStoreVirtualTuple(slot);
/* Add to heap */ tuplesort_puttupleslot(so->sortstate, slot);
pairingheap_add(so->itemQueue, &scanitem->ph_node);
/* Calculate max distance */
if (so->itemCount == so->maxItems)
{
maxDistance = ((IvfflatScanItem *) pairingheap_first(so->itemQueue))->distance;
scanitem = &so->items[so->itemCount];
}
}
else if (distance < maxDistance)
{
/* Reuse */
scanitem->searchPage = searchPage;
scanitem->tid = itup->t_tid;
scanitem->distance = distance;
pairingheap_add(so->itemQueue, &scanitem->ph_node);
/* Remove */
scanitem = (IvfflatScanItem *) pairingheap_remove_first(so->itemQueue);
/* Update max distance */
maxDistance = ((IvfflatScanItem *) pairingheap_first(so->itemQueue))->distance;
}
} }
searchPage = IvfflatPageGetOpaque(page)->nextblkno; searchPage = IvfflatPageGetOpaque(page)->nextblkno;
@@ -197,10 +171,7 @@ GetScanItems(IndexScanDesc scan, Datum value)
} }
} }
for (i = 0; i < so->itemCount; i++) tuplesort_performsort(so->sortstate);
so->sortedItems[i] = (IvfflatScanItem *) pairingheap_remove_first(so->itemQueue);
Assert(pairingheap_is_empty(so->itemQueue));
} }
/* /*
@@ -212,6 +183,10 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
IndexScanDesc scan; IndexScanDesc scan;
IvfflatScanOpaque so; IvfflatScanOpaque so;
int lists; int lists;
AttrNumber attNums[] = {1};
Oid sortOperators[] = {Float8LessOperator};
Oid sortCollations[] = {InvalidOid};
bool nullsFirstFlags[] = {false};
int probes = ivfflat_probes; int probes = ivfflat_probes;
scan = RelationGetIndexScan(index, nkeys, norderbys); scan = RelationGetIndexScan(index, nkeys, norderbys);
@@ -230,13 +205,30 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC); so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
so->collation = index->rd_indcollation[0]; so->collation = index->rd_indcollation[0];
so->listQueue = pairingheap_allocate(CompareLists, scan); /* Create tuple description for sorting */
#if PG_VERSION_NUM >= 120000
so->tupdesc = CreateTemplateTupleDesc(3);
#else
so->tupdesc = CreateTemplateTupleDesc(3, false);
#endif
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
so->maxItems = 10; /* Prep sort */
so->itemCount = 0; #if PG_VERSION_NUM >= 110000
so->itemQueue = pairingheap_allocate(CompareItems, scan); so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
so->items = palloc(sizeof(IvfflatScanItem) * (so->maxItems + 1)); #else
so->sortedItems = palloc(sizeof(IvfflatScanItem *) * so->maxItems); so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, false);
#endif
#if PG_VERSION_NUM >= 120000
so->slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple);
#else
so->slot = MakeSingleTupleTableSlot(so->tupdesc);
#endif
so->listQueue = pairingheap_allocate(CompareLists, scan);
scan->opaque = so; scan->opaque = so;
@@ -251,10 +243,13 @@ ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int
{ {
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque; IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
#if PG_VERSION_NUM >= 130000
if (!so->first)
tuplesort_reset(so->sortstate);
#endif
so->first = true; so->first = true;
pairingheap_reset(so->listQueue); pairingheap_reset(so->listQueue);
pairingheap_reset(so->itemQueue);
so->itemCount = 0;
if (keys && scan->numberOfKeys > 0) if (keys && scan->numberOfKeys > 0)
memmove(scan->keyData, keys, scan->numberOfKeys * sizeof(ScanKeyData)); memmove(scan->keyData, keys, scan->numberOfKeys * sizeof(ScanKeyData));
@@ -281,9 +276,6 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
{ {
Datum value; Datum value;
/* Count index scan for stats */
pgstat_count_index_scan(scan->indexRelation);
/* Safety check */ /* Safety check */
if (scan->orderByData == NULL) if (scan->orderByData == NULL)
elog(ERROR, "cannot scan ivfflat index without order"); elog(ERROR, "cannot scan ivfflat index without order");
@@ -294,10 +286,6 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
value = scan->orderByData->sk_argument; value = scan->orderByData->sk_argument;
/* Value should not be compressed or toasted */
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
if (so->normprocinfo != NULL) if (so->normprocinfo != NULL)
{ {
/* No items will match if normalization fails */ /* No items will match if normalization fails */
@@ -314,18 +302,19 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
pfree(DatumGetPointer(value)); pfree(DatumGetPointer(value));
} }
if (so->itemCount > 0) #if PG_VERSION_NUM >= 100000
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL))
#else
if (tuplesort_gettupleslot(so->sortstate, true, so->slot, NULL))
#endif
{ {
IvfflatScanItem *scanitem; ItemPointer tid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
so->itemCount--;
scanitem = so->sortedItems[so->itemCount];
#if PG_VERSION_NUM >= 120000 #if PG_VERSION_NUM >= 120000
scan->xs_heaptid = scanitem->tid; scan->xs_heaptid = *tid;
#else #else
scan->xs_ctup.t_self = scanitem->tid; scan->xs_ctup.t_self = *tid;
#endif #endif
if (BufferIsValid(so->buf)) if (BufferIsValid(so->buf))
@@ -337,7 +326,7 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
* *
* https://www.postgresql.org/docs/current/index-locking.html * https://www.postgresql.org/docs/current/index-locking.html
*/ */
so->buf = ReadBuffer(scan->indexRelation, scanitem->searchPage); so->buf = ReadBuffer(scan->indexRelation, indexblkno);
scan->xs_recheckorderby = false; scan->xs_recheckorderby = false;
return true; return true;
@@ -359,10 +348,7 @@ ivfflatendscan(IndexScanDesc scan)
ReleaseBuffer(so->buf); ReleaseBuffer(so->buf);
pairingheap_free(so->listQueue); pairingheap_free(so->listQueue);
tuplesort_end(so->sortstate);
pairingheap_free(so->itemQueue);
pfree(so->items);
pfree(so->sortedItems);
pfree(so); pfree(so);
scan->opaque = NULL; scan->opaque = NULL;

View File

@@ -86,7 +86,7 @@ IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * resul
if (norm > 0) if (norm > 0)
{ {
v = DatumGetVector(*value); v = (Vector *) DatumGetPointer(*value);
if (result == NULL) if (result == NULL)
result = InitVector(v->dim); result = InitVector(v->dim);

View File

@@ -143,11 +143,6 @@ ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
{ {
Relation rel = info->index; Relation rel = info->index;
if (info->analyze_only)
return stats;
/* stats is NULL if ambulkdelete not called */
/* OK to return NULL if index not changed */
if (stats == NULL) if (stats == NULL)
return NULL; return NULL;

View File

@@ -20,13 +20,9 @@
#endif #endif
#if PG_VERSION_NUM < 130000 #if PG_VERSION_NUM < 130000
#define TYPALIGN_DOUBLE 'd'
#define TYPALIGN_INT 'i' #define TYPALIGN_INT 'i'
#endif #endif
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
PG_MODULE_MAGIC; PG_MODULE_MAGIC;
/* /*
@@ -86,30 +82,6 @@ CheckElement(float value)
errmsg("infinite value not allowed in vector"))); errmsg("infinite value not allowed in vector")));
} }
/*
* Check state array
*/
static float8 *
CheckStateArray(ArrayType *statearray, const char *caller)
{
if (ARR_NDIM(statearray) != 1 ||
ARR_DIMS(statearray)[0] < 1 ||
ARR_HASNULL(statearray) ||
ARR_ELEMTYPE(statearray) != FLOAT8OID)
elog(ERROR, "%s: expected state array", caller);
return (float8 *) ARR_DATA_PTR(statearray);
}
#if PG_VERSION_NUM < 120003
static pg_noinline void
float_overflow_error(void)
{
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("value out of range: overflow")));
}
#endif
/* /*
* Print vector - useful for debugging * Print vector - useful for debugging
*/ */
@@ -416,7 +388,7 @@ array_to_vector(PG_FUNCTION_ARGS)
else if (ARR_ELEMTYPE(array) == FLOAT4OID) else if (ARR_ELEMTYPE(array) == FLOAT4OID)
result->x[i] = DatumGetFloat4(elemsp[i]); result->x[i] = DatumGetFloat4(elemsp[i]);
else if (ARR_ELEMTYPE(array) == NUMERICOID) else if (ARR_ELEMTYPE(array) == NUMERICOID)
result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i])); result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(elemsp[i])));
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION), (errcode(ERRCODE_DATA_EXCEPTION),
@@ -467,7 +439,6 @@ l2_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
diff = ax[i] - bx[i]; diff = ax[i] - bx[i];
@@ -494,7 +465,6 @@ vector_l2_squared_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
diff = ax[i] - bx[i]; diff = ax[i] - bx[i];
@@ -519,7 +489,6 @@ inner_product(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -541,7 +510,6 @@ vector_negative_inner_product(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -565,7 +533,6 @@ cosine_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -573,8 +540,7 @@ cosine_distance(PG_FUNCTION_ARGS)
normb += bx[i] * bx[i]; normb += bx[i] * bx[i];
} }
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */ PG_RETURN_FLOAT8(1 - (distance / (sqrt(norma) * sqrt(normb))));
PG_RETURN_FLOAT8(1 - (distance / sqrt(norma * normb)));
} }
/* /*
@@ -592,7 +558,6 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += a->x[i] * b->x[i]; distance += a->x[i] * b->x[i];
@@ -628,7 +593,6 @@ vector_norm(PG_FUNCTION_ARGS)
float *ax = a->x; float *ax = a->x;
double norm = 0.0; double norm = 0.0;
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
norm += ax[i] * ax[i]; norm += ax[i] * ax[i];
@@ -653,8 +617,6 @@ vector_add(PG_FUNCTION_ARGS)
result = InitVector(a->dim); result = InitVector(a->dim);
rx = result->x; rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++) for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] + bx[i]; rx[i] = ax[i] + bx[i];
@@ -679,8 +641,6 @@ vector_sub(PG_FUNCTION_ARGS)
result = InitVector(a->dim); result = InitVector(a->dim);
rx = result->x; rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++) for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] - bx[i]; rx[i] = ax[i] - bx[i];
@@ -798,167 +758,3 @@ vector_cmp(PG_FUNCTION_ARGS)
PG_RETURN_INT32(vector_cmp_internal(a, b)); PG_RETURN_INT32(vector_cmp_internal(a, b));
} }
/*
* Accumulate vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_accum);
Datum
vector_accum(PG_FUNCTION_ARGS)
{
ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
Vector *newval = PG_GETARG_VECTOR_P(1);
float8 *statevalues;
int16 dim;
bool newarr;
float8 n;
Datum *statedatums;
float *x = newval->x;
ArrayType *result;
/* Check array before using */
statevalues = CheckStateArray(statearray, "vector_accum");
dim = STATE_DIMS(statearray);
newarr = dim == 0;
if (newarr)
dim = newval->dim;
else
CheckExpectedDim(dim, newval->dim);
n = statevalues[0] + 1.0;
statedatums = CreateStateDatums(dim);
statedatums[0] = Float8GetDatumFast(n);
if (newarr)
{
for (int i = 0; i < dim; i++)
statedatums[i + 1] = Float8GetDatumFast((double) x[i]);
}
else
{
for (int i = 0; i < dim; i++)
{
double v = statevalues[i + 1] + x[i];
if (isinf(v))
float_overflow_error();
statedatums[i + 1] = Float8GetDatumFast(v);
}
}
/* Use float8 array like float4_accum */
result = construct_array(statedatums, dim + 1,
FLOAT8OID,
sizeof(float8), FLOAT8PASSBYVAL, TYPALIGN_DOUBLE);
pfree(statedatums);
PG_RETURN_ARRAYTYPE_P(result);
}
/*
* Combine vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_combine);
Datum
vector_combine(PG_FUNCTION_ARGS)
{
ArrayType *statearray1 = PG_GETARG_ARRAYTYPE_P(0);
ArrayType *statearray2 = PG_GETARG_ARRAYTYPE_P(1);
float8 *statevalues1;
float8 *statevalues2;
float8 n;
float8 n1;
float8 n2;
int16 dim;
Datum *statedatums;
ArrayType *result;
/* Check arrays before using */
statevalues1 = CheckStateArray(statearray1, "vector_combine");
statevalues2 = CheckStateArray(statearray2, "vector_combine");
n1 = statevalues1[0];
n2 = statevalues2[0];
if (n1 == 0.0)
{
n = n2;
dim = STATE_DIMS(statearray2);
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
statedatums[i] = Float8GetDatumFast(statevalues2[i]);
}
else if (n2 == 0.0)
{
n = n1;
dim = STATE_DIMS(statearray1);
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
statedatums[i] = Float8GetDatumFast(statevalues1[i]);
}
else
{
n = n1 + n2;
dim = STATE_DIMS(statearray1);
CheckExpectedDim(dim, STATE_DIMS(statearray2));
statedatums = CreateStateDatums(dim);
for (int i = 1; i <= dim; i++)
{
double v = statevalues1[i] + statevalues2[i];
if (isinf(v))
float_overflow_error();
statedatums[i] = Float8GetDatumFast(v);
}
}
statedatums[0] = Float8GetDatumFast(n);
result = construct_array(statedatums, dim + 1,
FLOAT8OID,
sizeof(float8), FLOAT8PASSBYVAL, TYPALIGN_DOUBLE);
pfree(statedatums);
PG_RETURN_ARRAYTYPE_P(result);
}
/*
* Average vectors
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_avg);
Datum
vector_avg(PG_FUNCTION_ARGS)
{
ArrayType *statearray = PG_GETARG_ARRAYTYPE_P(0);
float8 *statevalues;
float8 n;
uint16 dim;
Vector *result;
float v;
/* Check array before using */
statevalues = CheckStateArray(statearray, "vector_avg");
n = statevalues[0];
/* SQL defines AVG of no values to be NULL */
if (n == 0.0)
PG_RETURN_NULL();
/* Create vector */
dim = STATE_DIMS(statearray);
result = InitVector(dim);
for (int i = 0; i < dim; i++)
{
v = statevalues[i + 1] / n;
CheckElement(v);
result->x[i] = v;
}
PG_RETURN_POINTER(result);
}

View File

@@ -3,11 +3,7 @@
#include "postgres.h" #include "postgres.h"
#if PG_VERSION_NUM >= 160000 #define VECTOR_MAX_DIM 1024
#include "varatt.h"
#endif
#define VECTOR_MAX_DIM 16000
#define VECTOR_SIZE(_dim) (offsetof(Vector, x) + sizeof(float)*(_dim)) #define VECTOR_SIZE(_dim) (offsetof(Vector, x) + sizeof(float)*(_dim))
#define DatumGetVector(x) ((Vector *) PG_DETOAST_DATUM(x)) #define DatumGetVector(x) ((Vector *) PG_DETOAST_DATUM(x))

View File

@@ -22,12 +22,6 @@ SELECT ARRAY[1,2,3]::float8[]::vector;
[1,2,3] [1,2,3]
(1 row) (1 row)
SELECT ARRAY[1,2,3]::numeric[]::vector;
array
---------
[1,2,3]
(1 row)
SELECT '{NULL}'::real[]::vector; SELECT '{NULL}'::real[]::vector;
ERROR: array must not containing NULLs ERROR: array must not containing NULLs
SELECT '{NaN}'::real[]::vector; SELECT '{NaN}'::real[]::vector;
@@ -44,8 +38,8 @@ SELECT '[1,2,3]'::vector::real[];
{1,2,3} {1,2,3}
(1 row) (1 row)
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n; SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
ERROR: vector cannot have more than 16000 dimensions ERROR: vector cannot have more than 1024 dimensions
-- ensure no error -- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3]; SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
?column? ?column?

View File

@@ -22,28 +22,10 @@ SELECT round(vector_norm('[1,1]')::numeric, 5);
1.41421 1.41421
(1 row) (1 row)
SELECT vector_norm('[3,4]'); SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5);
vector_norm round
------------- ---------
5 2.23607
(1 row)
SELECT vector_norm('[0,1]');
vector_norm
-------------
1
(1 row)
SELECT l2_distance('[0,0]', '[3,4]');
l2_distance
-------------
5
(1 row)
SELECT l2_distance('[0,0]', '[0,1]');
l2_distance
-------------
1
(1 row) (1 row)
SELECT l2_distance('[1,2]', '[3]'); SELECT l2_distance('[1,2]', '[3]');
@@ -56,10 +38,10 @@ SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]'); SELECT inner_product('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1 ERROR: different vector dimensions 2 and 1
SELECT cosine_distance('[1,2]', '[2,4]'); SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5);
cosine_distance round
----------------- ---------
0 0.00000
(1 row) (1 row)
SELECT cosine_distance('[1,2]', '[0,0]'); SELECT cosine_distance('[1,2]', '[0,0]');
@@ -68,37 +50,5 @@ SELECT cosine_distance('[1,2]', '[0,0]');
NaN NaN
(1 row) (1 row)
SELECT cosine_distance('[1,1]', '[1,1]');
cosine_distance
-----------------
0
(1 row)
SELECT cosine_distance('[1,1]', '[-1,-1]');
cosine_distance
-----------------
2
(1 row)
SELECT cosine_distance('[1,2]', '[3]'); SELECT cosine_distance('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1 ERROR: different vector dimensions 2 and 1
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
avg
-----------
[2,3.5,5]
(1 row)
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
avg
-----------
[2,3.5,5]
(1 row)
SELECT avg(v) FROM unnest(ARRAY[]::vector[]) v;
avg
-----
(1 row)
SELECT avg(v) FROM unnest(ARRAY['[1,2]'::vector, '[3]']) v;
ERROR: expected 2 dimensions, not 1

View File

@@ -2,14 +2,13 @@ SELECT ARRAY[1,2,3]::vector;
SELECT ARRAY[1.0,2.0,3.0]::vector; SELECT ARRAY[1.0,2.0,3.0]::vector;
SELECT ARRAY[1,2,3]::float4[]::vector; SELECT ARRAY[1,2,3]::float4[]::vector;
SELECT ARRAY[1,2,3]::float8[]::vector; SELECT ARRAY[1,2,3]::float8[]::vector;
SELECT ARRAY[1,2,3]::numeric[]::vector;
SELECT '{NULL}'::real[]::vector; SELECT '{NULL}'::real[]::vector;
SELECT '{NaN}'::real[]::vector; SELECT '{NaN}'::real[]::vector;
SELECT '{Infinity}'::real[]::vector; SELECT '{Infinity}'::real[]::vector;
SELECT '{-Infinity}'::real[]::vector; SELECT '{-Infinity}'::real[]::vector;
SELECT '{}'::real[]::vector; SELECT '{}'::real[]::vector;
SELECT '[1,2,3]'::vector::real[]; SELECT '[1,2,3]'::vector::real[];
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n; SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
-- ensure no error -- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3]; SELECT ARRAY[1,2,3] = ARRAY[1,2,3];

View File

@@ -2,25 +2,14 @@ SELECT '[1,2,3]'::vector + '[4,5,6]';
SELECT '[1,2,3]'::vector - '[4,5,6]'; SELECT '[1,2,3]'::vector - '[4,5,6]';
SELECT vector_dims('[1,2,3]'); SELECT vector_dims('[1,2,3]');
SELECT round(vector_norm('[1,1]')::numeric, 5); SELECT round(vector_norm('[1,1]')::numeric, 5);
SELECT vector_norm('[3,4]');
SELECT vector_norm('[0,1]');
SELECT l2_distance('[0,0]', '[3,4]'); SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5);
SELECT l2_distance('[0,0]', '[0,1]');
SELECT l2_distance('[1,2]', '[3]'); SELECT l2_distance('[1,2]', '[3]');
SELECT inner_product('[1,2]', '[3,4]'); SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]'); SELECT inner_product('[1,2]', '[3]');
SELECT cosine_distance('[1,2]', '[2,4]'); SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5);
SELECT cosine_distance('[1,2]', '[0,0]'); SELECT cosine_distance('[1,2]', '[0,0]');
SELECT cosine_distance('[1,1]', '[1,1]');
SELECT cosine_distance('[1,1]', '[-1,-1]');
SELECT cosine_distance('[1,2]', '[3]'); SELECT cosine_distance('[1,2]', '[3]');
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
SELECT avg(v) FROM unnest(ARRAY[]::vector[]) v;
SELECT avg(v) FROM unnest(ARRAY['[1,2]'::vector, '[3]']) v;

View File

@@ -20,8 +20,15 @@ sub test_index_replay
# Wait for replica to catch up # Wait for replica to catch up
my $applname = $node_replica->name; my $applname = $node_replica->name;
my $caughtup_query;
my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num"); my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';"; if ($server_version_num >= 100000) {
$caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
} else {
# TODO figure out why replay location doesn't work
$caughtup_query = "SELECT pg_current_xlog_location() <= write_location FROM pg_stat_replication WHERE application_name = '$applname';";
}
$node_primary->poll_query_until('postgres', $caughtup_query) $node_primary->poll_query_until('postgres', $caughtup_query)
or die "Timed out while waiting for replica 1 to catch up"; or die "Timed out while waiting for replica 1 to catch up";
@@ -56,9 +63,6 @@ if ($dim > 32) {
# TODO use wal_keep_segments for Postgres < 13 # TODO use wal_keep_segments for Postgres < 13
$node_primary->append_conf('postgresql.conf', qq(wal_keep_size = 1GB)); $node_primary->append_conf('postgresql.conf', qq(wal_keep_size = 1GB));
} }
if ($dim > 1500) {
$node_primary->append_conf('postgresql.conf', qq(maintenance_work_mem = 128MB));
}
$node_primary->start; $node_primary->start;
my $backup_name = 'my_backup'; my $backup_name = 'my_backup';

View File

@@ -4,15 +4,6 @@ use PostgresNode;
use TestLib; use TestLib;
use Test::More tests => 1; use Test::More tests => 1;
my $dim = 3;
my @r = ();
for (1 .. $dim) {
my $v = int(rand(1000)) + 1;
push(@r, "i % $v");
}
my $array_sql = join(", ", @r);
# Initialize node # Initialize node
my $node = get_new_node('node'); my $node = get_new_node('node');
$node->init; $node->init;
@@ -20,9 +11,9 @@ $node->start;
# Create table and index # Create table and index
$node->safe_psql("postgres", "CREATE EXTENSION vector;"); $node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));"); $node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;" "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);"); $node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
@@ -33,7 +24,7 @@ my $size = $node->safe_psql("postgres", "SELECT pg_total_relation_size('tst_v_id
$node->safe_psql("postgres", "DELETE FROM tst;"); $node->safe_psql("postgres", "DELETE FROM tst;");
$node->safe_psql("postgres", "VACUUM tst;"); $node->safe_psql("postgres", "VACUUM tst;");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;" "INSERT INTO tst SELECT i % 10, ARRAY[i % 1000, i % 333, i % 55] FROM generate_series(1, 100000) i;"
); );
# Check size # Check size

View File

@@ -2,7 +2,7 @@ use strict;
use warnings; use warnings;
use PostgresNode; use PostgresNode;
use TestLib; use TestLib;
use Test::More tests => 7; use Test::More tests => 5;
my $dim = 768; my $dim = 768;
@@ -32,19 +32,10 @@ $node->pgbench(
} }
); );
sub idx_scan
{
# Stats do not update instantaneously
# https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-VIEWS
sleep(1);
$node->safe_psql("postgres", "SELECT idx_scan FROM pg_stat_user_indexes WHERE indexrelid = 'tst_v_idx'::regclass;");
}
my $expected = 10000 + 5 * 100 * 10; my $expected = 10000 + 5 * 100 * 10;
my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;"); my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;");
is($count, $expected); is($count, $expected);
is(idx_scan(), 0);
$count = $node->safe_psql("postgres", qq( $count = $node->safe_psql("postgres", qq(
SET enable_seqscan = off; SET enable_seqscan = off;
@@ -52,4 +43,3 @@ $count = $node->safe_psql("postgres", qq(
SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t; SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t;
)); ));
is($count, $expected); is($count, $expected);
is(idx_scan(), 1);

View File

@@ -1,35 +0,0 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 5;
# Initialize node
my $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 (r1 real, r2 real, r3 real, v vector(3));");
$node->safe_psql("postgres", qq(
INSERT INTO tst SELECT r1, r2, r3, ARRAY[r1, r2, r3] FROM (
SELECT random() + 1.01 AS r1, random() + 2.01 AS r2, random() + 3.01 AS r3 FROM generate_series(1, 1000000) t
) i;
));
# Test avg
my $avg = $node->safe_psql("postgres", "SELECT AVG(v) FROM tst;");
like($avg, qr/\[1\.5/);
like($avg, qr/,2\.5/);
like($avg, qr/,3\.5/);
# Test matches real
my $r1 = $node->safe_psql("postgres", "SELECT AVG(r1)::float4 FROM tst;");
my $r2 = $node->safe_psql("postgres", "SELECT AVG(r2)::float4 FROM tst;");
my $r3 = $node->safe_psql("postgres", "SELECT AVG(r3)::float4 FROM tst;");
is($avg, "[$r1,$r2,$r3]");
# Test explain
my $explain = $node->safe_psql("postgres", "EXPLAIN SELECT AVG(v) FROM tst;");
like($explain, qr/Partial Aggregate/);

View File

@@ -1,32 +0,0 @@
use strict;
use warnings;
use PostgresNode;
use TestLib;
use Test::More tests => 1;
my $dim = 1024;
# Initialize node
my $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 (v1 vector(1024), v2 vector(1024), v3 vector(1024));");
# Test insert succeeds
$node->safe_psql("postgres",
"INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
);
# Change storage to PLAIN
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v1 SET STORAGE PLAIN");
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v2 SET STORAGE PLAIN");
$node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v3 SET STORAGE PLAIN");
# Test insert fails
my ($ret, $stdout, $stderr) = $node->psql("postgres",
"INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
);
like($stderr, qr/row is too big/);

View File

@@ -1,4 +1,4 @@
comment = 'vector data type and ivfflat access method' comment = 'vector data type and ivfflat access method'
default_version = '0.4.1' default_version = '0.3.2'
module_pathname = '$libdir/vector' module_pathname = '$libdir/vector'
relocatable = true relocatable = true