Compare commits

...

51 Commits

Author SHA1 Message Date
Andrew Kane
25d6747721 Version bump to 0.4.0 [skip ci] 2023-01-11 11:36:25 -08:00
Andrew Kane
fce99e0472 Updated readme and changelog for 0.4.0 [skip ci] 2023-01-11 11:34:28 -08:00
Andrew Kane
ec415bf5c4 Added upgrade instructions for 0.4.0 [skip ci] 2023-01-11 11:32:47 -08:00
Andrew Kane
0111ffffbd Updated readme for 0.4.0 [skip ci] 2023-01-11 11:32:21 -08:00
Andrew Kane
7d1398d1a7 Updated Azure link [skip ci] 2023-01-10 23:13:27 -08:00
Andrew Kane
b6f1a82774 Added assertions to scan [skip ci] 2023-01-10 21:07:19 -08:00
Andrew Kane
7b0b6a7875 Increased max dimensions for vector from 1024 to 16000 and increased max dimensions for index from 1024 to 2000 2023-01-10 14:49:50 -08:00
Andrew Kane
42d0cf1a25 Changed storage for existing installations [skip ci] 2023-01-10 11:34:43 -08:00
Andrew Kane
d164fd35a8 Made dimensions configurable for vacuum test 2023-01-10 03:14:49 -08:00
Andrew Kane
13e0fa24fe Use memory context for inserts 2023-01-10 02:53:58 -08:00
Andrew Kane
7c65fd13c1 Detoast once for all calls 2023-01-10 02:35:08 -08:00
Andrew Kane
9616a611c3 Added test for storage 2023-01-10 02:08:09 -08:00
Andrew Kane
474933ae39 Improved error message [skip ci] 2023-01-10 01:22:34 -08:00
Andrew Kane
b1237c7c4e Added separate dimensions limit for ivfflat indexes 2023-01-10 01:20:25 -08:00
Andrew Kane
66108cb406 Restored change to extended storage 2023-01-10 01:13:19 -08:00
Andrew Kane
8c3eb51ddc Added comment [skip ci] 2023-01-10 01:03:27 -08:00
Andrew Kane
915cf35e27 Use memory context for adding samples 2023-01-10 01:03:16 -08:00
Andrew Kane
ec800ef903 Use memory context for building index 2023-01-10 00:53:33 -08:00
Andrew Kane
4a2f20f5fc Reverted change to extended storage for now (causes high memory during distance calculation in BuildCallback) 2023-01-09 17:23:45 -08:00
Andrew Kane
e2b103a343 Updated version check [skip ci] 2023-01-09 15:54:44 -08:00
Andrew Kane
5d82d7bf99 Improved test [skip ci] 2022-12-30 19:30:17 -08:00
Andrew Kane
7c74d8ab75 Improved test [skip ci] 2022-12-30 19:29:19 -08:00
Andrew Kane
8dbd39f641 Improved test [skip ci] 2022-12-30 19:28:12 -08:00
Andrew Kane
d4681dd898 Simplified test 2022-12-30 19:25:40 -08:00
Andrew Kane
14984a08ea Improved avg test 2022-12-30 18:54:53 -08:00
Andrew Kane
30e07a6943 Updated readme [skip ci] 2022-12-30 18:34:51 -08:00
Andrew Kane
be26cf2f82 Updated readme [skip ci] 2022-12-30 18:29:22 -08:00
Andrew Kane
f205312430 Added float_overflow_error function for Postgres 11 2022-12-30 17:55:02 -08:00
Andrew Kane
085b75b727 Updated readme [skip ci] 2022-12-30 17:39:03 -08:00
Andrew Kane
3d8543f9ff Fixed include 2022-12-30 17:33:00 -08:00
Andrew Kane
8cbf0254bb Fixed TYPALIGN_DOUBLE error 2022-12-30 17:26:41 -08:00
Andrew Kane
e09f93cba7 Added avg aggregate for vector - closes #51 2022-12-30 17:22:25 -08:00
Andrew Kane
b400ac0f36 Insert before unlocking new buffer 2022-12-23 20:08:32 -08:00
Andrew Kane
aa62b42a9a Updated changelog [skip ci] 2022-12-23 19:19:15 -08:00
Andrew Kane
46b8294d5f Fixed script for Postgres < 13 [skip ci] 2022-12-23 19:16:44 -08:00
Andrew Kane
989b4c4208 Updated license year [skip ci] 2022-12-23 19:00:52 -08:00
Andrew Kane
fa491cd906 Changed storage for vector from plain to extended 2022-12-23 18:59:18 -08:00
Andrew Kane
00b767b107 Use DatumGetVector 2022-12-23 12:33:55 -08:00
Andrew Kane
1823024d9c Use consistent indentation [skip ci] 2022-12-23 12:04:52 -08:00
Andrew Kane
563f888ef1 Test with multiple versions of Ubuntu 2022-12-23 10:58:24 -08:00
Andrew Kane
141fea8d08 Use del on Windows 2022-12-23 10:54:34 -08:00
Andrew Kane
83407a9e23 Improved error handling on CI 2022-12-23 10:10:46 -08:00
Andrew Kane
0b1d36bb33 Added check for PGROOT 2022-12-23 09:46:07 -08:00
Andrew Kane
6d4ac36d50 Added uninstall task for Windows [skip ci] 2022-12-23 09:18:25 -08:00
Andrew Kane
e2f33dfdba Added clean task for Windows 2022-12-23 09:02:15 -08:00
Andrew Kane
3f3ba5b8e7 Set PROVE in Makefile if needed 2022-12-23 08:22:38 -08:00
Andrew Kane
0f69cc789a Combined sampling table and performing k-means phases 2022-12-23 08:07:09 -08:00
Andrew Kane
b09e14ce14 Dropped support for Postgres 10 2022-12-23 08:03:03 -08:00
Andrew Kane
1b5cb17f22 Removed code for Postgres < 10 2022-12-22 21:21:29 -08:00
Andrew Kane
7314d8b05a Improved CI [skip ci] 2022-12-09 01:56:00 -08:00
Andrew Kane
0a46adb112 Skip tests for certain branches [skip ci] 2022-12-09 01:48:38 -08:00
29 changed files with 584 additions and 163 deletions

View File

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

View File

@@ -2,11 +2,22 @@ name: build
on: [push, pull_request]
jobs:
ubuntu:
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
strategy:
fail-fast: false
matrix:
postgres: [15, 14, 13, 12, 11, 10]
include:
- 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-18.04
steps:
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
@@ -23,9 +34,10 @@ jobs:
- run: |
sudo apt-get update
sudo apt-get install libipc-run-perl
make prove_installcheck
- run: make prove_installcheck
mac:
runs-on: macos-latest
if: ${{ !startsWith(github.ref_name, 'windows') }}
steps:
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
@@ -38,20 +50,23 @@ jobs:
run: cat regression.diffs
- run: |
brew install cpanm
cpanm IPC::Run
cpanm --notest IPC::Run
wget -q https://github.com/postgres/postgres/archive/refs/tags/REL_14_5.tar.gz
tar xf REL_14_5.tar.gz
make prove_installcheck PROVE=prove PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres-REL_14_5/src/test/perl" PERL5LIB="/Users/runner/perl5/lib/perl5"
windows:
runs-on: windows-latest
if: ${{ !startsWith(github.ref_name, 'mac') }}
steps:
- uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1
with:
postgres-version: 14
- run: |
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat"
nmake /NOLOGO /F Makefile.win
nmake /NOLOGO /F Makefile.win install
nmake /NOLOGO /F Makefile.win installcheck
call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" && ^
nmake /NOLOGO /F Makefile.win && ^
nmake /NOLOGO /F Makefile.win install && ^
nmake /NOLOGO /F Makefile.win installcheck && ^
nmake /NOLOGO /F Makefile.win clean && ^
nmake /NOLOGO /F Makefile.win uninstall
shell: cmd

4
.gitignore vendored
View File

@@ -6,3 +6,7 @@ regression.*
*.o
*.so
*.bc
*.dll
*.obj
*.lib
*.exp

View File

@@ -1,8 +1,15 @@
## 0.4.0 (unreleased)
## 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 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
- Added `avg` aggregate for vector
- Added experimental support for Windows
- Dropped support for Postgres 10
## 0.3.2 (2022-11-22)

View File

@@ -1,4 +1,4 @@
Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California

View File

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

View File

@@ -1,5 +1,5 @@
EXTENSION = vector
EXTVERSION = 0.3.2
EXTVERSION = 0.4.0
MODULE_big = vector
DATA = $(wildcard sql/*--*.sql)
@@ -40,6 +40,11 @@ PG_CONFIG ?= pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
# for Mac
ifeq ($(PROVE),)
PROVE = prove
endif
# for Postgres 15
PROVE_FLAGS += -I ./test/perl

View File

@@ -1,5 +1,5 @@
EXTENSION = vector
EXTVERSION = 0.3.2
EXTVERSION = 0.4.0
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,6 +24,9 @@ sql\$(EXTENSION)--$(EXTVERSION).sql: sql\$(EXTENSION).sql
copy sql\$(EXTENSION).sql $@
# TODO use pg_config
!ifndef PGROOT
!error PGROOT is not set
!endif
BINDIR = $(PGROOT)\bin
INCLUDEDIR = $(PGROOT)\include
INCLUDEDIR_SERVER = $(PGROOT)\include\server
@@ -35,7 +38,7 @@ CFLAGS = /nologo /I"$(INCLUDEDIR_SERVER)\port\win32_msvc" /I"$(INCLUDEDIR_SERVER
CFLAGS = $(CFLAGS) $(PG_CFLAGS)
SHLIB = src\$(EXTENSION).dll
SHLIB = $(EXTENSION).dll
LIBS = "$(LIBDIR)\postgres.lib"
@@ -54,3 +57,14 @@ install:
installcheck:
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
uninstall:
del /f "$(PKGLIBDIR)\$(SHLIB)"
del /f "$(SHAREDIR)\extension\$(EXTENSION).control"
del /f "$(SHAREDIR)\extension\vector--*.sql"
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

View File

@@ -14,10 +14,10 @@ Supports L2 distance, inner product, and cosine distance
## Installation
Compile and install the extension (supports Postgres 10+)
Compile and install the extension (supports Postgres 11+)
```sh
git clone --branch v0.3.2 https://github.com/pgvector/pgvector.git
git clone --branch v0.4.0 https://github.com/pgvector/pgvector.git
cd pgvector
make
make install # may need sudo
@@ -77,7 +77,7 @@ Cosine distance
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops);
```
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.
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. Vectors with up to 2,000 dimensions can be indexed.
### Index Options
@@ -119,10 +119,9 @@ 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`
2. `performing k-means`
3. `sorting tuples`
4. `loading tuples`
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
@@ -164,7 +163,7 @@ CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000
### 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 1024 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 16,000 dimensions.
### Vector Operators
@@ -180,11 +179,17 @@ Operator | Description
Function | Description
--- | ---
cosine_distance(vector, vector) | cosine distance
inner_product(vector, vector) | inner product
l2_distance(vector, vector) | Euclidean distance
vector_dims(vector) | number of dimensions
vector_norm(vector) | Euclidean norm
cosine_distance(vector, vector) → double precision | cosine distance
inner_product(vector, vector) → double precision | inner product
l2_distance(vector, vector) → double precision | Euclidean distance
vector_dims(vector) → integer | number of dimensions
vector_norm(vector) → double precision | Euclidean norm
### Aggregate Functions
Function | Description | Partial Mode
--- | --- | ---
avg(vector) → vector | arithmetic mean | Yes
## Libraries
@@ -210,12 +215,12 @@ A non-partitioned table has a limit of 32 TB by default in Postgres. A partition
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?
#### 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/vector.h`
2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/ivfflat.h`
## Additional Installation Methods
@@ -232,7 +237,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.3.2 https://github.com/pgvector/pgvector.git
git clone --branch v0.4.0 https://github.com/pgvector/pgvector.git
cd pgvector
docker build -t pgvector .
```
@@ -260,7 +265,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 - 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)
- Azure Database for PostgreSQL - vote or comment on [this page](https://feedback.azure.com/d365community/idea/7b423322-6189-ed11-a81b-000d3ae49307)
## Upgrading
@@ -272,6 +277,16 @@ ALTER EXTENSION vector UPDATE;
## Upgrade Notes
### 0.4.0
For 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
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);
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)
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)
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)
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;

View File

@@ -0,0 +1,23 @@
-- 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

@@ -25,7 +25,8 @@ CREATE TYPE vector (
OUTPUT = vector_out,
TYPMOD_IN = vector_typmod_in,
RECEIVE = vector_recv,
SEND = vector_send
SEND = vector_send,
STORAGE = extended
);
-- functions
@@ -83,6 +84,26 @@ CREATE FUNCTION vector_negative_inner_product(vector, vector) RETURNS float8
CREATE FUNCTION vector_spherical_distance(vector, vector) RETURNS float8
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
CREATE FUNCTION vector(vector, integer, boolean) RETURNS vector

View File

@@ -6,6 +6,7 @@
#include "ivfflat.h"
#include "miscadmin.h"
#include "storage/bufmgr.h"
#include "utils/memutils.h"
#if PG_VERSION_NUM >= 140000
#include "utils/backend_progress.h"
@@ -22,13 +23,8 @@
#define PROGRESS_CREATEIDX_TUPLES_DONE 0
#endif
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_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
#define CALLBACK_ITEM_POINTER ItemPointer tid
@@ -43,20 +39,16 @@
#endif
/*
* Callback for sampling
* Add sample
*/
static void
SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
AddSample(Datum *values, IvfflatBuildState * buildstate)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
VectorArray samples = buildstate->samples;
int targsamples = samples->maxlen;
Datum value = values[0];
/* Skip nulls */
if (isnull[0])
return;
/* Detoast once for all calls */
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/*
* Normalize with KMEANS_NORM_PROC since spherical distance function
@@ -94,6 +86,31 @@ SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
}
}
/*
* 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
*/
@@ -103,8 +120,6 @@ 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, RandomInt());
@@ -117,38 +132,28 @@ SampleRows(IvfflatBuildState * buildstate)
#if PG_VERSION_NUM >= 120000
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#elif PG_VERSION_NUM >= 110000
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#else
IndexBuildHeapRangeScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
false, true, targblock, 1, SampleCallback, (void *) buildstate);
false, true, targblock, 1, SampleCallback, (void *) buildstate, NULL);
#endif
}
}
/*
* Callback for table_index_build_scan
* Add tuple to sort
*/
static void
BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
bool *isnull, bool tupleIsAlive, void *state)
AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState * buildstate)
{
IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
double distance;
double minDistance = DBL_MAX;
int closestCenter = -1;
VectorArray centers = buildstate->centers;
TupleTableSlot *slot = buildstate->slot;
Datum value = values[0];
int i;
#if PG_VERSION_NUM < 130000
ItemPointer tid = &hup->t_self;
#endif
if (isnull[0])
return;
/* Detoast once for all calls */
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
/* Normalize if needed */
if (buildstate->normprocinfo != NULL)
@@ -196,6 +201,35 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
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
*/
@@ -205,11 +239,7 @@ GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot,
Datum value;
bool isnull;
#if PG_VERSION_NUM >= 100000
if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL))
#else
if (tuplesort_gettupleslot(sortstate, true, slot, NULL))
#endif
{
*list = DatumGetInt32(slot_getattr(slot, 1, &isnull));
value = slot_getattr(slot, 3, &isnull);
@@ -308,6 +338,9 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
if (buildstate->dimensions < 0)
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->indtuples = 0;
@@ -331,11 +364,7 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
#endif
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 1, "list", INT4OID, -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);
#else
TupleDescInitEntry(buildstate->tupdesc, (AttrNumber) 3, "vector", RelationGetDescr(index)->attrs[0]->atttypid, -1, 0);
#endif
#if PG_VERSION_NUM >= 120000
buildstate->slot = MakeSingleTupleTableSlot(buildstate->tupdesc, &TTSOpsVirtual);
@@ -349,6 +378,10 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
/* Reuse for each tuple */
buildstate->normvec = InitVector(buildstate->dimensions);
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
"Ivfflat build temporary context",
ALLOCSET_DEFAULT_SIZES);
#ifdef IVFFLAT_KMEANS_DEBUG
buildstate->inertia = 0;
buildstate->listSums = palloc0(sizeof(double) * buildstate->lists);
@@ -370,6 +403,8 @@ FreeBuildState(IvfflatBuildState * buildstate)
pfree(buildstate->listSums);
pfree(buildstate->listCounts);
#endif
MemoryContextDelete(buildstate->tmpCtx);
}
/*
@@ -380,6 +415,8 @@ ComputeCenters(IvfflatBuildState * buildstate)
{
int numSamples;
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
/* Target 50 samples per list, with at least 10000 samples */
/* The number of samples has a large effect on index build time */
numSamples = buildstate->lists * 50;
@@ -397,7 +434,6 @@ ComputeCenters(IvfflatBuildState * buildstate)
SampleRows(buildstate);
/* Calculate 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 */
@@ -535,11 +571,7 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
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
buildstate->sortstate = tuplesort_begin_heap(buildstate->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, maintenance_work_mem, false);
#endif
/* Add tuples to sort */
if (buildstate->heap != NULL)
@@ -547,12 +579,9 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
#if PG_VERSION_NUM >= 120000
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, true, BuildCallback, (void *) buildstate, NULL);
#elif PG_VERSION_NUM >= 110000
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate, NULL);
#else
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
true, BuildCallback, (void *) buildstate);
true, BuildCallback, (void *) buildstate, NULL);
#endif
}

View File

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

View File

@@ -3,8 +3,8 @@
#include "postgres.h"
#if PG_VERSION_NUM < 100000
#error "Requires PostgreSQL 10+"
#if PG_VERSION_NUM < 110000
#error "Requires PostgreSQL 11+"
#endif
#include "access/generic_xlog.h"
@@ -23,6 +23,8 @@
#include "portability/instr_time.h"
#endif
#define IVFFLAT_MAX_DIM 2000
/* Support functions */
#define IVFFLAT_DISTANCE_PROC 1
#define IVFFLAT_NORM_PROC 2
@@ -42,10 +44,9 @@
/* 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 PROGRESS_IVFFLAT_PHASE_KMEANS 2
#define PROGRESS_IVFFLAT_PHASE_SORT 3
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
@@ -146,6 +147,9 @@ typedef struct IvfflatBuildState
Tuplesortstate *sortstate;
TupleDesc tupdesc;
TupleTableSlot *slot;
/* Memory */
MemoryContext tmpCtx;
} IvfflatBuildState;
typedef struct IvfflatMetaPageData
@@ -234,9 +238,7 @@ bool ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer hea
#if PG_VERSION_NUM >= 140000
,bool indexUnchanged
#endif
#if PG_VERSION_NUM >= 100000
,IndexInfo *indexInfo
#endif
);
IndexBulkDeleteResult *ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
IndexBulkDeleteResult *ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats);

View File

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

View File

@@ -7,13 +7,8 @@
#include "miscadmin.h"
#include "storage/bufmgr.h"
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_operator_d.h"
#include "catalog/pg_type_d.h"
#else
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#endif
/*
* Compare list distances
@@ -216,11 +211,7 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
/* Prep sort */
#if PG_VERSION_NUM >= 110000
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
#else
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);
@@ -286,6 +277,10 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
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)
{
/* No items will match if normalization fails */
@@ -302,11 +297,7 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
pfree(DatumGetPointer(value));
}
#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
{
ItemPointer tid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));

View File

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

View File

@@ -20,9 +20,13 @@
#endif
#if PG_VERSION_NUM < 130000
#define TYPALIGN_DOUBLE 'd'
#define TYPALIGN_INT 'i'
#endif
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
PG_MODULE_MAGIC;
/*
@@ -82,6 +86,30 @@ CheckElement(float value)
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 < 120000
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
*/
@@ -758,3 +786,167 @@ vector_cmp(PG_FUNCTION_ARGS)
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(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,7 +3,7 @@
#include "postgres.h"
#define VECTOR_MAX_DIM 1024
#define VECTOR_MAX_DIM 16000
#define VECTOR_SIZE(_dim) (offsetof(Vector, x) + sizeof(float)*(_dim))
#define DatumGetVector(x) ((Vector *) PG_DETOAST_DATUM(x))

View File

@@ -38,8 +38,8 @@ SELECT '[1,2,3]'::vector::real[];
{1,2,3}
(1 row)
SELECT array_agg(n)::vector FROM generate_series(1, 1025) n;
ERROR: vector cannot have more than 1024 dimensions
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
?column?

View File

@@ -52,3 +52,23 @@ SELECT cosine_distance('[1,2]', '[0,0]');
SELECT cosine_distance('[1,2]', '[3]');
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

@@ -8,7 +8,7 @@ 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;
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];

View File

@@ -13,3 +13,8 @@ SELECT inner_product('[1,2]', '[3]');
SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5);
SELECT cosine_distance('[1,2]', '[0,0]');
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,15 +20,8 @@ sub test_index_replay
# Wait for replica to catch up
my $applname = $node_replica->name;
my $caughtup_query;
my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
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';";
}
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
$node_primary->poll_query_until('postgres', $caughtup_query)
or die "Timed out while waiting for replica 1 to catch up";
@@ -63,6 +56,9 @@ if ($dim > 32) {
# TODO use wal_keep_segments for Postgres < 13
$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;
my $backup_name = 'my_backup';

View File

@@ -4,6 +4,15 @@ use PostgresNode;
use TestLib;
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
my $node = get_new_node('node');
$node->init;
@@ -11,9 +20,9 @@ $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", "CREATE TABLE tst (i int4, v vector($dim));");
$node->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, ARRAY[i % 1000, i % 333, i % 55] FROM generate_series(1, 100000) i;"
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
);
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
@@ -24,7 +33,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", "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;"
"INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
);
# Check size

35
test/t/008_avg.pl Normal file
View File

@@ -0,0 +1,35 @@
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/);

32
test/t/009_storage.pl Normal file
View File

@@ -0,0 +1,32 @@
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'
default_version = '0.3.2'
default_version = '0.4.0'
module_pathname = '$libdir/vector'
relocatable = true