mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
7 Commits
tinyint
...
hnsw-array
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48b0256931 | ||
|
|
74a830eb56 | ||
|
|
72e9cf06c1 | ||
|
|
310a880186 | ||
|
|
3c2a3db8b2 | ||
|
|
d57a34b25c | ||
|
|
9ac825d14e |
@@ -1,7 +1,7 @@
|
|||||||
## 0.5.1 (unreleased)
|
## 0.5.1 (unreleased)
|
||||||
|
|
||||||
- Added check for MVCC-compliant snapshot for HNSW index scans
|
|
||||||
- Improved performance of index scans for IVFFlat after updates and deletes
|
- Improved performance of index scans for IVFFlat after updates and deletes
|
||||||
|
- Fixed locking for index scans for HNSW
|
||||||
|
|
||||||
## 0.5.0 (2023-08-28)
|
## 0.5.0 (2023-08-28)
|
||||||
|
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -3,8 +3,8 @@ EXTVERSION = 0.5.0
|
|||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
OBJS = 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/tinyint.o src/vector.o
|
OBJS = src/float4.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
|
||||||
HEADERS = src/tinyint.h src/vector.h
|
HEADERS = 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.5.0
|
EXTVERSION = 0.5.0
|
||||||
|
|
||||||
OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\tinyint.obj src\vector.obj
|
OBJS = src\float4.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
|
||||||
HEADERS = src\tinyint.h src\vector.h
|
HEADERS = 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)
|
||||||
@@ -56,7 +56,7 @@ install:
|
|||||||
copy $(EXTENSION).control "$(SHAREDIR)\extension"
|
copy $(EXTENSION).control "$(SHAREDIR)\extension"
|
||||||
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
|
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
|
||||||
mkdir "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
mkdir "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||||
for %f in ($(HEADERS)) do copy %f "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
copy $(HEADERS) "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||||
|
|
||||||
installcheck:
|
installcheck:
|
||||||
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
|
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
|
||||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.5.1'" to load this file. \quit
|
|
||||||
|
|
||||||
-- tinyint
|
|
||||||
|
|
||||||
CREATE TYPE tinyint;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_in(cstring, oid, integer) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_out(tinyint) RETURNS cstring
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_recv(internal, oid, integer) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_send(tinyint) RETURNS bytea
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE TYPE tinyint (
|
|
||||||
INPUT = tinyint_in,
|
|
||||||
OUTPUT = tinyint_out,
|
|
||||||
RECEIVE = tinyint_recv,
|
|
||||||
SEND = tinyint_send,
|
|
||||||
INTERNALLENGTH = 1,
|
|
||||||
PASSEDBYVALUE,
|
|
||||||
ALIGNMENT = char
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE FUNCTION integer_to_tinyint(integer, integer, boolean) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION numeric_to_tinyint(numeric, integer, boolean) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE CAST (integer AS tinyint)
|
|
||||||
WITH FUNCTION integer_to_tinyint(integer, integer, boolean) AS IMPLICIT;
|
|
||||||
|
|
||||||
CREATE CAST (numeric AS tinyint)
|
|
||||||
WITH FUNCTION numeric_to_tinyint(numeric, integer, boolean) AS IMPLICIT;
|
|
||||||
|
|
||||||
CREATE FUNCTION l2_distance(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION inner_product(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION cosine_distance(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_negative_inner_product(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE OPERATOR <-> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = l2_distance,
|
|
||||||
COMMUTATOR = '<->'
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE OPERATOR <#> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = tinyint_negative_inner_product,
|
|
||||||
COMMUTATOR = '<#>'
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE OPERATOR <=> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = cosine_distance,
|
|
||||||
COMMUTATOR = '<=>'
|
|
||||||
);
|
|
||||||
@@ -34,6 +34,9 @@ CREATE TYPE vector (
|
|||||||
CREATE FUNCTION l2_distance(vector, vector) RETURNS float8
|
CREATE FUNCTION l2_distance(vector, vector) RETURNS float8
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION l2_distance(float4[], float4[]) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME', 'float4_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION inner_product(vector, vector) RETURNS float8
|
CREATE FUNCTION inner_product(vector, vector) RETURNS float8
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
@@ -84,6 +87,9 @@ CREATE FUNCTION vector_cmp(vector, vector) RETURNS int4
|
|||||||
CREATE FUNCTION vector_l2_squared_distance(vector, vector) RETURNS float8
|
CREATE FUNCTION vector_l2_squared_distance(vector, vector) RETURNS float8
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION float4_l2_squared_distance(float4[], float4[]) RETURNS float8
|
||||||
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
CREATE FUNCTION vector_negative_inner_product(vector, vector) RETURNS float8
|
CREATE FUNCTION vector_negative_inner_product(vector, vector) RETURNS float8
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
@@ -164,6 +170,11 @@ CREATE OPERATOR <-> (
|
|||||||
COMMUTATOR = '<->'
|
COMMUTATOR = '<->'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = float4[], RIGHTARG = float4[], PROCEDURE = l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
CREATE OPERATOR <#> (
|
CREATE OPERATOR <#> (
|
||||||
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_negative_inner_product,
|
LEFTARG = vector, RIGHTARG = vector, PROCEDURE = vector_negative_inner_product,
|
||||||
COMMUTATOR = '<#>'
|
COMMUTATOR = '<#>'
|
||||||
@@ -280,6 +291,11 @@ CREATE OPERATOR CLASS vector_l2_ops
|
|||||||
OPERATOR 1 <-> (vector, vector) FOR ORDER BY float_ops,
|
OPERATOR 1 <-> (vector, vector) FOR ORDER BY float_ops,
|
||||||
FUNCTION 1 vector_l2_squared_distance(vector, vector);
|
FUNCTION 1 vector_l2_squared_distance(vector, vector);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS float4_l2_ops
|
||||||
|
FOR TYPE float4[] USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (float4[], float4[]) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 float4_l2_squared_distance(float4[], float4[]);
|
||||||
|
|
||||||
CREATE OPERATOR CLASS vector_ip_ops
|
CREATE OPERATOR CLASS vector_ip_ops
|
||||||
FOR TYPE vector USING hnsw AS
|
FOR TYPE vector USING hnsw AS
|
||||||
OPERATOR 1 <#> (vector, vector) FOR ORDER BY float_ops,
|
OPERATOR 1 <#> (vector, vector) FOR ORDER BY float_ops,
|
||||||
@@ -290,68 +306,3 @@ CREATE OPERATOR CLASS vector_cosine_ops
|
|||||||
OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_ops,
|
OPERATOR 1 <=> (vector, vector) FOR ORDER BY float_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);
|
||||||
|
|
||||||
-- tinyint
|
|
||||||
|
|
||||||
CREATE TYPE tinyint;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_in(cstring, oid, integer) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_out(tinyint) RETURNS cstring
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_recv(internal, oid, integer) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_send(tinyint) RETURNS bytea
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE TYPE tinyint (
|
|
||||||
INPUT = tinyint_in,
|
|
||||||
OUTPUT = tinyint_out,
|
|
||||||
RECEIVE = tinyint_recv,
|
|
||||||
SEND = tinyint_send,
|
|
||||||
INTERNALLENGTH = 1,
|
|
||||||
PASSEDBYVALUE,
|
|
||||||
ALIGNMENT = char
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE FUNCTION integer_to_tinyint(integer, integer, boolean) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION numeric_to_tinyint(numeric, integer, boolean) RETURNS tinyint
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE CAST (integer AS tinyint)
|
|
||||||
WITH FUNCTION integer_to_tinyint(integer, integer, boolean) AS IMPLICIT;
|
|
||||||
|
|
||||||
CREATE CAST (numeric AS tinyint)
|
|
||||||
WITH FUNCTION numeric_to_tinyint(numeric, integer, boolean) AS IMPLICIT;
|
|
||||||
|
|
||||||
CREATE FUNCTION l2_distance(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_l2_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION inner_product(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_inner_product' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION cosine_distance(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME', 'tinyint_cosine_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE FUNCTION tinyint_negative_inner_product(tinyint[], tinyint[]) RETURNS float8
|
|
||||||
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
|
||||||
|
|
||||||
CREATE OPERATOR <-> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = l2_distance,
|
|
||||||
COMMUTATOR = '<->'
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE OPERATOR <#> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = tinyint_negative_inner_product,
|
|
||||||
COMMUTATOR = '<#>'
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE OPERATOR <=> (
|
|
||||||
LEFTARG = tinyint[], RIGHTARG = tinyint[], PROCEDURE = cosine_distance,
|
|
||||||
COMMUTATOR = '<=>'
|
|
||||||
);
|
|
||||||
|
|||||||
60
src/float4.c
Normal file
60
src/float4.c
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
#include "postgres.h"
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "utils/array.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 distance between vectors
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(float4_l2_distance);
|
||||||
|
Datum
|
||||||
|
float4_l2_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||||
|
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||||
|
float *ax = (float *) ARR_DATA_PTR(a);
|
||||||
|
float *bx = (float *) ARR_DATA_PTR(b);
|
||||||
|
float distance = 0.0;
|
||||||
|
float diff;
|
||||||
|
|
||||||
|
/* TODO Check rank, dimensions, and nulls */
|
||||||
|
int dim = ARR_DIMS(a)[0];
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
diff = ax[i] - bx[i];
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8(sqrt((double) distance));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the L2 squared distance between vectors
|
||||||
|
* This saves a sqrt calculation
|
||||||
|
*/
|
||||||
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(float4_l2_squared_distance);
|
||||||
|
Datum
|
||||||
|
float4_l2_squared_distance(PG_FUNCTION_ARGS)
|
||||||
|
{
|
||||||
|
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
||||||
|
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
||||||
|
float *ax = (float *) ARR_DATA_PTR(a);
|
||||||
|
float *bx = (float *) ARR_DATA_PTR(b);
|
||||||
|
float distance = 0.0;
|
||||||
|
float diff;
|
||||||
|
|
||||||
|
/* TODO Check rank, dimensions, and nulls */
|
||||||
|
int dim = ARR_DIMS(a)[0];
|
||||||
|
|
||||||
|
/* Auto-vectorized */
|
||||||
|
for (int i = 0; i < dim; i++)
|
||||||
|
{
|
||||||
|
diff = ax[i] - bx[i];
|
||||||
|
distance += diff * diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
PG_RETURN_FLOAT8((double) distance);
|
||||||
|
}
|
||||||
@@ -33,6 +33,12 @@ HnswInit(void)
|
|||||||
HNSW_DEFAULT_EF_CONSTRUCTION, HNSW_MIN_EF_CONSTRUCTION, HNSW_MAX_EF_CONSTRUCTION
|
HNSW_DEFAULT_EF_CONSTRUCTION, HNSW_MIN_EF_CONSTRUCTION, HNSW_MAX_EF_CONSTRUCTION
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
,AccessExclusiveLock
|
,AccessExclusiveLock
|
||||||
|
#endif
|
||||||
|
);
|
||||||
|
add_int_reloption(hnsw_relopt_kind, "dimensions", "Number of dimensions",
|
||||||
|
HNSW_DEFAULT_DIMENSIONS, HNSW_MIN_DIMENSIONS, HNSW_MAX_DIMENSIONS
|
||||||
|
#if PG_VERSION_NUM >= 130000
|
||||||
|
,AccessExclusiveLock
|
||||||
#endif
|
#endif
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -125,6 +131,7 @@ hnswoptions(Datum reloptions, bool validate)
|
|||||||
static const relopt_parse_elt tab[] = {
|
static const relopt_parse_elt tab[] = {
|
||||||
{"m", RELOPT_TYPE_INT, offsetof(HnswOptions, m)},
|
{"m", RELOPT_TYPE_INT, offsetof(HnswOptions, m)},
|
||||||
{"ef_construction", RELOPT_TYPE_INT, offsetof(HnswOptions, efConstruction)},
|
{"ef_construction", RELOPT_TYPE_INT, offsetof(HnswOptions, efConstruction)},
|
||||||
|
{"dimensions", RELOPT_TYPE_INT, offsetof(HnswOptions, dimensions)},
|
||||||
};
|
};
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
#if PG_VERSION_NUM >= 130000
|
||||||
|
|||||||
14
src/hnsw.h
14
src/hnsw.h
@@ -42,6 +42,9 @@
|
|||||||
#define HNSW_DEFAULT_EF_SEARCH 40
|
#define HNSW_DEFAULT_EF_SEARCH 40
|
||||||
#define HNSW_MIN_EF_SEARCH 1
|
#define HNSW_MIN_EF_SEARCH 1
|
||||||
#define HNSW_MAX_EF_SEARCH 1000
|
#define HNSW_MAX_EF_SEARCH 1000
|
||||||
|
#define HNSW_DEFAULT_DIMENSIONS -1
|
||||||
|
#define HNSW_MIN_DIMENSIONS 1
|
||||||
|
#define HNSW_MAX_DIMENSIONS HNSW_MAX_DIM
|
||||||
|
|
||||||
/* Tuple types */
|
/* Tuple types */
|
||||||
#define HNSW_ELEMENT_TUPLE_TYPE 1
|
#define HNSW_ELEMENT_TUPLE_TYPE 1
|
||||||
@@ -57,9 +60,7 @@
|
|||||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||||
#define PROGRESS_HNSW_PHASE_LOAD 2
|
#define PROGRESS_HNSW_PHASE_LOAD 2
|
||||||
|
|
||||||
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
#define HNSW_ELEMENT_TUPLE_SIZE(_datum) MAXALIGN(offsetof(HnswElementTupleData, value) + VARSIZE_ANY(_datum))
|
||||||
|
|
||||||
#define HNSW_ELEMENT_TUPLE_SIZE(_dim) MAXALIGN(offsetof(HnswElementTupleData, vec) + VECTOR_SIZE(_dim))
|
|
||||||
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
||||||
|
|
||||||
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
||||||
@@ -98,12 +99,13 @@ typedef struct HnswElementData
|
|||||||
List *heaptids;
|
List *heaptids;
|
||||||
uint8 level;
|
uint8 level;
|
||||||
uint8 deleted;
|
uint8 deleted;
|
||||||
|
bool loaded;
|
||||||
HnswNeighborArray *neighbors;
|
HnswNeighborArray *neighbors;
|
||||||
BlockNumber blkno;
|
BlockNumber blkno;
|
||||||
OffsetNumber offno;
|
OffsetNumber offno;
|
||||||
OffsetNumber neighborOffno;
|
OffsetNumber neighborOffno;
|
||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
Vector *vec;
|
Datum value;
|
||||||
} HnswElementData;
|
} HnswElementData;
|
||||||
|
|
||||||
typedef HnswElementData * HnswElement;
|
typedef HnswElementData * HnswElement;
|
||||||
@@ -132,6 +134,7 @@ typedef struct HnswOptions
|
|||||||
int32 vl_len_; /* varlena header (do not touch directly!) */
|
int32 vl_len_; /* varlena header (do not touch directly!) */
|
||||||
int m; /* number of connections */
|
int m; /* number of connections */
|
||||||
int efConstruction; /* size of dynamic candidate list */
|
int efConstruction; /* size of dynamic candidate list */
|
||||||
|
int dimensions;
|
||||||
} HnswOptions;
|
} HnswOptions;
|
||||||
|
|
||||||
typedef struct HnswBuildState
|
typedef struct HnswBuildState
|
||||||
@@ -202,7 +205,7 @@ typedef struct HnswElementTupleData
|
|||||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
||||||
ItemPointerData neighbortid;
|
ItemPointerData neighbortid;
|
||||||
uint16 unused2;
|
uint16 unused2;
|
||||||
Vector vec;
|
char value[FLEXIBLE_ARRAY_MEMBER];
|
||||||
} HnswElementTupleData;
|
} HnswElementTupleData;
|
||||||
|
|
||||||
typedef HnswElementTupleData * HnswElementTuple;
|
typedef HnswElementTupleData * HnswElementTuple;
|
||||||
@@ -260,6 +263,7 @@ typedef struct HnswVacuumState
|
|||||||
/* Methods */
|
/* Methods */
|
||||||
int HnswGetM(Relation index);
|
int HnswGetM(Relation index);
|
||||||
int HnswGetEfConstruction(Relation index);
|
int HnswGetEfConstruction(Relation index);
|
||||||
|
int HnswGetDimensions(Relation index);
|
||||||
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
||||||
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||||
void HnswCommitBuffer(Buffer buf, GenericXLogState *state);
|
void HnswCommitBuffer(Buffer buf, GenericXLogState *state);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include "lib/pairingheap.h"
|
#include "lib/pairingheap.h"
|
||||||
#include "nodes/pg_list.h"
|
#include "nodes/pg_list.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
|
#include "utils/datum.h"
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
@@ -81,6 +82,7 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **
|
|||||||
HnswPageGetOpaque(*page)->nextblkno = BufferGetBlockNumber(newbuf);
|
HnswPageGetOpaque(*page)->nextblkno = BufferGetBlockNumber(newbuf);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(*buf);
|
||||||
GenericXLogFinish(*state);
|
GenericXLogFinish(*state);
|
||||||
UnlockReleaseBuffer(*buf);
|
UnlockReleaseBuffer(*buf);
|
||||||
|
|
||||||
@@ -105,8 +107,6 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
int dimensions = buildstate->dimensions;
|
|
||||||
Size etupSize;
|
|
||||||
Size maxSize;
|
Size maxSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
@@ -117,12 +117,11 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
ListCell *lc;
|
ListCell *lc;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
etup = palloc0(etupSize);
|
etup = palloc0(maxSize);
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(maxSize);
|
||||||
|
|
||||||
/* Prepare first page */
|
/* Prepare first page */
|
||||||
buf = HnswNewBuffer(index, forkNum);
|
buf = HnswNewBuffer(index, forkNum);
|
||||||
@@ -133,12 +132,14 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
foreach(lc, buildstate->elements)
|
foreach(lc, buildstate->elements)
|
||||||
{
|
{
|
||||||
HnswElement element = lfirst(lc);
|
HnswElement element = lfirst(lc);
|
||||||
|
Size etupSize;
|
||||||
Size ntupSize;
|
Size ntupSize;
|
||||||
Size combinedSize;
|
Size combinedSize;
|
||||||
|
|
||||||
HnswSetElementTuple(etup, element);
|
HnswSetElementTuple(etup, element);
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(element->value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
|
|
||||||
@@ -178,6 +179,7 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
insertPage = BufferGetBlockNumber(buf);
|
insertPage = BufferGetBlockNumber(buf);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
@@ -225,6 +227,7 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -273,18 +276,15 @@ InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState *
|
|||||||
int m = buildstate->m;
|
int m = buildstate->m;
|
||||||
|
|
||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
element->value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(buildstate->normprocinfo, collation, &value, buildstate->normvec))
|
if (!HnswNormValue(buildstate->normprocinfo, collation, &element->value, buildstate->normvec))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Copy value to element so accessible outside of memory context */
|
|
||||||
memcpy(element->vec, DatumGetVector(value), VECTOR_SIZE(buildstate->dimensions));
|
|
||||||
|
|
||||||
/* Insert element in graph */
|
/* Insert element in graph */
|
||||||
HnswInsertElement(element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
HnswInsertElement(element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
@@ -360,7 +360,6 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
|
|
||||||
/* Allocate necessary memory outside of memory context */
|
/* Allocate necessary memory outside of memory context */
|
||||||
element = HnswInitElement(tid, buildstate->m, buildstate->ml, buildstate->maxLevel);
|
element = HnswInitElement(tid, buildstate->m, buildstate->ml, buildstate->maxLevel);
|
||||||
element->vec = palloc(VECTOR_SIZE(buildstate->dimensions));
|
|
||||||
|
|
||||||
/* Use memory context since detoast can allocate */
|
/* Use memory context since detoast can allocate */
|
||||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
@@ -368,9 +367,8 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
/* Insert tuple */
|
/* Insert tuple */
|
||||||
inserted = InsertTuple(index, values, element, buildstate, &dup);
|
inserted = InsertTuple(index, values, element, buildstate, &dup);
|
||||||
|
|
||||||
/* Reset memory context */
|
/* Switch memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
MemoryContextReset(buildstate->tmpCtx);
|
|
||||||
|
|
||||||
/* Add outside memory context */
|
/* Add outside memory context */
|
||||||
if (dup != NULL)
|
if (dup != NULL)
|
||||||
@@ -378,9 +376,16 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
|
|
||||||
/* Add to buildstate or free */
|
/* Add to buildstate or free */
|
||||||
if (inserted)
|
if (inserted)
|
||||||
|
{
|
||||||
|
element->value = datumCopy(element->value, false, -1);
|
||||||
|
element->loaded = true;
|
||||||
buildstate->elements = lappend(buildstate->elements, element);
|
buildstate->elements = lappend(buildstate->elements, element);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
HnswFreeElement(element);
|
HnswFreeElement(element);
|
||||||
|
|
||||||
|
/* Reset memory context */
|
||||||
|
MemoryContextReset(buildstate->tmpCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -395,6 +400,7 @@ HnswGetMaxInMemoryElements(int m, double ml, int dimensions)
|
|||||||
elementSize += sizeof(HnswNeighborArray) * (avgLevel + 1);
|
elementSize += sizeof(HnswNeighborArray) * (avgLevel + 1);
|
||||||
elementSize += sizeof(HnswCandidate) * (m * (avgLevel + 2));
|
elementSize += sizeof(HnswCandidate) * (m * (avgLevel + 2));
|
||||||
elementSize += sizeof(ItemPointerData);
|
elementSize += sizeof(ItemPointerData);
|
||||||
|
/* TODO Handle non-vector types */
|
||||||
elementSize += VECTOR_SIZE(dimensions);
|
elementSize += VECTOR_SIZE(dimensions);
|
||||||
return (maintenance_work_mem * 1024L) / elementSize;
|
return (maintenance_work_mem * 1024L) / elementSize;
|
||||||
}
|
}
|
||||||
@@ -412,6 +418,9 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
|
|
||||||
buildstate->m = HnswGetM(index);
|
buildstate->m = HnswGetM(index);
|
||||||
buildstate->efConstruction = HnswGetEfConstruction(index);
|
buildstate->efConstruction = HnswGetEfConstruction(index);
|
||||||
|
buildstate->dimensions = HnswGetDimensions(index);
|
||||||
|
|
||||||
|
if (buildstate->dimensions < 0)
|
||||||
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
||||||
|
|
||||||
/* Require column to have dimensions to be indexed */
|
/* Require column to have dimensions to be indexed */
|
||||||
|
|||||||
@@ -123,7 +123,6 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
Size minCombinedSize;
|
Size minCombinedSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
BlockNumber currentPage = insertPage;
|
BlockNumber currentPage = insertPage;
|
||||||
int dimensions = e->vec->dim;
|
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
Buffer nbuf;
|
Buffer nbuf;
|
||||||
Page npage;
|
Page npage;
|
||||||
@@ -132,10 +131,10 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(e->value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||||
minCombinedSize = etupSize + HNSW_NEIGHBOR_TUPLE_SIZE(0, m) + sizeof(ItemIdData);
|
minCombinedSize = etupSize + HNSW_NEIGHBOR_TUPLE_SIZE(0, m) + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* Prepare element tuple */
|
/* Prepare element tuple */
|
||||||
@@ -202,6 +201,8 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
HnswInsertAppendPage(index, &newbuf, &newpage, state, page);
|
HnswInsertAppendPage(index, &newbuf, &newpage, state, page);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(newbuf);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
|
|
||||||
/* Unlock previous buffer */
|
/* Unlock previous buffer */
|
||||||
@@ -268,6 +269,9 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
|
if (nbuf != buf)
|
||||||
|
MarkBufferDirty(nbuf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
if (nbuf != buf)
|
if (nbuf != buf)
|
||||||
@@ -386,6 +390,7 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -405,7 +410,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
|||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(dup->vec->dim);
|
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(dup->value);
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
int i;
|
int i;
|
||||||
|
|
||||||
@@ -439,6 +444,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
@@ -515,7 +521,7 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
|
|
||||||
/* Create an element */
|
/* Create an element */
|
||||||
element = HnswInitElement(heap_tid, m, HnswGetMl(m), HnswGetMaxLevel(m));
|
element = HnswInitElement(heap_tid, m, HnswGetMl(m), HnswGetMaxLevel(m));
|
||||||
element->vec = DatumGetVector(value);
|
element->value = value;
|
||||||
|
|
||||||
/* Prevent concurrent inserts when likely updating entry point */
|
/* Prevent concurrent inserts when likely updating entry point */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
|
|||||||
@@ -113,6 +113,12 @@ hnswbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
|
|
||||||
scan->opaque = so;
|
scan->opaque = so;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
||||||
|
* before marking tuples as deleted.
|
||||||
|
*/
|
||||||
|
LockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||||
|
|
||||||
return scan;
|
return scan;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,25 +166,11 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
if (scan->orderByData == NULL)
|
if (scan->orderByData == NULL)
|
||||||
elog(ERROR, "cannot scan hnsw index without order");
|
elog(ERROR, "cannot scan hnsw index without order");
|
||||||
|
|
||||||
/* Requires MVCC-compliant snapshot as not able to maintain a pin */
|
|
||||||
/* https://www.postgresql.org/docs/current/index-locking.html */
|
|
||||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
|
||||||
elog(ERROR, "non-MVCC snapshots are not supported with hnsw");
|
|
||||||
|
|
||||||
/* Get scan value */
|
/* Get scan value */
|
||||||
value = GetScanValue(scan);
|
value = GetScanValue(scan);
|
||||||
|
|
||||||
/*
|
|
||||||
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
|
||||||
* before marking tuples as deleted.
|
|
||||||
*/
|
|
||||||
LockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
|
||||||
|
|
||||||
so->w = GetScanItems(scan, value);
|
so->w = GetScanItems(scan, value);
|
||||||
|
|
||||||
/* Release shared lock */
|
|
||||||
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
|
||||||
|
|
||||||
so->first = false;
|
so->first = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,6 +198,15 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
scan->xs_ctup.t_self = *heaptid;
|
scan->xs_ctup.t_self = *heaptid;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Typically, an index scan must maintain a pin on the index page
|
||||||
|
* holding the item last returned by amgettuple. However, this is not
|
||||||
|
* needed with the current vacuum strategy, which ensures scans do not
|
||||||
|
* visit tuples in danger of being marked as deleted.
|
||||||
|
*
|
||||||
|
* https://www.postgresql.org/docs/current/index-locking.html
|
||||||
|
*/
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -222,6 +223,9 @@ hnswendscan(IndexScanDesc scan)
|
|||||||
{
|
{
|
||||||
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
||||||
|
|
||||||
|
/* Release shared lock */
|
||||||
|
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
|
||||||
|
|
||||||
MemoryContextDelete(so->tmpCtx);
|
MemoryContextDelete(so->tmpCtx);
|
||||||
|
|
||||||
pfree(so);
|
pfree(so);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
|
#include "utils/datum.h"
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -34,6 +35,20 @@ HnswGetEfConstruction(Relation index)
|
|||||||
return HNSW_DEFAULT_EF_CONSTRUCTION;
|
return HNSW_DEFAULT_EF_CONSTRUCTION;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the number of dimensions in the index
|
||||||
|
*/
|
||||||
|
int
|
||||||
|
HnswGetDimensions(Relation index)
|
||||||
|
{
|
||||||
|
HnswOptions *opts = (HnswOptions *) index->rd_options;
|
||||||
|
|
||||||
|
if (opts)
|
||||||
|
return opts->dimensions;
|
||||||
|
|
||||||
|
return HNSW_DEFAULT_DIMENSIONS;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get proc
|
* Get proc
|
||||||
*/
|
*/
|
||||||
@@ -117,6 +132,7 @@ HnswInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState *
|
|||||||
void
|
void
|
||||||
HnswCommitBuffer(Buffer buf, GenericXLogState *state)
|
HnswCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||||
{
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -186,7 +202,8 @@ HnswFreeElement(HnswElement element)
|
|||||||
{
|
{
|
||||||
HnswFreeNeighbors(element);
|
HnswFreeNeighbors(element);
|
||||||
list_free_deep(element->heaptids);
|
list_free_deep(element->heaptids);
|
||||||
pfree(element->vec);
|
if (element->loaded)
|
||||||
|
pfree(DatumGetPointer(element->value));
|
||||||
pfree(element);
|
pfree(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +230,7 @@ HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno)
|
|||||||
element->blkno = blkno;
|
element->blkno = blkno;
|
||||||
element->offno = offno;
|
element->offno = offno;
|
||||||
element->neighbors = NULL;
|
element->neighbors = NULL;
|
||||||
element->vec = NULL;
|
element->loaded = false;
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,7 +340,7 @@ HnswSetElementTuple(HnswElementTuple etup, HnswElement element)
|
|||||||
else
|
else
|
||||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||||
}
|
}
|
||||||
memcpy(&etup->vec, element->vec, VECTOR_SIZE(element->vec->dim));
|
memcpy(&etup->value, DatumGetPointer(element->value), VARSIZE_ANY(element->value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -446,8 +463,10 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
|||||||
|
|
||||||
if (loadVec)
|
if (loadVec)
|
||||||
{
|
{
|
||||||
element->vec = palloc(VECTOR_SIZE(etup->vec.dim));
|
Datum value = PointerGetDatum(&etup->value);
|
||||||
memcpy(element->vec, &etup->vec, VECTOR_SIZE(etup->vec.dim));
|
|
||||||
|
element->value = datumCopy(value, false, -1);
|
||||||
|
element->loaded = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -475,7 +494,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
|||||||
|
|
||||||
/* Calculate distance */
|
/* Calculate distance */
|
||||||
if (distance != NULL)
|
if (distance != NULL)
|
||||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->vec)));
|
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->value)));
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -486,7 +505,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
|||||||
static float
|
static float
|
||||||
GetCandidateDistance(HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
GetCandidateDistance(HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, PointerGetDatum(hc->element->vec)));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, hc->element->value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -721,7 +740,7 @@ HnswGetDistance(HnswElement a, HnswElement b, int lc, FmgrInfo *procinfo, Oid co
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(a->vec), PointerGetDatum(b->vec)));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, a->value, b->value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -804,7 +823,7 @@ HnswFindDuplicate(HnswElement e)
|
|||||||
HnswCandidate *neighbor = &neighbors->items[i];
|
HnswCandidate *neighbor = &neighbors->items[i];
|
||||||
|
|
||||||
/* Exit early since ordered by distance */
|
/* Exit early since ordered by distance */
|
||||||
if (vector_cmp_internal(e->vec, neighbor->element->vec) != 0)
|
if (!datumIsEqual(e->value, neighbor->element->value, false, -1))
|
||||||
break;
|
break;
|
||||||
|
|
||||||
/* Check for space */
|
/* Check for space */
|
||||||
@@ -879,13 +898,13 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
|||||||
/* Load elements on insert */
|
/* Load elements on insert */
|
||||||
if (index != NULL)
|
if (index != NULL)
|
||||||
{
|
{
|
||||||
Datum q = PointerGetDatum(hc->element->vec);
|
Datum q = hc->element->value;
|
||||||
|
|
||||||
for (int i = 0; i < currentNeighbors->length; i++)
|
for (int i = 0; i < currentNeighbors->length; i++)
|
||||||
{
|
{
|
||||||
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
||||||
|
|
||||||
if (hc3->element->vec == NULL)
|
if (!hc3->element->loaded)
|
||||||
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
||||||
else
|
else
|
||||||
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
||||||
@@ -967,7 +986,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
|||||||
List *w;
|
List *w;
|
||||||
int level = element->level;
|
int level = element->level;
|
||||||
int entryLevel;
|
int entryLevel;
|
||||||
Datum q = PointerGetDatum(element->vec);
|
Datum q = element->value;
|
||||||
HnswElement skipElement = existing ? element : NULL;
|
HnswElement skipElement = existing ? element : NULL;
|
||||||
|
|
||||||
/* No neighbors if no entry point */
|
/* No neighbors if no entry point */
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
if (itemUpdated)
|
if (itemUpdated)
|
||||||
{
|
{
|
||||||
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(PointerGetDatum(&etup->value));
|
||||||
|
|
||||||
/* Mark rest as invalid */
|
/* Mark rest as invalid */
|
||||||
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
||||||
@@ -128,7 +128,10 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
blkno = HnswPageGetOpaque(page)->nextblkno;
|
blkno = HnswPageGetOpaque(page)->nextblkno;
|
||||||
|
|
||||||
if (updated)
|
if (updated)
|
||||||
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
GenericXLogAbort(state);
|
GenericXLogAbort(state);
|
||||||
|
|
||||||
@@ -226,6 +229,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
@@ -481,6 +485,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
Size etupSize;
|
Size etupSize;
|
||||||
Size ntupSize;
|
Size ntupSize;
|
||||||
|
Datum value;
|
||||||
Buffer nbuf;
|
Buffer nbuf;
|
||||||
Page npage;
|
Page npage;
|
||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
@@ -504,8 +509,11 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
if (ItemPointerIsValid(&etup->heaptids[0]))
|
if (ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
/* Get datum */
|
||||||
|
value = PointerGetDatum(&etup->value);
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
||||||
|
|
||||||
/* Get neighbor page */
|
/* Get neighbor page */
|
||||||
@@ -528,7 +536,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
/* Overwrite element */
|
/* Overwrite element */
|
||||||
etup->deleted = 1;
|
etup->deleted = 1;
|
||||||
MemSet(&etup->vec.x, 0, etup->vec.dim * sizeof(float));
|
MemSet(&etup->value, 0, VARSIZE_ANY(value));
|
||||||
|
|
||||||
/* Overwrite neighbors */
|
/* Overwrite neighbors */
|
||||||
for (int i = 0; i < ntup->count; i++)
|
for (int i = 0; i < ntup->count; i++)
|
||||||
@@ -543,6 +551,9 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
|
if (nbuf != buf)
|
||||||
|
MarkBufferDirty(nbuf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
if (nbuf != buf)
|
if (nbuf != buf)
|
||||||
UnlockReleaseBuffer(nbuf);
|
UnlockReleaseBuffer(nbuf);
|
||||||
|
|||||||
@@ -506,11 +506,9 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
Size listSize;
|
|
||||||
IvfflatList list;
|
IvfflatList list;
|
||||||
|
|
||||||
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
list = palloc0(BLCKSZ);
|
||||||
list = palloc(listSize);
|
|
||||||
|
|
||||||
buf = IvfflatNewBuffer(index, forkNum);
|
buf = IvfflatNewBuffer(index, forkNum);
|
||||||
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
||||||
@@ -518,11 +516,13 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
for (int i = 0; i < lists; i++)
|
for (int i = 0; i < lists; i++)
|
||||||
{
|
{
|
||||||
OffsetNumber offno;
|
OffsetNumber offno;
|
||||||
|
Datum center = PointerGetDatum(VectorArrayGet(centers, i));
|
||||||
|
Size listSize = MAXALIGN(IVFFLAT_LIST_SIZE(center));
|
||||||
|
|
||||||
/* Load list */
|
/* Load list */
|
||||||
list->startPage = InvalidBlockNumber;
|
list->startPage = InvalidBlockNumber;
|
||||||
list->insertPage = InvalidBlockNumber;
|
list->insertPage = InvalidBlockNumber;
|
||||||
memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
|
memcpy(&list->center, DatumGetPointer(center), VARSIZE_ANY(center));
|
||||||
|
|
||||||
/* Ensure free space */
|
/* Ensure free space */
|
||||||
if (PageGetFreeSpace(page) < listSize)
|
if (PageGetFreeSpace(page) < listSize)
|
||||||
|
|||||||
@@ -52,7 +52,7 @@
|
|||||||
#define PROGRESS_IVFFLAT_PHASE_ASSIGN 3
|
#define PROGRESS_IVFFLAT_PHASE_ASSIGN 3
|
||||||
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
|
#define PROGRESS_IVFFLAT_PHASE_LOAD 4
|
||||||
|
|
||||||
#define IVFFLAT_LIST_SIZE(_dim) (offsetof(IvfflatListData, center) + VECTOR_SIZE(_dim))
|
#define IVFFLAT_LIST_SIZE(_datum) (offsetof(IvfflatListData, center) + VARSIZE_ANY(_datum))
|
||||||
|
|
||||||
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
|
#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque) PageGetSpecialPointer(page))
|
||||||
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
|
#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *) PageGetContents(page))
|
||||||
@@ -229,7 +229,7 @@ typedef struct IvfflatListData
|
|||||||
{
|
{
|
||||||
BlockNumber startPage;
|
BlockNumber startPage;
|
||||||
BlockNumber insertPage;
|
BlockNumber insertPage;
|
||||||
Vector center;
|
char center[FLEXIBLE_ARRAY_MEMBER];
|
||||||
} IvfflatListData;
|
} IvfflatListData;
|
||||||
|
|
||||||
typedef IvfflatListData * IvfflatList;
|
typedef IvfflatListData * IvfflatList;
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
|
|
||||||
/* Get tuple size */
|
/* Get tuple size */
|
||||||
itemsz = MAXALIGN(IndexTupleSize(itup));
|
itemsz = MAXALIGN(IndexTupleSize(itup));
|
||||||
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)) - sizeof(ItemIdData));
|
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
|
||||||
|
|
||||||
/* Find a page to insert the item */
|
/* Find a page to insert the item */
|
||||||
for (;;)
|
for (;;)
|
||||||
@@ -142,6 +142,8 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
|
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(newbuf);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
|
|
||||||
/* Unlock previous buffer */
|
/* Unlock previous buffer */
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogStat
|
|||||||
void
|
void
|
||||||
IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
|
IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||||
{
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -159,6 +160,8 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
|
|||||||
IvfflatInitPage(newbuf, newpage);
|
IvfflatInitPage(newbuf, newpage);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(*buf);
|
||||||
|
MarkBufferDirty(newbuf);
|
||||||
GenericXLogFinish(*state);
|
GenericXLogFinish(*state);
|
||||||
|
|
||||||
/* Unlock */
|
/* Unlock */
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
|||||||
{
|
{
|
||||||
/* Delete tuples */
|
/* Delete tuples */
|
||||||
PageIndexMultiDelete(page, deletable, ndeletable);
|
PageIndexMultiDelete(page, deletable, ndeletable);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|||||||
294
src/tinyint.c
294
src/tinyint.c
@@ -1,294 +0,0 @@
|
|||||||
#include "postgres.h"
|
|
||||||
|
|
||||||
#include <math.h>
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
#include "fmgr.h"
|
|
||||||
#include "lib/stringinfo.h"
|
|
||||||
#include "libpq/pqformat.h"
|
|
||||||
#include "tinyint.h"
|
|
||||||
#include "utils/array.h"
|
|
||||||
#include "utils/builtins.h"
|
|
||||||
#include "utils/numeric.h"
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Check if array is a vector
|
|
||||||
*/
|
|
||||||
static bool
|
|
||||||
ArrayIsVector(ArrayType *a)
|
|
||||||
{
|
|
||||||
return ARR_NDIM(a) == 1 && !array_contains_nulls(a);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Check if dimensions are the same
|
|
||||||
*/
|
|
||||||
static int
|
|
||||||
CheckDims(ArrayType *a, ArrayType *b)
|
|
||||||
{
|
|
||||||
int dima;
|
|
||||||
int dimb;
|
|
||||||
|
|
||||||
if (!ArrayIsVector(a) || !ArrayIsVector(b))
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
dima = ARR_DIMS(a)[0];
|
|
||||||
dimb = ARR_DIMS(b)[0];
|
|
||||||
|
|
||||||
if (dima != dimb)
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
return dima;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Check range
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
CheckRange(long i)
|
|
||||||
{
|
|
||||||
if (i < INT8_MIN || i > INT8_MAX)
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
|
||||||
errmsg("value \"%ld\" is out of range for type tinyint", i)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert textual representation to internal representation
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_in);
|
|
||||||
Datum
|
|
||||||
tinyint_in(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
char *s = PG_GETARG_CSTRING(0);
|
|
||||||
const char *ptr = s;
|
|
||||||
long i;
|
|
||||||
char *end;
|
|
||||||
|
|
||||||
/* skip leading spaces */
|
|
||||||
while (*ptr != '\0' && isspace((unsigned char) *ptr))
|
|
||||||
ptr++;
|
|
||||||
|
|
||||||
if (*ptr == '\0')
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
|
||||||
errmsg("invalid input syntax for type tinyint: \"%s\"", s)));
|
|
||||||
|
|
||||||
i = strtol(ptr, &end, 10);
|
|
||||||
ptr = end;
|
|
||||||
|
|
||||||
if (i < INT8_MIN || i > INT8_MAX)
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
|
||||||
errmsg("value \"%s\" is out of range for type tinyint", s)));
|
|
||||||
|
|
||||||
/* allow trailing whitespace, but not other trailing chars */
|
|
||||||
while (*ptr != '\0' && isspace((unsigned char) *ptr))
|
|
||||||
ptr++;
|
|
||||||
|
|
||||||
if (*ptr != '\0')
|
|
||||||
ereport(ERROR,
|
|
||||||
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
|
|
||||||
errmsg("invalid input syntax for type tinyint: \"%s\"", s)));
|
|
||||||
|
|
||||||
PG_RETURN_INT8(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert internal representation to textual representation
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_out);
|
|
||||||
Datum
|
|
||||||
tinyint_out(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
int8 num = PG_GETARG_INT8(0);
|
|
||||||
char *result = (char *) palloc(5); /* sign, 3 digits, '\0' */
|
|
||||||
|
|
||||||
pg_ltoa((int32) num, result);
|
|
||||||
PG_RETURN_CSTRING(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert external binary representation to internal representation
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_recv);
|
|
||||||
Datum
|
|
||||||
tinyint_recv(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
|
|
||||||
|
|
||||||
PG_RETURN_INT8((int8) pq_getmsgint(buf, sizeof(int8)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert internal representation to the external binary representation
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_send);
|
|
||||||
Datum
|
|
||||||
tinyint_send(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
int8 arg1 = PG_GETARG_INT8(0);
|
|
||||||
StringInfoData buf;
|
|
||||||
|
|
||||||
pq_begintypsend(&buf);
|
|
||||||
pq_sendint8(&buf, arg1);
|
|
||||||
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert integer to tinyint
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(integer_to_tinyint);
|
|
||||||
Datum
|
|
||||||
integer_to_tinyint(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
int32 i = PG_GETARG_INT32(0);
|
|
||||||
|
|
||||||
CheckRange(i);
|
|
||||||
|
|
||||||
PG_RETURN_INT8(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Convert numeric to tinyint
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(numeric_to_tinyint);
|
|
||||||
Datum
|
|
||||||
numeric_to_tinyint(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
Numeric num = PG_GETARG_NUMERIC(0);
|
|
||||||
int32 i = numeric_int4_opt_error(num, NULL);
|
|
||||||
|
|
||||||
CheckRange(i);
|
|
||||||
|
|
||||||
PG_RETURN_INT8(i);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the L2 distance between tinyint arrays
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_l2_distance);
|
|
||||||
Datum
|
|
||||||
tinyint_l2_distance(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
|
||||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
|
||||||
int8 *ax = (int8 *) ARR_DATA_PTR(a);
|
|
||||||
int8 *bx = (int8 *) ARR_DATA_PTR(b);
|
|
||||||
double distance = 0.0;
|
|
||||||
int dim = CheckDims(a, b);
|
|
||||||
|
|
||||||
/* TODO Decide on error or NULL */
|
|
||||||
if (!dim)
|
|
||||||
PG_RETURN_NULL();
|
|
||||||
|
|
||||||
/* Auto-vectorized */
|
|
||||||
for (int i = 0; i < dim; i++)
|
|
||||||
{
|
|
||||||
double diff = ax[i] - bx[i];
|
|
||||||
|
|
||||||
distance += diff * diff;
|
|
||||||
}
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8(sqrt(distance));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the inner product of two tinyint arrays
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_inner_product);
|
|
||||||
Datum
|
|
||||||
tinyint_inner_product(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
|
||||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
|
||||||
int8 *ax = (int8 *) ARR_DATA_PTR(a);
|
|
||||||
int8 *bx = (int8 *) ARR_DATA_PTR(b);
|
|
||||||
double distance = 0.0;
|
|
||||||
int dim = CheckDims(a, b);
|
|
||||||
|
|
||||||
/* TODO Decide on error or NULL */
|
|
||||||
if (!dim)
|
|
||||||
PG_RETURN_NULL();
|
|
||||||
|
|
||||||
/* Auto-vectorized */
|
|
||||||
for (int i = 0; i < dim; i++)
|
|
||||||
distance += ax[i] * bx[i];
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8(distance);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the negative inner product of two tinyint arrays
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_negative_inner_product);
|
|
||||||
Datum
|
|
||||||
tinyint_negative_inner_product(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
|
||||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
|
||||||
int8 *ax = (int8 *) ARR_DATA_PTR(a);
|
|
||||||
int8 *bx = (int8 *) ARR_DATA_PTR(b);
|
|
||||||
double distance = 0.0;
|
|
||||||
int dim = CheckDims(a, b);
|
|
||||||
|
|
||||||
/* TODO Decide on error or NULL */
|
|
||||||
if (!dim)
|
|
||||||
PG_RETURN_NULL();
|
|
||||||
|
|
||||||
/* Auto-vectorized */
|
|
||||||
for (int i = 0; i < dim; i++)
|
|
||||||
distance += ax[i] * bx[i];
|
|
||||||
|
|
||||||
PG_RETURN_FLOAT8(distance * -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the cosine distance between two float2 arrays
|
|
||||||
*/
|
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(tinyint_cosine_distance);
|
|
||||||
Datum
|
|
||||||
tinyint_cosine_distance(PG_FUNCTION_ARGS)
|
|
||||||
{
|
|
||||||
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
|
|
||||||
ArrayType *b = PG_GETARG_ARRAYTYPE_P(1);
|
|
||||||
int8 *ax = (int8 *) ARR_DATA_PTR(a);
|
|
||||||
int8 *bx = (int8 *) ARR_DATA_PTR(b);
|
|
||||||
double distance = 0.0;
|
|
||||||
double norma = 0.0;
|
|
||||||
double normb = 0.0;
|
|
||||||
double similarity;
|
|
||||||
int dim = CheckDims(a, b);
|
|
||||||
|
|
||||||
/* TODO Decide on error or NULL */
|
|
||||||
if (!dim)
|
|
||||||
PG_RETURN_NULL();
|
|
||||||
|
|
||||||
/* Auto-vectorized */
|
|
||||||
for (int i = 0; i < dim; i++)
|
|
||||||
{
|
|
||||||
float axi = ax[i];
|
|
||||||
float bxi = bx[i];
|
|
||||||
|
|
||||||
distance += axi * bxi;
|
|
||||||
norma += axi * axi;
|
|
||||||
normb += bxi * bxi;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
|
|
||||||
similarity = distance / sqrt(norma * 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);
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#ifndef TINYINT_H
|
|
||||||
#define TINYINT_H
|
|
||||||
|
|
||||||
#define DatumGetInt8(X) ((int8) (X))
|
|
||||||
#define PG_GETARG_INT8(n) DatumGetInt8(PG_GETARG_DATUM(n))
|
|
||||||
#define PG_RETURN_INT8(x) return Int8GetDatum(x)
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -74,65 +74,65 @@ SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
|||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
SELECT inner_product('[1,2]', '[3,4]');
|
||||||
inner_product
|
inner_product
|
||||||
---------------
|
---------------
|
||||||
11
|
11
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT inner_product('[1,2]'::vector, '[3]');
|
SELECT inner_product('[1,2]', '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
SELECT inner_product('[3e38]', '[3e38]');
|
||||||
inner_product
|
inner_product
|
||||||
---------------
|
---------------
|
||||||
Infinity
|
Infinity
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
SELECT cosine_distance('[1,2]', '[2,4]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
SELECT cosine_distance('[1,2]', '[0,0]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
NaN
|
NaN
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
SELECT cosine_distance('[1,1]', '[1,1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
SELECT cosine_distance('[1,0]', '[0,2]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
1
|
1
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
2
|
2
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
SELECT cosine_distance('[1,2]', '[3]');
|
||||||
ERROR: different vector dimensions 2 and 1
|
ERROR: different vector dimensions 2 and 1
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[1.1,1.1]');
|
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[-1.1,-1.1]');
|
SELECT cosine_distance('[1,1]', '[-1.1,-1.1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
2
|
2
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
SELECT cosine_distance('[3e38]', '[3e38]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
NaN
|
NaN
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
SELECT '127'::tinyint;
|
|
||||||
tinyint
|
|
||||||
---------
|
|
||||||
127
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '128'::tinyint;
|
|
||||||
ERROR: value "128" is out of range for type tinyint
|
|
||||||
LINE 1: SELECT '128'::tinyint;
|
|
||||||
^
|
|
||||||
SELECT '-128'::tinyint;
|
|
||||||
tinyint
|
|
||||||
---------
|
|
||||||
-128
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '-129'::tinyint;
|
|
||||||
ERROR: value "-129" is out of range for type tinyint
|
|
||||||
LINE 1: SELECT '-129'::tinyint;
|
|
||||||
^
|
|
||||||
SELECT ''::tinyint;
|
|
||||||
ERROR: invalid input syntax for type tinyint: ""
|
|
||||||
LINE 1: SELECT ''::tinyint;
|
|
||||||
^
|
|
||||||
SELECT ' 1'::tinyint;
|
|
||||||
tinyint
|
|
||||||
---------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '1 '::tinyint;
|
|
||||||
tinyint
|
|
||||||
---------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '1a'::tinyint;
|
|
||||||
ERROR: invalid input syntax for type tinyint: "1a"
|
|
||||||
LINE 1: SELECT '1a'::tinyint;
|
|
||||||
^
|
|
||||||
SELECT '{1,2,3}'::tinyint[];
|
|
||||||
tinyint
|
|
||||||
---------
|
|
||||||
{1,2,3}
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '128'::numeric::tinyint;
|
|
||||||
ERROR: value "128" is out of range for type tinyint
|
|
||||||
SELECT 'NaN'::numeric::tinyint;
|
|
||||||
ERROR: cannot convert NaN to integer
|
|
||||||
SELECT l2_distance('{0,0}'::tinyint[], '{3,4}'::tinyint[]);
|
|
||||||
l2_distance
|
|
||||||
-------------
|
|
||||||
5
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT l2_distance('{0,0}'::tinyint[], '{0,1}'::tinyint[]);
|
|
||||||
l2_distance
|
|
||||||
-------------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT l2_distance('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
l2_distance
|
|
||||||
-------------
|
|
||||||
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT l2_distance('{3e38}'::tinyint[], '{-3e38}'::tinyint[]);
|
|
||||||
ERROR: invalid input syntax for type tinyint: "3e38"
|
|
||||||
LINE 1: SELECT l2_distance('{3e38}'::tinyint[], '{-3e38}'::tinyint[]...
|
|
||||||
^
|
|
||||||
SELECT '{0,0}'::tinyint[] <-> '{3,4}'::tinyint[];
|
|
||||||
?column?
|
|
||||||
----------
|
|
||||||
5
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT inner_product('{1,2}'::tinyint[], '{3,4}'::tinyint[]);
|
|
||||||
inner_product
|
|
||||||
---------------
|
|
||||||
11
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT inner_product('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
inner_product
|
|
||||||
---------------
|
|
||||||
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT inner_product('{127}'::tinyint[], '{127}'::tinyint[]);
|
|
||||||
inner_product
|
|
||||||
---------------
|
|
||||||
16129
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT '{1,2}'::tinyint[] <#> '{3,4}'::tinyint[];
|
|
||||||
?column?
|
|
||||||
----------
|
|
||||||
-11
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{2,4}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
0
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{0,0}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
NaN
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,1}'::tinyint[], '{1,1}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
0
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,0}'::tinyint[], '{0,2}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,1}'::tinyint[], '{-1,-1}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
2
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('{3e38}'::tinyint[], '{3e38}'::tinyint[]);
|
|
||||||
ERROR: invalid input syntax for type tinyint: "3e38"
|
|
||||||
LINE 1: SELECT cosine_distance('{3e38}'::tinyint[], '{3e38}'::tinyin...
|
|
||||||
^
|
|
||||||
SELECT '{1,2}'::tinyint[] <=> '{2,4}'::tinyint[];
|
|
||||||
?column?
|
|
||||||
----------
|
|
||||||
0
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
@@ -18,19 +18,19 @@ SELECT l2_distance('[0,0]'::vector, '[0,1]');
|
|||||||
SELECT l2_distance('[1,2]'::vector, '[3]');
|
SELECT l2_distance('[1,2]'::vector, '[3]');
|
||||||
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
SELECT l2_distance('[3e38]'::vector, '[-3e38]');
|
||||||
|
|
||||||
SELECT inner_product('[1,2]'::vector, '[3,4]');
|
SELECT inner_product('[1,2]', '[3,4]');
|
||||||
SELECT inner_product('[1,2]'::vector, '[3]');
|
SELECT inner_product('[1,2]', '[3]');
|
||||||
SELECT inner_product('[3e38]'::vector, '[3e38]');
|
SELECT inner_product('[3e38]', '[3e38]');
|
||||||
|
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[2,4]');
|
SELECT cosine_distance('[1,2]', '[2,4]');
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[0,0]');
|
SELECT cosine_distance('[1,2]', '[0,0]');
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[1,1]');
|
SELECT cosine_distance('[1,1]', '[1,1]');
|
||||||
SELECT cosine_distance('[1,0]'::vector, '[0,2]');
|
SELECT cosine_distance('[1,0]', '[0,2]');
|
||||||
SELECT cosine_distance('[1,1]'::vector, '[-1,-1]');
|
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||||
SELECT cosine_distance('[1,2]'::vector, '[3]');
|
SELECT cosine_distance('[1,2]', '[3]');
|
||||||
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('[1,1]', '[-1.1,-1.1]');
|
||||||
SELECT cosine_distance('[3e38]'::vector, '[3e38]');
|
SELECT cosine_distance('[3e38]', '[3e38]');
|
||||||
|
|
||||||
SELECT l1_distance('[0,0]', '[3,4]');
|
SELECT l1_distance('[0,0]', '[3,4]');
|
||||||
SELECT l1_distance('[0,0]', '[0,1]');
|
SELECT l1_distance('[0,0]', '[0,1]');
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
SELECT '127'::tinyint;
|
|
||||||
SELECT '128'::tinyint;
|
|
||||||
SELECT '-128'::tinyint;
|
|
||||||
SELECT '-129'::tinyint;
|
|
||||||
|
|
||||||
SELECT ''::tinyint;
|
|
||||||
SELECT ' 1'::tinyint;
|
|
||||||
SELECT '1 '::tinyint;
|
|
||||||
SELECT '1a'::tinyint;
|
|
||||||
|
|
||||||
SELECT '{1,2,3}'::tinyint[];
|
|
||||||
|
|
||||||
SELECT '128'::numeric::tinyint;
|
|
||||||
SELECT 'NaN'::numeric::tinyint;
|
|
||||||
|
|
||||||
SELECT l2_distance('{0,0}'::tinyint[], '{3,4}'::tinyint[]);
|
|
||||||
SELECT l2_distance('{0,0}'::tinyint[], '{0,1}'::tinyint[]);
|
|
||||||
SELECT l2_distance('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
SELECT l2_distance('{3e38}'::tinyint[], '{-3e38}'::tinyint[]);
|
|
||||||
SELECT '{0,0}'::tinyint[] <-> '{3,4}'::tinyint[];
|
|
||||||
|
|
||||||
SELECT inner_product('{1,2}'::tinyint[], '{3,4}'::tinyint[]);
|
|
||||||
SELECT inner_product('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
SELECT inner_product('{127}'::tinyint[], '{127}'::tinyint[]);
|
|
||||||
SELECT '{1,2}'::tinyint[] <#> '{3,4}'::tinyint[];
|
|
||||||
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{2,4}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{0,0}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{1,1}'::tinyint[], '{1,1}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{1,0}'::tinyint[], '{0,2}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{1,1}'::tinyint[], '{-1,-1}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{1,2}'::tinyint[], '{3}'::tinyint[]);
|
|
||||||
SELECT cosine_distance('{3e38}'::tinyint[], '{3e38}'::tinyint[]);
|
|
||||||
SELECT '{1,2}'::tinyint[] <=> '{2,4}'::tinyint[];
|
|
||||||
93
test/t/019_hnsw_array.pl
Normal file
93
test/t/019_hnsw_array.pl
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v float4[3]);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "{$r1,$r2,$r3}");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->");
|
||||||
|
my @opclasses = ("float4_l2_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v $opclass) WITH (dimensions = 3);");
|
||||||
|
|
||||||
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
Reference in New Issue
Block a user