mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22a4ed0302 | ||
|
|
cbcbebe52e | ||
|
|
5da3bdf98e | ||
|
|
0d82124bca | ||
|
|
2c48e3edc2 | ||
|
|
7d63bb4b98 | ||
|
|
de410a2915 | ||
|
|
64aa99aa31 | ||
|
|
997fa167da | ||
|
|
67eec4edbf | ||
|
|
396090d8e0 | ||
|
|
ba18942fcf | ||
|
|
8e59455c3c | ||
|
|
bd50e3067d | ||
|
|
af9d4ad659 | ||
|
|
08abb63cbe | ||
|
|
06b8556a49 | ||
|
|
3f674c9994 |
@@ -1,9 +1,6 @@
|
|||||||
## 0.7.0 (unreleased)
|
## 0.7.0 (unreleased)
|
||||||
|
|
||||||
- Added support for binary vectors to HNSW
|
- Added `intvec` type
|
||||||
- Added `hamming_distance` function
|
|
||||||
- Added `jaccard_distance` function
|
|
||||||
- Added `quantize_binary` function
|
|
||||||
|
|
||||||
## 0.6.2 (2024-03-18)
|
## 0.6.2 (2024-03-18)
|
||||||
|
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -3,8 +3,8 @@ EXTVERSION = 0.6.2
|
|||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
OBJS = src/bitvector.o src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/vector.o
|
OBJS = src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/intvec.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/vector.o
|
||||||
HEADERS = src/vector.h
|
HEADERS = src/intvec.h src/vector.h
|
||||||
|
|
||||||
TESTS = $(wildcard test/sql/*.sql)
|
TESTS = $(wildcard test/sql/*.sql)
|
||||||
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.6.2
|
EXTVERSION = 0.6.2
|
||||||
|
|
||||||
OBJS = src\bitvector.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
|
OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\intvec.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
|
||||||
HEADERS = src\vector.h
|
HEADERS = src\intvec.h src\vector.h
|
||||||
|
|
||||||
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
|
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
|
||||||
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
||||||
|
|||||||
58
README.md
58
README.md
@@ -5,7 +5,7 @@ Open-source vector similarity search for Postgres
|
|||||||
Store your vectors with the rest of your data. Supports:
|
Store your vectors with the rest of your data. Supports:
|
||||||
|
|
||||||
- exact and approximate nearest neighbor search
|
- exact and approximate nearest neighbor search
|
||||||
- L2 distance, inner product, cosine distance, and more
|
- L2 distance, inner product, and cosine distance
|
||||||
- any [language](#languages) with a Postgres client
|
- any [language](#languages) with a Postgres client
|
||||||
|
|
||||||
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
||||||
@@ -221,19 +221,7 @@ Cosine distance
|
|||||||
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
|
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
|
||||||
```
|
```
|
||||||
|
|
||||||
Hamming distance - added in 0.7.0
|
Vectors with up to 2,000 dimensions can be indexed.
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding bit_hamming_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
Jaccard distance - added in 0.7.0
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding bit_jaccard_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
Vectors with up to 2,000 dimensions can be indexed, or bit vectors with up to 64,000 dimensions.
|
|
||||||
|
|
||||||
### Index Options
|
### Index Options
|
||||||
|
|
||||||
@@ -427,7 +415,19 @@ You can use [Reciprocal Rank Fusion](https://github.com/pgvector/pgvector-python
|
|||||||
|
|
||||||
### Tuning
|
### Tuning
|
||||||
|
|
||||||
Use a tool like [PgTune](https://pgtune.leopard.in.ua/) to set initial values for Postgres server parameters.
|
Use a tool like [PgTune](https://pgtune.leopard.in.ua/) to set initial values for Postgres server parameters. For instance, `shared_buffers` should typically be 25% of the server’s memory. You can find the config file with:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SHOW config_file;
|
||||||
|
```
|
||||||
|
|
||||||
|
And check individual settings with:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SHOW shared_buffers;
|
||||||
|
```
|
||||||
|
|
||||||
|
Be sure to restart Postgres for changes to take effect.
|
||||||
|
|
||||||
### Loading
|
### Loading
|
||||||
|
|
||||||
@@ -683,6 +683,8 @@ ALTER TABLE items ALTER COLUMN embedding SET STORAGE PLAIN;
|
|||||||
|
|
||||||
Results are limited by the size of the dynamic candidate list (`hnsw.ef_search`). There may be even less results due to dead tuples or filtering conditions in the query. We recommend setting `hnsw.ef_search` to at least twice the `LIMIT` of the query. If you need more than 500 results, use an IVFFlat index instead.
|
Results are limited by the size of the dynamic candidate list (`hnsw.ef_search`). There may be even less results due to dead tuples or filtering conditions in the query. We recommend setting `hnsw.ef_search` to at least twice the `LIMIT` of the query. If you need more than 500 results, use an IVFFlat index instead.
|
||||||
|
|
||||||
|
Also, note that `NULL` vectors are not indexed (as well as zero vectors for cosine distance).
|
||||||
|
|
||||||
#### Why are there less results for a query after adding an IVFFlat index?
|
#### Why are there less results for a query after adding an IVFFlat index?
|
||||||
|
|
||||||
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
|
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
|
||||||
@@ -693,11 +695,13 @@ DROP INDEX index_name;
|
|||||||
|
|
||||||
Results can also be limited by the number of probes (`ivfflat.probes`).
|
Results can also be limited by the number of probes (`ivfflat.probes`).
|
||||||
|
|
||||||
|
Also, note that `NULL` vectors are not indexed (as well as zero vectors for cosine distance).
|
||||||
|
|
||||||
## 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 16,000 dimensions.
|
||||||
|
|
||||||
### Vector Operators
|
### Vector Operators
|
||||||
|
|
||||||
@@ -718,30 +722,36 @@ cosine_distance(vector, vector) → double precision | cosine distance |
|
|||||||
inner_product(vector, vector) → double precision | inner product |
|
inner_product(vector, vector) → double precision | inner product |
|
||||||
l2_distance(vector, vector) → double precision | Euclidean distance |
|
l2_distance(vector, vector) → double precision | Euclidean distance |
|
||||||
l1_distance(vector, vector) → double precision | taxicab distance | 0.5.0
|
l1_distance(vector, vector) → double precision | taxicab distance | 0.5.0
|
||||||
quantize_binary(vector) → bit | quantize | 0.7.0
|
|
||||||
vector_dims(vector) → integer | number of dimensions |
|
vector_dims(vector) → integer | number of dimensions |
|
||||||
vector_norm(vector) → double precision | Euclidean norm |
|
vector_norm(vector) → double precision | Euclidean norm |
|
||||||
|
|
||||||
### Aggregate Functions
|
### Vector Aggregate Functions
|
||||||
|
|
||||||
Function | Description | Added
|
Function | Description | Added
|
||||||
--- | --- | ---
|
--- | --- | ---
|
||||||
avg(vector) → vector | average |
|
avg(vector) → vector | average |
|
||||||
sum(vector) → vector | sum | 0.5.0
|
sum(vector) → vector | sum | 0.5.0
|
||||||
|
|
||||||
### Bit Operators
|
### Intvec Type
|
||||||
|
|
||||||
|
Each int vector takes `dimensions + 8` bytes of storage. Each element is a single byte signed integer. Int vectors can have up to 16,000 dimensions.
|
||||||
|
|
||||||
|
### Intvec Operators
|
||||||
|
|
||||||
Operator | Description | Added
|
Operator | Description | Added
|
||||||
--- | --- | ---
|
--- | --- | ---
|
||||||
<~> | Hamming distance | 0.7.0
|
<-> | Euclidean distance | 0.7.0
|
||||||
<%> | Jaccard distance | 0.7.0
|
<#> | negative inner product | 0.7.0
|
||||||
|
<=> | cosine distance | 0.7.0
|
||||||
|
|
||||||
### Bit Functions
|
### Intvec Functions
|
||||||
|
|
||||||
Function | Description | Added
|
Function | Description | Added
|
||||||
--- | --- | ---
|
--- | --- | ---
|
||||||
hamming_distance(bit, bit) → double precision | Hamming distance | 0.7.0
|
cosine_distance(intvec, intvec) → double precision | cosine distance | 0.7.0
|
||||||
jaccard_distance(bit, bit) → double precision | Jaccard distance | 0.7.0
|
inner_product(intvec, intvec) → double precision | inner product | 0.7.0
|
||||||
|
l2_distance(intvec, intvec) → double precision | Euclidean distance | 0.7.0
|
||||||
|
l1_distance(intvec, intvec) → double precision | taxicab distance | 0.7.0
|
||||||
|
|
||||||
## Installation Notes - Linux and Mac
|
## Installation Notes - Linux and Mac
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,92 @@
|
|||||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.7.0'" to load this file. \quit
|
\echo Use "ALTER EXTENSION vector UPDATE TO '0.7.0'" to load this file. \quit
|
||||||
|
|
||||||
CREATE FUNCTION quantize_binary(vector) RETURNS bit
|
CREATE TYPE intvec;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_in(cstring, oid, integer) RETURNS intvec
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION hamming_distance(bit, bit) RETURNS float8
|
CREATE FUNCTION intvec_out(intvec) RETURNS cstring
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION jaccard_distance(bit, bit) RETURNS float8
|
CREATE FUNCTION intvec_typmod_in(cstring[]) RETURNS integer
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE OPERATOR <~> (
|
CREATE FUNCTION intvec_recv(internal, oid, integer) RETURNS intvec
|
||||||
LEFTARG = bit, RIGHTARG = bit, PROCEDURE = hamming_distance,
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
COMMUTATOR = '<~>'
|
|
||||||
|
CREATE FUNCTION intvec_send(intvec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE intvec (
|
||||||
|
INPUT = intvec_in,
|
||||||
|
OUTPUT = intvec_out,
|
||||||
|
TYPMOD_IN = intvec_typmod_in,
|
||||||
|
RECEIVE = intvec_recv,
|
||||||
|
SEND = intvec_send,
|
||||||
|
STORAGE = external
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR <%> (
|
CREATE FUNCTION l2_distance(intvec, intvec) RETURNS float8
|
||||||
LEFTARG = bit, RIGHTARG = bit, PROCEDURE = jaccard_distance,
|
AS 'MODULE_PATHNAME', 'intvec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
COMMUTATOR = '<%>'
|
|
||||||
|
CREATE FUNCTION inner_product(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l1_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_norm(intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_l2_norm' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_l2_squared_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_negative_inner_product(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec(intvec, integer, boolean) RETURNS intvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_intvec(integer[], integer, boolean) RETURNS intvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE CAST (intvec AS intvec)
|
||||||
|
WITH FUNCTION intvec(intvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (integer[] AS intvec)
|
||||||
|
WITH FUNCTION array_to_intvec(integer[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR CLASS bit_hamming_ops
|
CREATE OPERATOR <#> (
|
||||||
FOR TYPE bit USING hnsw AS
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = intvec_negative_inner_product,
|
||||||
OPERATOR 1 <~> (bit, bit) FOR ORDER BY float_ops,
|
COMMUTATOR = '<#>'
|
||||||
FUNCTION 1 hamming_distance(bit, bit);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR CLASS bit_jaccard_ops
|
CREATE OPERATOR <=> (
|
||||||
FOR TYPE bit USING hnsw AS
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = cosine_distance,
|
||||||
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
COMMUTATOR = '<=>'
|
||||||
FUNCTION 1 jaccard_distance(bit, bit);
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_l2_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 intvec_l2_squared_distance(intvec, intvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_ip_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 intvec_negative_inner_product(intvec, intvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_cosine_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 cosine_distance(intvec, intvec),
|
||||||
|
FUNCTION 2 l2_norm(intvec);
|
||||||
|
|||||||
113
sql/vector.sql
113
sql/vector.sql
@@ -58,9 +58,6 @@ CREATE FUNCTION vector_sub(vector, vector) RETURNS vector
|
|||||||
CREATE FUNCTION vector_mul(vector, vector) RETURNS vector
|
CREATE FUNCTION vector_mul(vector, vector) RETURNS vector
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION quantize_binary(vector) RETURNS bit
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
-- private functions
|
-- private functions
|
||||||
|
|
||||||
CREATE FUNCTION vector_lt(vector, vector) RETURNS bool
|
CREATE FUNCTION vector_lt(vector, vector) RETURNS bool
|
||||||
@@ -291,30 +288,106 @@ CREATE OPERATOR CLASS vector_cosine_ops
|
|||||||
FUNCTION 1 vector_negative_inner_product(vector, vector),
|
FUNCTION 1 vector_negative_inner_product(vector, vector),
|
||||||
FUNCTION 2 vector_norm(vector);
|
FUNCTION 2 vector_norm(vector);
|
||||||
|
|
||||||
-- bit functions
|
-- intvec type
|
||||||
|
|
||||||
CREATE FUNCTION hamming_distance(bit, bit) RETURNS float8
|
CREATE TYPE intvec;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_in(cstring, oid, integer) RETURNS intvec
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION jaccard_distance(bit, bit) RETURNS float8
|
CREATE FUNCTION intvec_out(intvec) RETURNS cstring
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE OPERATOR <~> (
|
CREATE FUNCTION intvec_typmod_in(cstring[]) RETURNS integer
|
||||||
LEFTARG = bit, RIGHTARG = bit, PROCEDURE = hamming_distance,
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
COMMUTATOR = '<~>'
|
|
||||||
|
CREATE FUNCTION intvec_recv(internal, oid, integer) RETURNS intvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_send(intvec) RETURNS bytea
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE TYPE intvec (
|
||||||
|
INPUT = intvec_in,
|
||||||
|
OUTPUT = intvec_out,
|
||||||
|
TYPMOD_IN = intvec_typmod_in,
|
||||||
|
RECEIVE = intvec_recv,
|
||||||
|
SEND = intvec_send,
|
||||||
|
STORAGE = external
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR <%> (
|
-- intvec functions
|
||||||
LEFTARG = bit, RIGHTARG = bit, PROCEDURE = jaccard_distance,
|
|
||||||
COMMUTATOR = '<%>'
|
CREATE FUNCTION l2_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION inner_product(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION cosine_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l1_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_l1_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_norm(intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'intvec_l2_norm' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- intvec private functions
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_l2_squared_distance(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec_negative_inner_product(intvec, intvec) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- intvec cast functions
|
||||||
|
|
||||||
|
CREATE FUNCTION intvec(intvec, integer, boolean) RETURNS intvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION array_to_intvec(integer[], integer, boolean) RETURNS intvec
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
-- intvec casts
|
||||||
|
|
||||||
|
CREATE CAST (intvec AS intvec)
|
||||||
|
WITH FUNCTION intvec(intvec, integer, boolean) AS IMPLICIT;
|
||||||
|
|
||||||
|
CREATE CAST (integer[] AS intvec)
|
||||||
|
WITH FUNCTION array_to_intvec(integer[], integer, boolean) AS ASSIGNMENT;
|
||||||
|
|
||||||
|
-- intvec operators
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR CLASS bit_hamming_ops
|
CREATE OPERATOR <#> (
|
||||||
FOR TYPE bit USING hnsw AS
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = intvec_negative_inner_product,
|
||||||
OPERATOR 1 <~> (bit, bit) FOR ORDER BY float_ops,
|
COMMUTATOR = '<#>'
|
||||||
FUNCTION 1 hamming_distance(bit, bit);
|
);
|
||||||
|
|
||||||
CREATE OPERATOR CLASS bit_jaccard_ops
|
CREATE OPERATOR <=> (
|
||||||
FOR TYPE bit USING hnsw AS
|
LEFTARG = intvec, RIGHTARG = intvec, PROCEDURE = cosine_distance,
|
||||||
OPERATOR 1 <%> (bit, bit) FOR ORDER BY float_ops,
|
COMMUTATOR = '<=>'
|
||||||
FUNCTION 1 jaccard_distance(bit, bit);
|
);
|
||||||
|
|
||||||
|
-- intvec opclasses
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_l2_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 intvec_l2_squared_distance(intvec, intvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_ip_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <#> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 intvec_negative_inner_product(intvec, intvec);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS intvec_cosine_ops
|
||||||
|
FOR TYPE intvec USING hnsw AS
|
||||||
|
OPERATOR 1 <=> (intvec, intvec) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 cosine_distance(intvec, intvec),
|
||||||
|
FUNCTION 2 l2_norm(intvec);
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
#include "postgres.h"
|
|
||||||
|
|
||||||
#include "bitvector.h"
|
|
||||||
#include "port/pg_bitutils.h"
|
|
||||||
#include "utils/varbit.h"
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 160000
|
|
||||||
#include "varatt.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Allocate and initialize a new bit vector
|
|
||||||
*/
|
|
||||||
VarBit *
|
|
||||||
InitBitVector(int dim)
|
|
||||||
{
|
|
||||||
VarBit *result;
|
|
||||||
int size;
|
|
||||||
|
|
||||||
size = VARBITTOTALLEN(dim);
|
|
||||||
result = (VarBit *) palloc0(size);
|
|
||||||
SET_VARSIZE(result, size);
|
|
||||||
VARBITLEN(result) = dim;
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Ensure same number of bits
|
|
||||||
*/
|
|
||||||
static inline void
|
|
||||||
CheckBitLengths(uint32 aLen, uint32 bLen)
|
|
||||||
{
|
|
||||||
if (aLen != bLen)
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
|
||||||
errmsg("different bit lengths %u and %u", aLen, bLen)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the Hamming distance between two bit strings
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(hamming_distance);
|
|
||||||
Datum
|
|
||||||
hamming_distance(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
VarBit *a = PG_GETARG_VARBIT_P(0);
|
|
||||||
VarBit *b = PG_GETARG_VARBIT_P(1);
|
|
||||||
unsigned char *ax = VARBITS(a);
|
|
||||||
unsigned char *bx = VARBITS(b);
|
|
||||||
uint64 distance = 0;
|
|
||||||
|
|
||||||
CheckBitLengths(VARBITLEN(a), VARBITLEN(b));
|
|
||||||
|
|
||||||
/* TODO Improve performance */
|
|
||||||
for (uint32 i = 0; i < VARBITBYTES(a); i++)
|
|
||||||
distance += pg_number_of_ones[ax[i] ^ bx[i]];
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8((double) distance);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the Jaccard distance between two bit strings
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(jaccard_distance);
|
|
||||||
Datum
|
|
||||||
jaccard_distance(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
VarBit *a = PG_GETARG_VARBIT_P(0);
|
|
||||||
VarBit *b = PG_GETARG_VARBIT_P(1);
|
|
||||||
unsigned char *ax = VARBITS(a);
|
|
||||||
unsigned char *bx = VARBITS(b);
|
|
||||||
uint64 ab = 0;
|
|
||||||
uint64 aa;
|
|
||||||
uint64 bb;
|
|
||||||
|
|
||||||
CheckBitLengths(VARBITLEN(a), VARBITLEN(b));
|
|
||||||
|
|
||||||
/* TODO Improve performance */
|
|
||||||
for (uint32 i = 0; i < VARBITBYTES(a); i++)
|
|
||||||
ab += pg_number_of_ones[ax[i] & bx[i]];
|
|
||||||
|
|
||||||
if (ab == 0)
|
|
||||||
PG_RETURN_FLOAT8(1);
|
|
||||||
|
|
||||||
aa = pg_popcount((char *) ax, VARBITBYTES(a));
|
|
||||||
bb = pg_popcount((char *) bx, VARBITBYTES(b));
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8(1 - (ab / ((double) (aa + bb - ab))));
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#ifndef BITVECTOR_H
|
|
||||||
#define BITVECTOR_H
|
|
||||||
|
|
||||||
#include "utils/varbit.h"
|
|
||||||
|
|
||||||
VarBit *InitBitVector(int dim);
|
|
||||||
|
|
||||||
#endif
|
|
||||||
11
src/hnsw.h
11
src/hnsw.h
@@ -55,6 +55,12 @@
|
|||||||
#define HNSW_UPDATE_ENTRY_GREATER 1
|
#define HNSW_UPDATE_ENTRY_GREATER 1
|
||||||
#define HNSW_UPDATE_ENTRY_ALWAYS 2
|
#define HNSW_UPDATE_ENTRY_ALWAYS 2
|
||||||
|
|
||||||
|
typedef enum HnswType
|
||||||
|
{
|
||||||
|
HNSW_TYPE_VECTOR,
|
||||||
|
HNSW_TYPE_INTVEC
|
||||||
|
} HnswType;
|
||||||
|
|
||||||
/* Build phases */
|
/* Build phases */
|
||||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||||
#define PROGRESS_HNSW_PHASE_LOAD 2
|
#define PROGRESS_HNSW_PHASE_LOAD 2
|
||||||
@@ -242,6 +248,7 @@ typedef struct HnswBuildState
|
|||||||
Relation index;
|
Relation index;
|
||||||
IndexInfo *indexInfo;
|
IndexInfo *indexInfo;
|
||||||
ForkNumber forkNum;
|
ForkNumber forkNum;
|
||||||
|
HnswType type;
|
||||||
|
|
||||||
/* Settings */
|
/* Settings */
|
||||||
int dimensions;
|
int dimensions;
|
||||||
@@ -262,7 +269,6 @@ typedef struct HnswBuildState
|
|||||||
HnswGraph *graph;
|
HnswGraph *graph;
|
||||||
double ml;
|
double ml;
|
||||||
int maxLevel;
|
int maxLevel;
|
||||||
Vector *normvec;
|
|
||||||
|
|
||||||
/* Memory */
|
/* Memory */
|
||||||
MemoryContext graphCtx;
|
MemoryContext graphCtx;
|
||||||
@@ -367,7 +373,8 @@ typedef struct HnswVacuumState
|
|||||||
int HnswGetM(Relation index);
|
int HnswGetM(Relation index);
|
||||||
int HnswGetEfConstruction(Relation index);
|
int HnswGetEfConstruction(Relation index);
|
||||||
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
HnswType HnswGetType(Relation index);
|
||||||
|
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type);
|
||||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||||
void HnswInitPage(Buffer buf, Page page);
|
void HnswInitPage(Buffer buf, Page page);
|
||||||
void HnswInit(void);
|
void HnswInit(void);
|
||||||
|
|||||||
@@ -44,7 +44,6 @@
|
|||||||
#include "access/xact.h"
|
#include "access/xact.h"
|
||||||
#include "access/xloginsert.h"
|
#include "access/xloginsert.h"
|
||||||
#include "catalog/index.h"
|
#include "catalog/index.h"
|
||||||
#include "catalog/pg_type_d.h"
|
|
||||||
#include "commands/progress.h"
|
#include "commands/progress.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
@@ -490,7 +489,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
|||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->normvec))
|
if (!HnswNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->type))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -673,20 +672,20 @@ static void
|
|||||||
InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, IndexInfo *indexInfo, ForkNumber forkNum)
|
InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, IndexInfo *indexInfo, ForkNumber forkNum)
|
||||||
{
|
{
|
||||||
int maxDimensions = HNSW_MAX_DIM;
|
int maxDimensions = HNSW_MAX_DIM;
|
||||||
Oid typid = TupleDescAttr(index->rd_att, 0)->atttypid;
|
|
||||||
|
|
||||||
if (typid == BITOID || typid == VARBITOID)
|
|
||||||
maxDimensions *= 32;
|
|
||||||
|
|
||||||
buildstate->heap = heap;
|
buildstate->heap = heap;
|
||||||
buildstate->index = index;
|
buildstate->index = index;
|
||||||
buildstate->indexInfo = indexInfo;
|
buildstate->indexInfo = indexInfo;
|
||||||
buildstate->forkNum = forkNum;
|
buildstate->forkNum = forkNum;
|
||||||
|
buildstate->type = HnswGetType(index);
|
||||||
|
|
||||||
buildstate->m = HnswGetM(index);
|
buildstate->m = HnswGetM(index);
|
||||||
buildstate->efConstruction = HnswGetEfConstruction(index);
|
buildstate->efConstruction = HnswGetEfConstruction(index);
|
||||||
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
||||||
|
|
||||||
|
if (buildstate->type == HNSW_TYPE_INTVEC)
|
||||||
|
maxDimensions *= 4;
|
||||||
|
|
||||||
/* Require column to have dimensions to be indexed */
|
/* Require column to have dimensions to be indexed */
|
||||||
if (buildstate->dimensions < 0)
|
if (buildstate->dimensions < 0)
|
||||||
elog(ERROR, "column does not have dimensions");
|
elog(ERROR, "column does not have dimensions");
|
||||||
@@ -710,9 +709,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
buildstate->ml = HnswGetMl(buildstate->m);
|
buildstate->ml = HnswGetMl(buildstate->m);
|
||||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||||
|
|
||||||
/* Reuse for each tuple */
|
|
||||||
buildstate->normvec = InitVector(buildstate->dimensions);
|
|
||||||
|
|
||||||
buildstate->graphCtx = GenerationContextCreate(CurrentMemoryContext,
|
buildstate->graphCtx = GenerationContextCreate(CurrentMemoryContext,
|
||||||
"Hnsw build graph context",
|
"Hnsw build graph context",
|
||||||
#if PG_VERSION_NUM >= 150000
|
#if PG_VERSION_NUM >= 150000
|
||||||
@@ -736,7 +732,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
static void
|
static void
|
||||||
FreeBuildState(HnswBuildState * buildstate)
|
FreeBuildState(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
pfree(buildstate->normvec);
|
|
||||||
MemoryContextDelete(buildstate->graphCtx);
|
MemoryContextDelete(buildstate->graphCtx);
|
||||||
MemoryContextDelete(buildstate->tmpCtx);
|
MemoryContextDelete(buildstate->tmpCtx);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -622,7 +622,7 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(normprocinfo, collation, &value, NULL))
|
if (!HnswNormValue(normprocinfo, collation, &value, HnswGetType(index)))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/relscan.h"
|
#include "access/relscan.h"
|
||||||
#include "bitvector.h"
|
|
||||||
#include "catalog/pg_type_d.h"
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "pgstat.h"
|
#include "pgstat.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
@@ -42,29 +40,6 @@ GetScanItems(IndexScanDesc scan, Datum q)
|
|||||||
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
|
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Get dimensions from metapage
|
|
||||||
*/
|
|
||||||
static int
|
|
||||||
GetDimensions(Relation index)
|
|
||||||
{
|
|
||||||
Buffer buf;
|
|
||||||
Page page;
|
|
||||||
HnswMetaPage metap;
|
|
||||||
int dimensions;
|
|
||||||
|
|
||||||
buf = ReadBuffer(index, HNSW_METAPAGE_BLKNO);
|
|
||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
metap = HnswPageGetMeta(page);
|
|
||||||
|
|
||||||
dimensions = metap->dimensions;
|
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
|
|
||||||
return dimensions;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get scan value
|
* Get scan value
|
||||||
*/
|
*/
|
||||||
@@ -75,15 +50,7 @@ GetScanValue(IndexScanDesc scan)
|
|||||||
Datum value;
|
Datum value;
|
||||||
|
|
||||||
if (scan->orderByData->sk_flags & SK_ISNULL)
|
if (scan->orderByData->sk_flags & SK_ISNULL)
|
||||||
{
|
value = PointerGetDatum(NULL);
|
||||||
Oid typid = TupleDescAttr(scan->indexRelation->rd_att, 0)->atttypid;
|
|
||||||
int dimensions = GetDimensions(scan->indexRelation);
|
|
||||||
|
|
||||||
if (typid == BITOID || typid == VARBITOID)
|
|
||||||
value = PointerGetDatum(InitBitVector(dimensions));
|
|
||||||
else
|
|
||||||
value = PointerGetDatum(InitVector(dimensions));
|
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
value = scan->orderByData->sk_argument;
|
value = scan->orderByData->sk_argument;
|
||||||
@@ -94,7 +61,7 @@ GetScanValue(IndexScanDesc scan)
|
|||||||
|
|
||||||
/* Fine if normalization fails */
|
/* Fine if normalization fails */
|
||||||
if (so->normprocinfo != NULL)
|
if (so->normprocinfo != NULL)
|
||||||
HnswNormValue(so->normprocinfo, so->collation, &value, NULL);
|
HnswNormValue(so->normprocinfo, so->collation, &value, HnswGetType(scan->indexRelation));
|
||||||
}
|
}
|
||||||
|
|
||||||
return value;
|
return value;
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include <float.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
|
#include "catalog/pg_type.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "lib/pairingheap.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "utils/datum.h"
|
#include "utils/datum.h"
|
||||||
#include "utils/memdebug.h"
|
#include "utils/memdebug.h"
|
||||||
#include "utils/rel.h"
|
#include "utils/rel.h"
|
||||||
|
#include "utils/syscache.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
@@ -149,6 +152,32 @@ HnswOptionalProcInfo(Relation index, uint16 procnum)
|
|||||||
return index_getprocinfo(index, 1, procnum);
|
return index_getprocinfo(index, 1, procnum);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get vector type
|
||||||
|
*/
|
||||||
|
HnswType
|
||||||
|
HnswGetType(Relation index)
|
||||||
|
{
|
||||||
|
Oid typeOid = TupleDescAttr(index->rd_att, 0)->atttypid;
|
||||||
|
HeapTuple tuple;
|
||||||
|
Form_pg_type type;
|
||||||
|
int result;
|
||||||
|
|
||||||
|
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeOid));
|
||||||
|
if (!HeapTupleIsValid(tuple))
|
||||||
|
elog(ERROR, "cache lookup failed for type %u", typeOid);
|
||||||
|
|
||||||
|
type = (Form_pg_type) GETSTRUCT(tuple);
|
||||||
|
if (strcmp(NameStr(type->typname), "intvec") == 0)
|
||||||
|
result = HNSW_TYPE_INTVEC;
|
||||||
|
else
|
||||||
|
result = HNSW_TYPE_VECTOR;
|
||||||
|
|
||||||
|
ReleaseSysCache(tuple);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Divide by the norm
|
* Divide by the norm
|
||||||
*
|
*
|
||||||
@@ -158,21 +187,29 @@ HnswOptionalProcInfo(Relation index, uint16 procnum)
|
|||||||
* if it's different than the original value
|
* if it's different than the original value
|
||||||
*/
|
*/
|
||||||
bool
|
bool
|
||||||
HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result)
|
HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, HnswType type)
|
||||||
{
|
{
|
||||||
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
||||||
|
|
||||||
if (norm > 0)
|
if (norm > 0)
|
||||||
|
{
|
||||||
|
/* TODO Remove vector-specific code */
|
||||||
|
if (type == HNSW_TYPE_VECTOR)
|
||||||
{
|
{
|
||||||
Vector *v = DatumGetVector(*value);
|
Vector *v = DatumGetVector(*value);
|
||||||
|
Vector *result = InitVector(v->dim);
|
||||||
if (result == NULL)
|
|
||||||
result = InitVector(v->dim);
|
|
||||||
|
|
||||||
for (int i = 0; i < v->dim; i++)
|
for (int i = 0; i < v->dim; i++)
|
||||||
result->x[i] = v->x[i] / norm;
|
result->x[i] = v->x[i] / norm;
|
||||||
|
|
||||||
*value = PointerGetDatum(result);
|
*value = PointerGetDatum(result);
|
||||||
|
}
|
||||||
|
else if (type == HNSW_TYPE_INTVEC)
|
||||||
|
{
|
||||||
|
/* Do nothing */
|
||||||
|
}
|
||||||
|
else
|
||||||
|
elog(ERROR, "Unsupported type");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -575,8 +612,20 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
|||||||
|
|
||||||
/* Calculate distance */
|
/* Calculate distance */
|
||||||
if (distance != NULL)
|
if (distance != NULL)
|
||||||
|
{
|
||||||
|
if (DatumGetPointer(*q) == NULL)
|
||||||
|
*distance = 0;
|
||||||
|
else
|
||||||
|
{
|
||||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->data)));
|
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->data)));
|
||||||
|
|
||||||
|
/* Needed for intvec cosine distance */
|
||||||
|
/* TODO Improve */
|
||||||
|
if (isnan(*distance))
|
||||||
|
*distance = FLT_MAX;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
608
src/intvec.c
Normal file
608
src/intvec.c
Normal file
@@ -0,0 +1,608 @@
|
|||||||
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "catalog/pg_type.h"
|
||||||
|
#include "fmgr.h"
|
||||||
|
#include "intvec.h"
|
||||||
|
#include "lib/stringinfo.h"
|
||||||
|
#include "libpq/pqformat.h"
|
||||||
|
#include "utils/array.h"
|
||||||
|
#include "utils/builtins.h"
|
||||||
|
#include "utils/lsyscache.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure same dimensions
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckDims(IntVector * a, IntVector * b)
|
||||||
|
{
|
||||||
|
if (a->dim != b->dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("different intvec dimensions %d and %d", a->dim, b->dim)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure expected dimensions
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckExpectedDim(int32 typmod, int dim)
|
||||||
|
{
|
||||||
|
if (typmod != -1 && typmod != dim)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("expected %d dimensions, not %d", typmod, dim)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure valid dimensions
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckDim(int dim)
|
||||||
|
{
|
||||||
|
if (dim < 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("intvec must have at least 1 dimension")));
|
||||||
|
|
||||||
|
if (dim > INTVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("intvec cannot have more than %d dimensions", INTVEC_MAX_DIM)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Ensure element in range
|
||||||
|
*/
|
||||||
|
static inline void
|
||||||
|
CheckElement(long value)
|
||||||
|
{
|
||||||
|
if (value < SCHAR_MIN || value > SCHAR_MAX)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("value \"%ld\" is out of range for type intvec", value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Allocate and initialize a new int vector
|
||||||
|
*/
|
||||||
|
IntVector *
|
||||||
|
InitIntVector(int dim)
|
||||||
|
{
|
||||||
|
IntVector *result;
|
||||||
|
int size;
|
||||||
|
|
||||||
|
size = INTVEC_SIZE(dim);
|
||||||
|
result = (IntVector *) palloc0(size);
|
||||||
|
SET_VARSIZE(result, size);
|
||||||
|
result->dim = dim;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check for whitespace, since array_isspace() is static
|
||||||
|
*/
|
||||||
|
static inline bool
|
||||||
|
intvec_isspace(char ch)
|
||||||
|
{
|
||||||
|
if (ch == ' ' ||
|
||||||
|
ch == '\t' ||
|
||||||
|
ch == '\n' ||
|
||||||
|
ch == '\r' ||
|
||||||
|
ch == '\v' ||
|
||||||
|
ch == '\f')
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert textual representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_in);
|
||||||
|
Datum
|
||||||
|
intvec_in(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
char *lit = PG_GETARG_CSTRING(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
int8 x[INTVEC_MAX_DIM];
|
||||||
|
int dim = 0;
|
||||||
|
char *pt;
|
||||||
|
char *stringEnd;
|
||||||
|
IntVector *result;
|
||||||
|
char *litcopy = pstrdup(lit);
|
||||||
|
char *str = litcopy;
|
||||||
|
|
||||||
|
while (intvec_isspace(*str))
|
||||||
|
str++;
|
||||||
|
|
||||||
|
if (*str != '[')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("malformed intvec literal: \"%s\"", lit),
|
||||||
|
errdetail("Vector contents must start with \"[\".")));
|
||||||
|
|
||||||
|
str++;
|
||||||
|
pt = strtok(str, ",");
|
||||||
|
stringEnd = pt;
|
||||||
|
|
||||||
|
while (pt != NULL && *stringEnd != ']')
|
||||||
|
{
|
||||||
|
long l;
|
||||||
|
|
||||||
|
if (dim == INTVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||||
|
errmsg("intvec cannot have more than %d dimensions", INTVEC_MAX_DIM)));
|
||||||
|
|
||||||
|
while (intvec_isspace(*pt))
|
||||||
|
pt++;
|
||||||
|
|
||||||
|
/* Check for empty string like float4in */
|
||||||
|
if (*pt == '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type intvec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
/* Use similar logic as int2vectorin */
|
||||||
|
errno = 0;
|
||||||
|
l = strtol(pt, &stringEnd, 10);
|
||||||
|
|
||||||
|
if (stringEnd == pt)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type intvec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
if (errno == ERANGE || l < SCHAR_MIN || l > SCHAR_MAX)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
||||||
|
errmsg("value \"%s\" is out of range for type intvec", pt)));
|
||||||
|
|
||||||
|
x[dim++] = l;
|
||||||
|
|
||||||
|
while (intvec_isspace(*stringEnd))
|
||||||
|
stringEnd++;
|
||||||
|
|
||||||
|
if (*stringEnd != '\0' && *stringEnd != ']')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("invalid input syntax for type intvec: \"%s\"", lit)));
|
||||||
|
|
||||||
|
pt = strtok(NULL, ",");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stringEnd == NULL || *stringEnd != ']')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("malformed intvec literal: \"%s\"", lit),
|
||||||
|
errdetail("Unexpected end of input.")));
|
||||||
|
|
||||||
|
stringEnd++;
|
||||||
|
|
||||||
|
/* Only whitespace is allowed after the closing brace */
|
||||||
|
while (intvec_isspace(*stringEnd))
|
||||||
|
stringEnd++;
|
||||||
|
|
||||||
|
if (*stringEnd != '\0')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("malformed intvec literal: \"%s\"", lit),
|
||||||
|
errdetail("Junk after closing right brace.")));
|
||||||
|
|
||||||
|
/* Ensure no consecutive delimiters since strtok skips */
|
||||||
|
for (pt = lit + 1; *pt != '\0'; pt++)
|
||||||
|
{
|
||||||
|
if (pt[-1] == ',' && *pt == ',')
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
||||||
|
errmsg("malformed intvec literal: \"%s\"", lit)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dim < 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("intvec must have at least 1 dimension")));
|
||||||
|
|
||||||
|
pfree(litcopy);
|
||||||
|
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
result = InitIntVector(dim);
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
result->x[i] = x[i];
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to textual representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_out);
|
||||||
|
Datum
|
||||||
|
intvec_out(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *vector = PG_GETARG_INTVEC_P(0);
|
||||||
|
int dim = vector->dim;
|
||||||
|
char *buf;
|
||||||
|
char *ptr;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Need:
|
||||||
|
*
|
||||||
|
* dim * 4 bytes for elements (-128 to 127)
|
||||||
|
*
|
||||||
|
* dim - 1 bytes for separator
|
||||||
|
*
|
||||||
|
* 3 bytes for [, ], and \0
|
||||||
|
*/
|
||||||
|
buf = (char *) palloc(5 * dim + 2);
|
||||||
|
ptr = buf;
|
||||||
|
|
||||||
|
*ptr = '[';
|
||||||
|
ptr++;
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
{
|
||||||
|
*ptr = ',';
|
||||||
|
ptr++;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if PG_VERSION_NUM >= 140000
|
||||||
|
ptr += pg_ltoa(vector->x[i], ptr);
|
||||||
|
#else
|
||||||
|
pg_ltoa(vector->x[i], ptr);
|
||||||
|
while (*ptr != '\0')
|
||||||
|
ptr++;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
*ptr = ']';
|
||||||
|
ptr++;
|
||||||
|
*ptr = '\0';
|
||||||
|
|
||||||
|
PG_FREE_IF_COPY(vector, 0);
|
||||||
|
PG_RETURN_CSTRING(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_typmod_in);
|
||||||
|
Datum
|
||||||
|
intvec_typmod_in(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
|
||||||
|
int32 *tl;
|
||||||
|
int n;
|
||||||
|
|
||||||
|
tl = ArrayGetIntegerTypmods(ta, &n);
|
||||||
|
|
||||||
|
if (n != 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
||||||
|
errmsg("invalid type modifier")));
|
||||||
|
|
||||||
|
if (*tl < 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
||||||
|
errmsg("dimensions for type intvec must be at least 1")));
|
||||||
|
|
||||||
|
if (*tl > INTVEC_MAX_DIM)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
||||||
|
errmsg("dimensions for type intvec cannot exceed %d", INTVEC_MAX_DIM)));
|
||||||
|
|
||||||
|
PG_RETURN_INT32(*tl);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert external binary representation to internal representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_recv);
|
||||||
|
Datum
|
||||||
|
intvec_recv(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
|
IntVector *result;
|
||||||
|
int16 dim;
|
||||||
|
int16 unused;
|
||||||
|
|
||||||
|
dim = pq_getmsgint(buf, sizeof(int16));
|
||||||
|
unused = pq_getmsgint(buf, sizeof(int16));
|
||||||
|
|
||||||
|
CheckDim(dim);
|
||||||
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
|
if (unused != 0)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("expected unused to be 0, not %d", unused)));
|
||||||
|
|
||||||
|
result = InitIntVector(dim);
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
result->x[i] = pq_getmsgint(buf, sizeof(int8));
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert internal representation to the external binary representation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_send);
|
||||||
|
Datum
|
||||||
|
intvec_send(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *vec = PG_GETARG_INTVEC_P(0);
|
||||||
|
StringInfoData buf;
|
||||||
|
|
||||||
|
pq_begintypsend(&buf);
|
||||||
|
pq_sendint(&buf, vec->dim, sizeof(int16));
|
||||||
|
pq_sendint(&buf, vec->unused, sizeof(int16));
|
||||||
|
for (int i = 0; i < vec->dim; i++)
|
||||||
|
pq_sendint8(&buf, vec->x[i]);
|
||||||
|
|
||||||
|
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert int vector to int vector
|
||||||
|
* This is needed to check the type modifier
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec);
|
||||||
|
Datum
|
||||||
|
intvec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *vec = PG_GETARG_INTVEC_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
|
||||||
|
CheckExpectedDim(typmod, vec->dim);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(vec);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Convert array to intvec vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(array_to_intvec);
|
||||||
|
Datum
|
||||||
|
array_to_intvec(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
ArrayType *array = PG_GETARG_ARRAYTYPE_P(0);
|
||||||
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
Vector *result;
|
||||||
|
int16 typlen;
|
||||||
|
bool typbyval;
|
||||||
|
char typalign;
|
||||||
|
Datum *elemsp;
|
||||||
|
int nelemsp;
|
||||||
|
|
||||||
|
if (ARR_NDIM(array) > 1)
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("array must be 1-D")));
|
||||||
|
|
||||||
|
if (ARR_HASNULL(array) && array_contains_nulls(array))
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
|
||||||
|
errmsg("array must not contain nulls")));
|
||||||
|
|
||||||
|
get_typlenbyvalalign(ARR_ELEMTYPE(array), &typlen, &typbyval, &typalign);
|
||||||
|
deconstruct_array(array, ARR_ELEMTYPE(array), typlen, typbyval, typalign, &elemsp, NULL, &nelemsp);
|
||||||
|
|
||||||
|
CheckDim(nelemsp);
|
||||||
|
CheckExpectedDim(typmod, nelemsp);
|
||||||
|
|
||||||
|
result = InitVector(nelemsp);
|
||||||
|
|
||||||
|
if (ARR_ELEMTYPE(array) == INT4OID)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < nelemsp; i++)
|
||||||
|
{
|
||||||
|
long l = DatumGetInt32(elemsp[i]);
|
||||||
|
|
||||||
|
CheckElement(l);
|
||||||
|
|
||||||
|
result->x[i] = l;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ereport(ERROR,
|
||||||
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
|
errmsg("unsupported array type")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Free allocation from deconstruct_array. Do not free individual elements
|
||||||
|
* when pass-by-reference since they point to original array.
|
||||||
|
*/
|
||||||
|
pfree(elemsp);
|
||||||
|
|
||||||
|
PG_RETURN_POINTER(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 distance between int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_l2_distance);
|
||||||
|
Datum
|
||||||
|
intvec_l2_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
{
|
||||||
|
int diff = ax[i] - bx[i];
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt((double) distance));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 squared distance between int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_l2_squared_distance);
|
||||||
|
Datum
|
||||||
|
intvec_l2_squared_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
{
|
||||||
|
int diff = ax[i] - bx[i];
|
||||||
|
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the inner product of two int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_inner_product);
|
||||||
|
Datum
|
||||||
|
intvec_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
distance += ax[i] * bx[i];
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the negative inner product of two int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_negative_inner_product);
|
||||||
|
Datum
|
||||||
|
intvec_negative_inner_product(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
distance += ax[i] * bx[i];
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) -distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the cosine distance between two int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_cosine_distance);
|
||||||
|
Datum
|
||||||
|
intvec_cosine_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
int norma = 0;
|
||||||
|
int normb = 0;
|
||||||
|
double similarity;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
{
|
||||||
|
int8 axi = ax[i];
|
||||||
|
int8 bxi = bx[i];
|
||||||
|
|
||||||
|
distance += axi * bxi;
|
||||||
|
norma += axi * axi;
|
||||||
|
normb += bxi * bxi;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
|
||||||
|
similarity = (double) distance / sqrt((double) norma * (double) normb);
|
||||||
|
|
||||||
|
#ifdef _MSC_VER
|
||||||
|
/* /fp:fast may not propagate NaN */
|
||||||
|
if (isnan(similarity))
|
||||||
|
PG_RETURN_FLOAT8(NAN);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Keep in range */
|
||||||
|
if (similarity > 1)
|
||||||
|
similarity = 1;
|
||||||
|
else if (similarity < -1)
|
||||||
|
similarity = -1;
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(1 - similarity);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L1 distance between two int vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_l1_distance);
|
||||||
|
Datum
|
||||||
|
intvec_l1_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
IntVector *b = PG_GETARG_INTVEC_P(1);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int8 *bx = b->x;
|
||||||
|
int distance = 0;
|
||||||
|
|
||||||
|
CheckDims(a, b);
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
distance += abs(ax[i] - bx[i]);
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) distance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 norm of an int vector
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(intvec_l2_norm);
|
||||||
|
Datum
|
||||||
|
intvec_l2_norm(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
IntVector *a = PG_GETARG_INTVEC_P(0);
|
||||||
|
int8 *ax = a->x;
|
||||||
|
int norm = 0;
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < a->dim; i++)
|
||||||
|
norm += ax[i] * ax[i];
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt((double) norm));
|
||||||
|
}
|
||||||
23
src/intvec.h
Normal file
23
src/intvec.h
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
#ifndef INTVEC_H
|
||||||
|
#define INTVEC_H
|
||||||
|
|
||||||
|
#include "vector.h"
|
||||||
|
|
||||||
|
#define INTVEC_MAX_DIM VECTOR_MAX_DIM
|
||||||
|
|
||||||
|
#define INTVEC_SIZE(_dim) (offsetof(IntVector, x) + sizeof(int8)*(_dim))
|
||||||
|
#define DatumGetIntVector(x) ((IntVector *) PG_DETOAST_DATUM(x))
|
||||||
|
#define PG_GETARG_INTVEC_P(x) DatumGetIntVector(PG_GETARG_DATUM(x))
|
||||||
|
#define PG_RETURN_INTVEC_P(x) PG_RETURN_POINTER(x)
|
||||||
|
|
||||||
|
typedef struct IntVector
|
||||||
|
{
|
||||||
|
int32 vl_len_; /* varlena header (do not touch directly!) */
|
||||||
|
int16 dim; /* number of dimensions */
|
||||||
|
int16 unused;
|
||||||
|
int8 x[FLEXIBLE_ARRAY_MEMBER];
|
||||||
|
} IntVector;
|
||||||
|
|
||||||
|
IntVector *InitIntVector(int dim);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -57,7 +57,7 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
|||||||
*/
|
*/
|
||||||
if (buildstate->kmeansnormprocinfo != NULL)
|
if (buildstate->kmeansnormprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(buildstate->kmeansnormprocinfo, buildstate->collation, &value, buildstate->normvec))
|
if (!IvfflatNormValue(buildstate->kmeansnormprocinfo, buildstate->collation, &value))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ SampleCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
|
|
||||||
/* Add sample */
|
/* Add sample */
|
||||||
AddSample(values, state);
|
AddSample(values, buildstate);
|
||||||
|
|
||||||
/* Reset memory context */
|
/* Reset memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
@@ -153,7 +153,7 @@ AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState
|
|||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(buildstate->normprocinfo, buildstate->collation, &value, buildstate->normvec))
|
if (!IvfflatNormValue(buildstate->normprocinfo, buildstate->collation, &value))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,9 +356,6 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
|||||||
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions);
|
buildstate->centers = VectorArrayInit(buildstate->lists, buildstate->dimensions);
|
||||||
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
buildstate->listInfo = palloc(sizeof(ListInfo) * buildstate->lists);
|
||||||
|
|
||||||
/* Reuse for each tuple */
|
|
||||||
buildstate->normvec = InitVector(buildstate->dimensions);
|
|
||||||
|
|
||||||
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Ivfflat build temporary context",
|
"Ivfflat build temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
@@ -380,7 +377,6 @@ FreeBuildState(IvfflatBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
VectorArrayFree(buildstate->centers);
|
VectorArrayFree(buildstate->centers);
|
||||||
pfree(buildstate->listInfo);
|
pfree(buildstate->listInfo);
|
||||||
pfree(buildstate->normvec);
|
|
||||||
|
|
||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
pfree(buildstate->listSums);
|
pfree(buildstate->listSums);
|
||||||
|
|||||||
@@ -172,7 +172,6 @@ typedef struct IvfflatBuildState
|
|||||||
VectorArray samples;
|
VectorArray samples;
|
||||||
VectorArray centers;
|
VectorArray centers;
|
||||||
ListInfo *listInfo;
|
ListInfo *listInfo;
|
||||||
Vector *normvec;
|
|
||||||
|
|
||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
double inertia;
|
double inertia;
|
||||||
@@ -267,7 +266,7 @@ void VectorArrayFree(VectorArray arr);
|
|||||||
void PrintVectorArray(char *msg, VectorArray arr);
|
void PrintVectorArray(char *msg, VectorArray arr);
|
||||||
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
||||||
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value);
|
||||||
int IvfflatGetLists(Relation index);
|
int IvfflatGetLists(Relation index);
|
||||||
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
||||||
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, NULL))
|
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -293,7 +293,7 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
|
|
||||||
/* Fine if normalization fails */
|
/* Fine if normalization fails */
|
||||||
if (so->normprocinfo != NULL)
|
if (so->normprocinfo != NULL)
|
||||||
IvfflatNormValue(so->normprocinfo, so->collation, &value, NULL);
|
IvfflatNormValue(so->normprocinfo, so->collation, &value);
|
||||||
}
|
}
|
||||||
|
|
||||||
IvfflatBench("GetScanLists", GetScanLists(scan, value));
|
IvfflatBench("GetScanLists", GetScanLists(scan, value));
|
||||||
|
|||||||
@@ -75,16 +75,14 @@ IvfflatOptionalProcInfo(Relation index, uint16 procnum)
|
|||||||
* if it's different than the original value
|
* if it's different than the original value
|
||||||
*/
|
*/
|
||||||
bool
|
bool
|
||||||
IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result)
|
IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value)
|
||||||
{
|
{
|
||||||
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
double norm = DatumGetFloat8(FunctionCall1Coll(procinfo, collation, *value));
|
||||||
|
|
||||||
if (norm > 0)
|
if (norm > 0)
|
||||||
{
|
{
|
||||||
Vector *v = DatumGetVector(*value);
|
Vector *v = DatumGetVector(*value);
|
||||||
|
Vector *result = InitVector(v->dim);
|
||||||
if (result == NULL)
|
|
||||||
result = InitVector(v->dim);
|
|
||||||
|
|
||||||
for (int i = 0; i < v->dim; i++)
|
for (int i = 0; i < v->dim; i++)
|
||||||
result->x[i] = v->x[i] / norm;
|
result->x[i] = v->x[i] / norm;
|
||||||
|
|||||||
21
src/vector.c
21
src/vector.c
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "bitvector.h"
|
|
||||||
#include "catalog/pg_type.h"
|
#include "catalog/pg_type.h"
|
||||||
#include "common/shortest_dec.h"
|
#include "common/shortest_dec.h"
|
||||||
#include "fmgr.h"
|
#include "fmgr.h"
|
||||||
@@ -861,26 +860,6 @@ vector_mul(PG_FUNCTION_ARGS)
|
|||||||
PG_RETURN_POINTER(result);
|
PG_RETURN_POINTER(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Quantize a vector
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(quantize_binary);
|
|
||||||
Datum
|
|
||||||
quantize_binary(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
|
||||||
float *ax = a->x;
|
|
||||||
VarBit *result = InitBitVector(a->dim);
|
|
||||||
unsigned char *rx = VARBITS(result);
|
|
||||||
|
|
||||||
/* TODO Improve */
|
|
||||||
for (int i = 0; i < a->dim; i++)
|
|
||||||
rx[i / 8] |= (ax[i] > 0) << (7 - (i % 8));
|
|
||||||
|
|
||||||
PG_RETURN_VARBIT_P(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Internal helper to compare vectors
|
* Internal helper to compare vectors
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
SELECT hamming_distance(B'111', B'111');
|
|
||||||
hamming_distance
|
|
||||||
------------------
|
|
||||||
0
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'110');
|
|
||||||
hamming_distance
|
|
||||||
------------------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'100');
|
|
||||||
hamming_distance
|
|
||||||
------------------
|
|
||||||
2
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'000');
|
|
||||||
hamming_distance
|
|
||||||
------------------
|
|
||||||
3
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT hamming_distance(B'111', B'00');
|
|
||||||
ERROR: different bit lengths 3 and 2
|
|
||||||
SELECT jaccard_distance(B'1111', B'1111');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
0
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1110');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
0.25
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1100');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
0.5
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1000');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
0.75
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'0000');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1100', B'1000');
|
|
||||||
jaccard_distance
|
|
||||||
------------------
|
|
||||||
0.5
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'000');
|
|
||||||
ERROR: different bit lengths 4 and 3
|
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
CREATE TABLE t (val vector(3));
|
CREATE TABLE t (val vector(3), val2 intvec(3));
|
||||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
INSERT INTO t (val, val2) VALUES ('[0,0,0]', '[0,0,0]'), ('[1,2,3]', '[1,2,3]'), ('[1,1,1]', '[1,1,1]'), (NULL, NULL);
|
||||||
CREATE TABLE t2 (val vector(3));
|
CREATE TABLE t2 (val vector(3), val2 intvec(3));
|
||||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||||
SELECT * FROM t2 ORDER BY val;
|
SELECT * FROM t2 ORDER BY val;
|
||||||
val
|
val | val2
|
||||||
---------
|
---------+---------
|
||||||
[0,0,0]
|
[0,0,0] | [0,0,0]
|
||||||
[1,1,1]
|
[1,1,1] | [1,1,1]
|
||||||
[1,2,3]
|
[1,2,3] | [1,2,3]
|
||||||
|
|
|
||||||
(4 rows)
|
(4 rows)
|
||||||
|
|
||||||
DROP TABLE t;
|
DROP TABLE t;
|
||||||
|
|||||||
@@ -104,122 +104,110 @@ SELECT vector_norm('[3e37,4e37]')::real;
|
|||||||
5e+37
|
5e+37
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l2_distance('[0,0]', '[3,4]');
|
SELECT l2_distance('[0,0]'::vector, '[3,4]');
|
||||||
l2_distance
|
l2_distance
|
||||||
-------------
|
-------------
|
||||||
5
|
5
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l2_distance('[0,0]', '[0,1]');
|
SELECT l2_distance('[0,0]'::vector, '[0,1]');
|
||||||
l2_distance
|
l2_distance
|
||||||
-------------
|
-------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l2_distance('[1,2]', '[3]');
|
SELECT l2_distance('[1,2]'::vector, '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT l2_distance('[3e38]', '[-3e38]');
|
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
||||||
l2_distance
|
l2_distance
|
||||||
-------------
|
-------------
|
||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT inner_product('[1,2]', '[3,4]');
|
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
||||||
inner_product
|
inner_product
|
||||||
---------------
|
---------------
|
||||||
11
|
11
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT inner_product('[1,2]', '[3]');
|
SELECT inner_product('[1,2]'::vector, '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT inner_product('[3e38]', '[3e38]');
|
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
||||||
inner_product
|
inner_product
|
||||||
---------------
|
---------------
|
||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]', '[2,4]');
|
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]', '[0,0]');
|
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
NaN
|
NaN
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]', '[1,1]');
|
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
2
|
2
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]', '[3]');
|
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
SELECT cosine_distance('[1,1]'::vector, '[1.1,1.1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]', '[-1.1,-1.1]');
|
SELECT cosine_distance('[1,1]'::vector, '[-1.1,-1.1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
2
|
2
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[3e38]', '[3e38]');
|
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
NaN
|
NaN
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l1_distance('[0,0]', '[3,4]');
|
SELECT l1_distance('[0,0]'::vector, '[3,4]');
|
||||||
l1_distance
|
l1_distance
|
||||||
-------------
|
-------------
|
||||||
7
|
7
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l1_distance('[0,0]', '[0,1]');
|
SELECT l1_distance('[0,0]'::vector, '[0,1]');
|
||||||
l1_distance
|
l1_distance
|
||||||
-------------
|
-------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT l1_distance('[1,2]', '[3]');
|
SELECT l1_distance('[1,2]'::vector, '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT l1_distance('[3e38]', '[-3e38]');
|
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
||||||
l1_distance
|
l1_distance
|
||||||
-------------
|
-------------
|
||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT quantize_binary('[1,0,-1]');
|
|
||||||
quantize_binary
|
|
||||||
-----------------
|
|
||||||
100
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]');
|
|
||||||
quantize_binary
|
|
||||||
-----------------
|
|
||||||
01001110101
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
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]']) v;
|
||||||
avg
|
avg
|
||||||
-----------
|
-----------
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
SET enable_seqscan = off;
|
|
||||||
CREATE TABLE t (val bit(3));
|
|
||||||
INSERT INTO t (val) VALUES (B'000'), (B'100'), (B'111'), (NULL);
|
|
||||||
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
|
||||||
INSERT INTO t (val) VALUES (B'110');
|
|
||||||
SELECT * FROM t ORDER BY val <~> B'111';
|
|
||||||
val
|
|
||||||
-----
|
|
||||||
111
|
|
||||||
110
|
|
||||||
100
|
|
||||||
000
|
|
||||||
(4 rows)
|
|
||||||
|
|
||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <~> (SELECT NULL::bit)) t2;
|
|
||||||
count
|
|
||||||
-------
|
|
||||||
4
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
DROP TABLE t;
|
|
||||||
26
test/expected/hnsw_intvec_cosine.out
Normal file
26
test/expected/hnsw_intvec_cosine.out
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_cosine_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
SELECT * FROM t ORDER BY val <=> '[3,3,3]';
|
||||||
|
val
|
||||||
|
---------
|
||||||
|
[1,1,1]
|
||||||
|
[1,2,3]
|
||||||
|
[1,2,4]
|
||||||
|
(3 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::intvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
3
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
21
test/expected/hnsw_intvec_ip.out
Normal file
21
test/expected/hnsw_intvec_ip.out
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_ip_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
SELECT * FROM t ORDER BY val <#> '[3,3,3]';
|
||||||
|
val
|
||||||
|
---------
|
||||||
|
[1,2,4]
|
||||||
|
[1,2,3]
|
||||||
|
[1,1,1]
|
||||||
|
[0,0,0]
|
||||||
|
(4 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::intvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
33
test/expected/hnsw_intvec_l2.out
Normal file
33
test/expected/hnsw_intvec_l2.out
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_l2_ops);
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
val
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
[1,2,4]
|
||||||
|
[1,1,1]
|
||||||
|
[0,0,0]
|
||||||
|
(4 rows)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::intvec)) t2;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
4
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
count
|
||||||
|
-------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
val
|
||||||
|
-----
|
||||||
|
(0 rows)
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
SET enable_seqscan = off;
|
|
||||||
CREATE TABLE t (val bit(4));
|
|
||||||
INSERT INTO t (val) VALUES (B'0000'), (B'1100'), (B'1111'), (NULL);
|
|
||||||
CREATE INDEX ON t USING hnsw (val bit_jaccard_ops);
|
|
||||||
INSERT INTO t (val) VALUES (B'1110');
|
|
||||||
SELECT * FROM t ORDER BY val <%> B'1111';
|
|
||||||
val
|
|
||||||
------
|
|
||||||
1111
|
|
||||||
1110
|
|
||||||
1100
|
|
||||||
0000
|
|
||||||
(4 rows)
|
|
||||||
|
|
||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <%> (SELECT NULL::bit)) t2;
|
|
||||||
count
|
|
||||||
-------
|
|
||||||
4
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
DROP TABLE t;
|
|
||||||
@@ -12,14 +12,11 @@ SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
|||||||
[0,0,0]
|
[0,0,0]
|
||||||
(4 rows)
|
(4 rows)
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
|
||||||
val
|
count
|
||||||
---------
|
-------
|
||||||
[0,0,0]
|
4
|
||||||
[1,1,1]
|
(1 row)
|
||||||
[1,2,3]
|
|
||||||
[1,2,4]
|
|
||||||
(4 rows)
|
|
||||||
|
|
||||||
SELECT COUNT(*) FROM t;
|
SELECT COUNT(*) FROM t;
|
||||||
count
|
count
|
||||||
|
|||||||
92
test/expected/intvec_functions.out
Normal file
92
test/expected/intvec_functions.out
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
SELECT l2_distance('[0,0]'::intvec, '[3,4]');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('[0,0]'::intvec, '[0,1]');
|
||||||
|
l2_distance
|
||||||
|
-------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l2_distance('[1,2]'::intvec, '[3]');
|
||||||
|
ERROR: different intvec dimensions 2 and 1
|
||||||
|
SELECT '[0,0]'::intvec <-> '[3,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
5
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::intvec, '[3,4]');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
11
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::intvec, '[3]');
|
||||||
|
ERROR: different intvec dimensions 2 and 1
|
||||||
|
SELECT inner_product('[127]'::intvec, '[127]');
|
||||||
|
inner_product
|
||||||
|
---------------
|
||||||
|
16129
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2]'::intvec <#> '[3,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
-11
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[2,4]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[0,0]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
NaN
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,1]'::intvec, '[1,1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,0]'::intvec, '[0,2]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,1]'::intvec, '[-1,-1]');
|
||||||
|
cosine_distance
|
||||||
|
-----------------
|
||||||
|
2
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[3]');
|
||||||
|
ERROR: different intvec dimensions 2 and 1
|
||||||
|
SELECT '[1,2]'::intvec <=> '[2,4]';
|
||||||
|
?column?
|
||||||
|
----------
|
||||||
|
0
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::intvec, '[3,4]');
|
||||||
|
l1_distance
|
||||||
|
-------------
|
||||||
|
7
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::intvec, '[0,1]');
|
||||||
|
l1_distance
|
||||||
|
-------------
|
||||||
|
1
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT l1_distance('[1,2]'::intvec, '[3]');
|
||||||
|
ERROR: different intvec dimensions 2 and 1
|
||||||
119
test/expected/intvec_input.out
Normal file
119
test/expected/intvec_input.out
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
SELECT '[1,2,3]'::intvec;
|
||||||
|
intvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[-1,-2,-3]'::intvec;
|
||||||
|
intvec
|
||||||
|
------------
|
||||||
|
[-1,-2,-3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT ' [ 1, 2 , 3 ] '::intvec;
|
||||||
|
intvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1.23456]'::intvec;
|
||||||
|
ERROR: invalid input syntax for type intvec: "[1.23456]"
|
||||||
|
LINE 1: SELECT '[1.23456]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[hello,1]'::intvec;
|
||||||
|
ERROR: invalid input syntax for type intvec: "[hello,1]"
|
||||||
|
LINE 1: SELECT '[hello,1]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[127,-128]'::intvec;
|
||||||
|
intvec
|
||||||
|
------------
|
||||||
|
[127,-128]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[128,-129]'::intvec;
|
||||||
|
ERROR: value "128" is out of range for type intvec
|
||||||
|
LINE 1: SELECT '[128,-129]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3'::intvec;
|
||||||
|
ERROR: malformed intvec literal: "[1,2,3"
|
||||||
|
LINE 1: SELECT '[1,2,3'::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Unexpected end of input.
|
||||||
|
SELECT '[1,2,3]9'::intvec;
|
||||||
|
ERROR: malformed intvec literal: "[1,2,3]9"
|
||||||
|
LINE 1: SELECT '[1,2,3]9'::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Junk after closing right brace.
|
||||||
|
SELECT '1,2,3'::intvec;
|
||||||
|
ERROR: malformed intvec literal: "1,2,3"
|
||||||
|
LINE 1: SELECT '1,2,3'::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Vector contents must start with "[".
|
||||||
|
SELECT ''::intvec;
|
||||||
|
ERROR: malformed intvec literal: ""
|
||||||
|
LINE 1: SELECT ''::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Vector contents must start with "[".
|
||||||
|
SELECT '['::intvec;
|
||||||
|
ERROR: malformed intvec literal: "["
|
||||||
|
LINE 1: SELECT '['::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Unexpected end of input.
|
||||||
|
SELECT '[,'::intvec;
|
||||||
|
ERROR: malformed intvec literal: "[,"
|
||||||
|
LINE 1: SELECT '[,'::intvec;
|
||||||
|
^
|
||||||
|
DETAIL: Unexpected end of input.
|
||||||
|
SELECT '[]'::intvec;
|
||||||
|
ERROR: intvec must have at least 1 dimension
|
||||||
|
LINE 1: SELECT '[]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,]'::intvec;
|
||||||
|
ERROR: invalid input syntax for type intvec: "[1,]"
|
||||||
|
LINE 1: SELECT '[1,]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1a]'::intvec;
|
||||||
|
ERROR: invalid input syntax for type intvec: "[1a]"
|
||||||
|
LINE 1: SELECT '[1a]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,,3]'::intvec;
|
||||||
|
ERROR: malformed intvec literal: "[1,,3]"
|
||||||
|
LINE 1: SELECT '[1,,3]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1, ,3]'::intvec;
|
||||||
|
ERROR: invalid input syntax for type intvec: "[1, ,3]"
|
||||||
|
LINE 1: SELECT '[1, ,3]'::intvec;
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::intvec(3);
|
||||||
|
intvec
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
(1 row)
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::intvec(2);
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
|
SELECT '[1,2,3]'::intvec(3, 2);
|
||||||
|
ERROR: invalid type modifier
|
||||||
|
LINE 1: SELECT '[1,2,3]'::intvec(3, 2);
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::intvec('a');
|
||||||
|
ERROR: invalid input syntax for type integer: "a"
|
||||||
|
LINE 1: SELECT '[1,2,3]'::intvec('a');
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::intvec(0);
|
||||||
|
ERROR: dimensions for type intvec must be at least 1
|
||||||
|
LINE 1: SELECT '[1,2,3]'::intvec(0);
|
||||||
|
^
|
||||||
|
SELECT '[1,2,3]'::intvec(16001);
|
||||||
|
ERROR: dimensions for type intvec cannot exceed 16000
|
||||||
|
LINE 1: SELECT '[1,2,3]'::intvec(16001);
|
||||||
|
^
|
||||||
|
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::intvec[]);
|
||||||
|
unnest
|
||||||
|
---------
|
||||||
|
[1,2,3]
|
||||||
|
[4,5,6]
|
||||||
|
(2 rows)
|
||||||
|
|
||||||
|
SELECT '{"[1,2,3]"}'::intvec(2)[];
|
||||||
|
ERROR: expected 2 dimensions, not 3
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
SELECT hamming_distance(B'111', B'111');
|
|
||||||
SELECT hamming_distance(B'111', B'110');
|
|
||||||
SELECT hamming_distance(B'111', B'100');
|
|
||||||
SELECT hamming_distance(B'111', B'000');
|
|
||||||
SELECT hamming_distance(B'111', B'00');
|
|
||||||
|
|
||||||
SELECT jaccard_distance(B'1111', B'1111');
|
|
||||||
SELECT jaccard_distance(B'1111', B'1110');
|
|
||||||
SELECT jaccard_distance(B'1111', B'1100');
|
|
||||||
SELECT jaccard_distance(B'1111', B'1000');
|
|
||||||
SELECT jaccard_distance(B'1111', B'0000');
|
|
||||||
SELECT jaccard_distance(B'1100', B'1000');
|
|
||||||
SELECT jaccard_distance(B'1111', B'000');
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
CREATE TABLE t (val vector(3));
|
CREATE TABLE t (val vector(3), val2 intvec(3));
|
||||||
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
INSERT INTO t (val, val2) VALUES ('[0,0,0]', '[0,0,0]'), ('[1,2,3]', '[1,2,3]'), ('[1,1,1]', '[1,1,1]'), (NULL, NULL);
|
||||||
|
|
||||||
CREATE TABLE t2 (val vector(3));
|
CREATE TABLE t2 (val vector(3), val2 intvec(3));
|
||||||
|
|
||||||
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
\copy t TO 'results/data.bin' WITH (FORMAT binary)
|
||||||
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
\copy t2 FROM 'results/data.bin' WITH (FORMAT binary)
|
||||||
|
|||||||
@@ -24,32 +24,29 @@ SELECT vector_norm('[3,4]');
|
|||||||
SELECT vector_norm('[0,1]');
|
SELECT vector_norm('[0,1]');
|
||||||
SELECT vector_norm('[3e37,4e37]')::real;
|
SELECT vector_norm('[3e37,4e37]')::real;
|
||||||
|
|
||||||
SELECT l2_distance('[0,0]', '[3,4]');
|
SELECT l2_distance('[0,0]'::vector, '[3,4]');
|
||||||
SELECT l2_distance('[0,0]', '[0,1]');
|
SELECT l2_distance('[0,0]'::vector, '[0,1]');
|
||||||
SELECT l2_distance('[1,2]', '[3]');
|
SELECT l2_distance('[1,2]'::vector, '[3]');
|
||||||
SELECT l2_distance('[3e38]', '[-3e38]');
|
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
||||||
|
|
||||||
SELECT inner_product('[1,2]', '[3,4]');
|
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
||||||
SELECT inner_product('[1,2]', '[3]');
|
SELECT inner_product('[1,2]'::vector, '[3]');
|
||||||
SELECT inner_product('[3e38]', '[3e38]');
|
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]', '[2,4]');
|
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
||||||
SELECT cosine_distance('[1,2]', '[0,0]');
|
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
||||||
SELECT cosine_distance('[1,1]', '[1,1]');
|
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
||||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
||||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
||||||
SELECT cosine_distance('[1,2]', '[3]');
|
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
||||||
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
SELECT cosine_distance('[1,1]'::vector, '[1.1,1.1]');
|
||||||
SELECT cosine_distance('[1,1]', '[-1.1,-1.1]');
|
SELECT cosine_distance('[1,1]'::vector, '[-1.1,-1.1]');
|
||||||
SELECT cosine_distance('[3e38]', '[3e38]');
|
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
||||||
|
|
||||||
SELECT l1_distance('[0,0]', '[3,4]');
|
SELECT l1_distance('[0,0]'::vector, '[3,4]');
|
||||||
SELECT l1_distance('[0,0]', '[0,1]');
|
SELECT l1_distance('[0,0]'::vector, '[0,1]');
|
||||||
SELECT l1_distance('[1,2]', '[3]');
|
SELECT l1_distance('[1,2]'::vector, '[3]');
|
||||||
SELECT l1_distance('[3e38]', '[-3e38]');
|
SELECT l1_distance('[3e38]'::vector, '[-3e38]');
|
||||||
|
|
||||||
SELECT quantize_binary('[1,0,-1]');
|
|
||||||
SELECT quantize_binary('[0,0.1,-0.2,-0.3,0.4,0.5,0.6,-0.7,0.8,-0.9,1]');
|
|
||||||
|
|
||||||
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]']) v;
|
||||||
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
|
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v;
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
SET enable_seqscan = off;
|
|
||||||
|
|
||||||
CREATE TABLE t (val bit(3));
|
|
||||||
INSERT INTO t (val) VALUES (B'000'), (B'100'), (B'111'), (NULL);
|
|
||||||
CREATE INDEX ON t USING hnsw (val bit_hamming_ops);
|
|
||||||
|
|
||||||
INSERT INTO t (val) VALUES (B'110');
|
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <~> B'111';
|
|
||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <~> (SELECT NULL::bit)) t2;
|
|
||||||
|
|
||||||
DROP TABLE t;
|
|
||||||
13
test/sql/hnsw_intvec_cosine.sql
Normal file
13
test/sql/hnsw_intvec_cosine.sql
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_cosine_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <=> '[3,3,3]';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> '[0,0,0]') t2;
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <=> (SELECT NULL::intvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
12
test/sql/hnsw_intvec_ip.sql
Normal file
12
test/sql/hnsw_intvec_ip.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_ip_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <#> '[3,3,3]';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <#> (SELECT NULL::intvec)) t2;
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
16
test/sql/hnsw_intvec_l2.sql
Normal file
16
test/sql/hnsw_intvec_l2.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
SET enable_seqscan = off;
|
||||||
|
|
||||||
|
CREATE TABLE t (val intvec(3));
|
||||||
|
INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
|
||||||
|
CREATE INDEX ON t USING hnsw (val intvec_l2_ops);
|
||||||
|
|
||||||
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::intvec)) t2;
|
||||||
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
|
TRUNCATE t;
|
||||||
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
|
|
||||||
|
DROP TABLE t;
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
SET enable_seqscan = off;
|
|
||||||
|
|
||||||
CREATE TABLE t (val bit(4));
|
|
||||||
INSERT INTO t (val) VALUES (B'0000'), (B'1100'), (B'1111'), (NULL);
|
|
||||||
CREATE INDEX ON t USING hnsw (val bit_jaccard_ops);
|
|
||||||
|
|
||||||
INSERT INTO t (val) VALUES (B'1110');
|
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <%> B'1111';
|
|
||||||
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <%> (SELECT NULL::bit)) t2;
|
|
||||||
|
|
||||||
DROP TABLE t;
|
|
||||||
@@ -7,7 +7,7 @@ CREATE INDEX ON t USING hnsw (val vector_l2_ops);
|
|||||||
INSERT INTO t (val) VALUES ('[1,2,4]');
|
INSERT INTO t (val) VALUES ('[1,2,4]');
|
||||||
|
|
||||||
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
SELECT * FROM t ORDER BY val <-> '[3,3,3]';
|
||||||
SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector);
|
SELECT COUNT(*) FROM (SELECT * FROM t ORDER BY val <-> (SELECT NULL::vector)) t2;
|
||||||
SELECT COUNT(*) FROM t;
|
SELECT COUNT(*) FROM t;
|
||||||
|
|
||||||
TRUNCATE t;
|
TRUNCATE t;
|
||||||
|
|||||||
21
test/sql/intvec_functions.sql
Normal file
21
test/sql/intvec_functions.sql
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
SELECT l2_distance('[0,0]'::intvec, '[3,4]');
|
||||||
|
SELECT l2_distance('[0,0]'::intvec, '[0,1]');
|
||||||
|
SELECT l2_distance('[1,2]'::intvec, '[3]');
|
||||||
|
SELECT '[0,0]'::intvec <-> '[3,4]';
|
||||||
|
|
||||||
|
SELECT inner_product('[1,2]'::intvec, '[3,4]');
|
||||||
|
SELECT inner_product('[1,2]'::intvec, '[3]');
|
||||||
|
SELECT inner_product('[127]'::intvec, '[127]');
|
||||||
|
SELECT '[1,2]'::intvec <#> '[3,4]';
|
||||||
|
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[2,4]');
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[0,0]');
|
||||||
|
SELECT cosine_distance('[1,1]'::intvec, '[1,1]');
|
||||||
|
SELECT cosine_distance('[1,0]'::intvec, '[0,2]');
|
||||||
|
SELECT cosine_distance('[1,1]'::intvec, '[-1,-1]');
|
||||||
|
SELECT cosine_distance('[1,2]'::intvec, '[3]');
|
||||||
|
SELECT '[1,2]'::intvec <=> '[2,4]';
|
||||||
|
|
||||||
|
SELECT l1_distance('[0,0]'::intvec, '[3,4]');
|
||||||
|
SELECT l1_distance('[0,0]'::intvec, '[0,1]');
|
||||||
|
SELECT l1_distance('[1,2]'::intvec, '[3]');
|
||||||
28
test/sql/intvec_input.sql
Normal file
28
test/sql/intvec_input.sql
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
SELECT '[1,2,3]'::intvec;
|
||||||
|
SELECT '[-1,-2,-3]'::intvec;
|
||||||
|
SELECT ' [ 1, 2 , 3 ] '::intvec;
|
||||||
|
SELECT '[1.23456]'::intvec;
|
||||||
|
SELECT '[hello,1]'::intvec;
|
||||||
|
SELECT '[127,-128]'::intvec;
|
||||||
|
SELECT '[128,-129]'::intvec;
|
||||||
|
SELECT '[1,2,3'::intvec;
|
||||||
|
SELECT '[1,2,3]9'::intvec;
|
||||||
|
SELECT '1,2,3'::intvec;
|
||||||
|
SELECT ''::intvec;
|
||||||
|
SELECT '['::intvec;
|
||||||
|
SELECT '[,'::intvec;
|
||||||
|
SELECT '[]'::intvec;
|
||||||
|
SELECT '[1,]'::intvec;
|
||||||
|
SELECT '[1a]'::intvec;
|
||||||
|
SELECT '[1,,3]'::intvec;
|
||||||
|
SELECT '[1, ,3]'::intvec;
|
||||||
|
|
||||||
|
SELECT '[1,2,3]'::intvec(3);
|
||||||
|
SELECT '[1,2,3]'::intvec(2);
|
||||||
|
SELECT '[1,2,3]'::intvec(3, 2);
|
||||||
|
SELECT '[1,2,3]'::intvec('a');
|
||||||
|
SELECT '[1,2,3]'::intvec(0);
|
||||||
|
SELECT '[1,2,3]'::intvec(16001);
|
||||||
|
|
||||||
|
SELECT unnest('{"[1,2,3]", "[4,5,6]"}'::intvec[]);
|
||||||
|
SELECT '{"[1,2,3]"}'::intvec(2)[];
|
||||||
@@ -86,7 +86,7 @@ foreach (@queries)
|
|||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
test_recall(0.20, $limit, "before vacuum");
|
test_recall(0.19, $limit, "before vacuum");
|
||||||
test_recall(0.95, 100, "before vacuum");
|
test_recall(0.95, 100, "before vacuum");
|
||||||
|
|
||||||
# TODO Test concurrent inserts with vacuum
|
# TODO Test concurrent inserts with vacuum
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ my $node;
|
|||||||
my @queries = ();
|
my @queries = ();
|
||||||
my @expected;
|
my @expected;
|
||||||
my $limit = 20;
|
my $limit = 20;
|
||||||
my $dim = 52;
|
my $dim = 20;
|
||||||
my $max = 2**$dim;
|
my $array_sql = join(",", ('(random() * 255)::int - 128') x $dim);
|
||||||
|
|
||||||
sub test_recall
|
sub test_recall
|
||||||
{
|
{
|
||||||
@@ -19,8 +19,7 @@ sub test_recall
|
|||||||
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
SET enable_seqscan = off;
|
SET enable_seqscan = off;
|
||||||
SET hnsw.ef_search = 100;
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator $queries[0] LIMIT $limit;
|
|
||||||
));
|
));
|
||||||
like($explain, qr/Index Scan/);
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
@@ -28,23 +27,21 @@ sub test_recall
|
|||||||
{
|
{
|
||||||
my $actual = $node->safe_psql("postgres", qq(
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
SET enable_seqscan = off;
|
SET enable_seqscan = off;
|
||||||
SET hnsw.ef_search = 100;
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
SELECT i FROM tst ORDER BY v $operator $queries[$i] LIMIT $limit;
|
|
||||||
));
|
));
|
||||||
my @actual_ids = split("\n", $actual);
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
my @expected_ids = split("\n", $expected[$i]);
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
my %expected_set = map { $_ => 1 } @expected_ids;
|
|
||||||
|
|
||||||
foreach (@actual_ids)
|
foreach (@expected_ids)
|
||||||
{
|
{
|
||||||
if (exists($expected_set{$_}))
|
if (exists($actual_set{$_}))
|
||||||
{
|
{
|
||||||
$correct++;
|
$correct++;
|
||||||
}
|
}
|
||||||
|
$total++;
|
||||||
}
|
}
|
||||||
|
|
||||||
$total += $limit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cmp_ok($correct / $total, ">=", $min, $operator);
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
@@ -57,21 +54,25 @@ $node->start;
|
|||||||
|
|
||||||
# Create table
|
# Create table
|
||||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v bit($dim));");
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v intvec($dim));");
|
||||||
$node->safe_psql("postgres",
|
$node->safe_psql("postgres",
|
||||||
"INSERT INTO tst SELECT i, (random() * $max)::bigint::bit($dim) FROM generate_series(1, 10000) i;"
|
"INSERT INTO tst SELECT i, ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
|
||||||
);
|
);
|
||||||
|
|
||||||
# Generate queries
|
# Generate queries
|
||||||
for (1 .. 20)
|
for (1 .. 20)
|
||||||
{
|
{
|
||||||
my $r = int(rand() * $max);
|
my @r = ();
|
||||||
push(@queries, "${r}::bigint::bit($dim)");
|
for (1 .. $dim)
|
||||||
|
{
|
||||||
|
push(@r, int(rand(256)) - 128);
|
||||||
|
}
|
||||||
|
push(@queries, "[" . join(",", @r) . "]");
|
||||||
}
|
}
|
||||||
|
|
||||||
# Check each index type
|
# Check each index type
|
||||||
my @operators = ("<~>", "<\%>");
|
my @operators = ("<->", "<#>", "<=>");
|
||||||
my @opclasses = ("bit_hamming_ops", "bit_jaccard_ops");
|
my @opclasses = ("intvec_l2_ops", "intvec_ip_ops", "intvec_cosine_ops");
|
||||||
|
|
||||||
for my $i (0 .. $#operators)
|
for my $i (0 .. $#operators)
|
||||||
{
|
{
|
||||||
@@ -82,13 +83,7 @@ for my $i (0 .. $#operators)
|
|||||||
@expected = ();
|
@expected = ();
|
||||||
foreach (@queries)
|
foreach (@queries)
|
||||||
{
|
{
|
||||||
# Handle ties
|
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
||||||
my $res = $node->safe_psql("postgres", qq(
|
|
||||||
WITH top AS (
|
|
||||||
SELECT v $operator $_ AS distance FROM tst ORDER BY v $operator $_ LIMIT $limit
|
|
||||||
)
|
|
||||||
SELECT i FROM tst WHERE (v $operator $_) <= (SELECT MAX(distance) FROM top)
|
|
||||||
));
|
|
||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +94,7 @@ for my $i (0 .. $#operators)
|
|||||||
));
|
));
|
||||||
|
|
||||||
# Test approximate results
|
# Test approximate results
|
||||||
my $min = $operator eq "<\%>" ? 0.96 : 0.99;
|
my $min = 0.99;
|
||||||
test_recall($min, $operator);
|
test_recall($min, $operator);
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
$node->safe_psql("postgres", "DROP INDEX idx;");
|
||||||
Reference in New Issue
Block a user