mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 03:57:34 +08:00
Compare commits
33 Commits
hqann3
...
hnsw-read-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90aaf2102b | ||
|
|
a7551a61ca | ||
|
|
5c9a97af3b | ||
|
|
8af675cd25 | ||
|
|
97e0ed4464 | ||
|
|
533ad160e0 | ||
|
|
dfbd724a1f | ||
|
|
5f270c9663 | ||
|
|
352ec5be29 | ||
|
|
17916cad00 | ||
|
|
284f2f0fec | ||
|
|
edd49863ba | ||
|
|
411291189d | ||
|
|
cab9da72c0 | ||
|
|
d702ee31f2 | ||
|
|
9ed39fb94b | ||
|
|
b7e680d41a | ||
|
|
f5841f07fd | ||
|
|
35ab919bf5 | ||
|
|
5c08be0291 | ||
|
|
544686feb1 | ||
|
|
1a8ebb1129 | ||
|
|
aca89aec73 | ||
|
|
c9875f5150 | ||
|
|
df2c3d301f | ||
|
|
d557f1c9b1 | ||
|
|
3d6dd20469 | ||
|
|
c711da411c | ||
|
|
3975e212cc | ||
|
|
2b741ef068 | ||
|
|
f85a7d3fd0 | ||
|
|
5c25f81789 | ||
|
|
d72ee71f23 |
10
.github/workflows/build.yml
vendored
10
.github/workflows/build.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
||||
- postgres: 13
|
||||
os: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: ${{ matrix.postgres }}
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
- postgres: 14
|
||||
os: macos-15-intel
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: ${{ matrix.postgres }}
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
tar xf $TAG.tar.gz
|
||||
mv postgres-$TAG postgres
|
||||
env:
|
||||
TAG: ${{ matrix.postgres == 18 && 'REL_18_0' || 'REL_14_19' }}
|
||||
TAG: ${{ matrix.postgres == 18 && 'REL_18_2' || 'REL_14_21' }}
|
||||
- run: make prove_installcheck PROVE_FLAGS="-I ./postgres/src/test/perl -I ./test/perl"
|
||||
env:
|
||||
PERL5LIB: /Users/runner/perl5/lib/perl5
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
- postgres: 14
|
||||
os: windows-2022
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
postgres-version: ${{ matrix.postgres }}
|
||||
@@ -133,7 +133,7 @@ jobs:
|
||||
if: ${{ !startsWith(github.ref_name, 'mac') && !startsWith(github.ref_name, 'windows') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: ankane/setup-postgres-valgrind@v1
|
||||
with:
|
||||
postgres-version: 18
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
## 0.9.0 (unreleased)
|
||||
|
||||
- Added support for inline filtering with HNSW
|
||||
|
||||
## 0.8.2 (unreleased)
|
||||
## 0.8.2 (2026-02-25)
|
||||
|
||||
- Fixed buffer overflow with parallel HNSW index build - [more info](https://github.com/pgvector/pgvector/issues/959)
|
||||
- Improved `install` target on Windows
|
||||
- Fixed `Index Searches` in `EXPLAIN` output for Postgres 18
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ ARG DEBIAN_CODENAME=bookworm
|
||||
FROM postgres:$PG_MAJOR-$DEBIAN_CODENAME
|
||||
ARG PG_MAJOR
|
||||
|
||||
ADD https://github.com/pgvector/pgvector.git#v0.8.1 /tmp/pgvector
|
||||
ADD https://github.com/pgvector/pgvector.git#v0.8.2 /tmp/pgvector
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-mark hold locales && \
|
||||
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
|
||||
Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
|
||||
|
||||
Portions Copyright (c) 1994, The Regents of the University of California
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "vector",
|
||||
"abstract": "Open-source vector similarity search for Postgres",
|
||||
"description": "Supports L2 distance, inner product, and cosine distance",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.2",
|
||||
"maintainer": [
|
||||
"Andrew Kane <andrew@ankane.org>"
|
||||
],
|
||||
@@ -20,7 +20,7 @@
|
||||
"vector": {
|
||||
"file": "sql/vector.sql",
|
||||
"docfile": "README.md",
|
||||
"version": "0.8.1",
|
||||
"version": "0.8.2",
|
||||
"abstract": "Open-source vector similarity search for Postgres"
|
||||
}
|
||||
},
|
||||
|
||||
7
Makefile
7
Makefile
@@ -1,5 +1,5 @@
|
||||
EXTENSION = vector
|
||||
EXTVERSION = 0.8.1
|
||||
EXTVERSION = 0.8.2
|
||||
|
||||
MODULE_big = vector
|
||||
DATA = $(wildcard sql/*--*--*.sql)
|
||||
@@ -27,6 +27,11 @@ ifneq ($(filter ppc64%, $(shell uname -m)), )
|
||||
OPTFLAGS =
|
||||
endif
|
||||
|
||||
# RISC-V64 doesn't support -march=native
|
||||
ifeq ($(shell uname -m), riscv64)
|
||||
OPTFLAGS =
|
||||
endif
|
||||
|
||||
# For auto-vectorization:
|
||||
# - GCC (needs -ftree-vectorize OR -O3) - https://gcc.gnu.org/projects/tree-ssa/vectorization.html
|
||||
# - Clang (could use pragma instead) - https://llvm.org/docs/Vectorizers.html
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
EXTENSION = vector
|
||||
EXTVERSION = 0.8.1
|
||||
EXTVERSION = 0.8.2
|
||||
|
||||
DATA_built = sql\$(EXTENSION)--$(EXTVERSION).sql
|
||||
OBJS = src\bitutils.obj src\bitvec.obj src\halfutils.obj src\halfvec.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\sparsevec.obj src\vector.obj
|
||||
|
||||
39
README.md
39
README.md
@@ -21,7 +21,7 @@ Compile and install the extension (supports Postgres 13+)
|
||||
|
||||
```sh
|
||||
cd /tmp
|
||||
git clone --branch v0.8.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
make install # may need sudo
|
||||
@@ -38,7 +38,7 @@ Ensure [C++ support in Visual Studio](https://learn.microsoft.com/en-us/cpp/buil
|
||||
```cmd
|
||||
set "PGROOT=C:\Program Files\PostgreSQL\18"
|
||||
cd %TEMP%
|
||||
git clone --branch v0.8.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
nmake /F Makefile.win
|
||||
nmake /F Makefile.win install
|
||||
@@ -467,12 +467,6 @@ If filtering by many different values, consider [partitioning](https://www.postg
|
||||
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
|
||||
```
|
||||
|
||||
Or a composite HNSW index (added in 0.9.0)
|
||||
|
||||
```sql
|
||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops, category_id);
|
||||
```
|
||||
|
||||
## Iterative Index Scans
|
||||
|
||||
With approximate indexes, queries with filtering can return less results since filtering is applied *after* the index is scanned. Starting with 0.8.0, you can enable iterative index scans, which will automatically scan more of the index until enough results are found (or it reaches `hnsw.max_scan_tuples` or `ivfflat.max_probes`).
|
||||
@@ -782,6 +776,7 @@ Algol | [pgvector-algol](https://github.com/pgvector/pgvector-algol)
|
||||
C | [pgvector-c](https://github.com/pgvector/pgvector-c)
|
||||
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
|
||||
C#, F#, Visual Basic | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
|
||||
COBOL | [pgvector-cobol](https://github.com/pgvector/pgvector-cobol)
|
||||
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
|
||||
D | [pgvector-d](https://github.com/pgvector/pgvector-d)
|
||||
Dart | [pgvector-dart](https://github.com/pgvector/pgvector-dart)
|
||||
@@ -809,6 +804,7 @@ Raku | [pgvector-raku](https://github.com/pgvector/pgvector-raku)
|
||||
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
|
||||
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
|
||||
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
|
||||
Tcl | [pgvector-tcl](https://github.com/pgvector/pgvector-tcl)
|
||||
Zig | [pgvector-zig](https://github.com/pgvector/pgvector-zig)
|
||||
|
||||
## Frequently Asked Questions
|
||||
@@ -1156,23 +1152,23 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
||||
|
||||
Supported tags are:
|
||||
|
||||
- `pg18-trixie`, `0.8.1-pg18-trixie`
|
||||
- `pg18-bookworm`, `0.8.1-pg18-bookworm`, `pg18`, `0.8.1-pg18`
|
||||
- `pg17-trixie`, `0.8.1-pg17-trixie`
|
||||
- `pg17-bookworm`, `0.8.1-pg17-bookworm`, `pg17`, `0.8.1-pg17`
|
||||
- `pg16-trixie`, `0.8.1-pg16-trixie`
|
||||
- `pg16-bookworm`, `0.8.1-pg16-bookworm`, `pg16`, `0.8.1-pg16`
|
||||
- `pg15-trixie`, `0.8.1-pg15-trixie`
|
||||
- `pg15-bookworm`, `0.8.1-pg15-bookworm`, `pg15`, `0.8.1-pg15`
|
||||
- `pg14-trixie`, `0.8.1-pg14-trixie`
|
||||
- `pg14-bookworm`, `0.8.1-pg14-bookworm`, `pg14`, `0.8.1-pg14`
|
||||
- `pg13-trixie`, `0.8.1-pg13-trixie`
|
||||
- `pg13-bookworm`, `0.8.1-pg13-bookworm`, `pg13`, `0.8.1-pg13`
|
||||
- `pg18-trixie`, `0.8.2-pg18-trixie`
|
||||
- `pg18-bookworm`, `0.8.2-pg18-bookworm`, `pg18`, `0.8.2-pg18`
|
||||
- `pg17-trixie`, `0.8.2-pg17-trixie`
|
||||
- `pg17-bookworm`, `0.8.2-pg17-bookworm`, `pg17`, `0.8.2-pg17`
|
||||
- `pg16-trixie`, `0.8.2-pg16-trixie`
|
||||
- `pg16-bookworm`, `0.8.2-pg16-bookworm`, `pg16`, `0.8.2-pg16`
|
||||
- `pg15-trixie`, `0.8.2-pg15-trixie`
|
||||
- `pg15-bookworm`, `0.8.2-pg15-bookworm`, `pg15`, `0.8.2-pg15`
|
||||
- `pg14-trixie`, `0.8.2-pg14-trixie`
|
||||
- `pg14-bookworm`, `0.8.2-pg14-bookworm`, `pg14`, `0.8.2-pg14`
|
||||
- `pg13-trixie`, `0.8.2-pg13-trixie`
|
||||
- `pg13-bookworm`, `0.8.2-pg13-bookworm`, `pg13`, `0.8.2-pg13`
|
||||
|
||||
You can also build the image manually:
|
||||
|
||||
```sh
|
||||
git clone --branch v0.8.1 https://github.com/pgvector/pgvector.git
|
||||
git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
docker build --pull --build-arg PG_MAJOR=18 -t myuser/pgvector .
|
||||
```
|
||||
@@ -1288,7 +1284,6 @@ Thanks to:
|
||||
- [k-means++: The Advantage of Careful Seeding](https://theory.stanford.edu/~sergei/papers/kMeansPP-soda.pdf)
|
||||
- [Concept Decompositions for Large Sparse Text Data using Clustering](https://www.cs.utexas.edu/users/inderjit/public_papers/concept_mlj.pdf)
|
||||
- [Efficient and Robust Approximate Nearest Neighbor Search using Hierarchical Navigable Small World Graphs](https://arxiv.org/ftp/arxiv/papers/1603/1603.09320.pdf)
|
||||
- [HQANN: Efficient and Robust Similarity Search for Hybrid Queries with Structured and Unstructured Constraints](https://arxiv.org/pdf/2207.07940.pdf)
|
||||
|
||||
## History
|
||||
|
||||
|
||||
2
sql/vector--0.8.1--0.8.2.sql
Normal file
2
sql/vector--0.8.1--0.8.2.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.8.2'" to load this file. \quit
|
||||
@@ -1,10 +0,0 @@
|
||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.9.0'" to load this file. \quit
|
||||
|
||||
CREATE FUNCTION hnsw_attribute_distance(integer, integer) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'hnsw_int4_attribute_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE OPERATOR CLASS vector_integer_ops
|
||||
DEFAULT FOR TYPE integer USING hnsw AS
|
||||
OPERATOR 2 = (integer, integer),
|
||||
FUNCTION 4 hnsw_attribute_distance(integer, integer);
|
||||
@@ -916,13 +916,3 @@ CREATE OPERATOR CLASS sparsevec_l1_ops
|
||||
OPERATOR 1 <+> (sparsevec, sparsevec) FOR ORDER BY float_ops,
|
||||
FUNCTION 1 l1_distance(sparsevec, sparsevec),
|
||||
FUNCTION 3 hnsw_sparsevec_support(internal);
|
||||
|
||||
-- hnsw attributes
|
||||
|
||||
CREATE FUNCTION hnsw_attribute_distance(integer, integer) RETURNS float8
|
||||
AS 'MODULE_PATHNAME', 'hnsw_int4_attribute_distance' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
|
||||
|
||||
CREATE OPERATOR CLASS vector_integer_ops
|
||||
DEFAULT FOR TYPE integer USING hnsw AS
|
||||
OPERATOR 2 = (integer, integer),
|
||||
FUNCTION 4 hnsw_attribute_distance(integer, integer);
|
||||
|
||||
@@ -169,7 +169,7 @@ BitJaccardDistanceAvx512Popcount(uint32 bytes, unsigned char *ax, unsigned char
|
||||
#endif
|
||||
|
||||
TARGET_XSAVE static bool
|
||||
SupportsAvx512Popcount()
|
||||
SupportsAvx512Popcount(void)
|
||||
{
|
||||
unsigned int exx[4] = {0, 0, 0, 0};
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "bitutils.h"
|
||||
#include "bitvec.h"
|
||||
#include "fmgr.h"
|
||||
#include "utils/varbit.h"
|
||||
#include "vector.h"
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "halfutils.h"
|
||||
#include "halfvec.h"
|
||||
|
||||
|
||||
@@ -13,12 +13,20 @@
|
||||
#include "port.h" /* for strtof() */
|
||||
#include "sparsevec.h"
|
||||
#include "utils/array.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/fmgrprotos.h"
|
||||
#include "utils/lsyscache.h"
|
||||
#include "utils/numeric.h"
|
||||
#include "utils/varbit.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#include "parser/scansup.h"
|
||||
#endif
|
||||
|
||||
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
|
||||
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
|
||||
|
||||
@@ -129,9 +137,9 @@ InitHalfVector(int dim)
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* Check for whitespace, since array_isspace() is static
|
||||
*/
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#define halfvec_isspace(ch) scanner_isspace(ch)
|
||||
#else
|
||||
static inline bool
|
||||
halfvec_isspace(char ch)
|
||||
{
|
||||
@@ -144,6 +152,7 @@ halfvec_isspace(char ch)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Check state array
|
||||
|
||||
84
src/hnsw.c
84
src/hnsw.c
@@ -1,18 +1,25 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "access/amapi.h"
|
||||
#include "access/genam.h"
|
||||
#include "access/reloptions.h"
|
||||
#include "commands/progress.h"
|
||||
#include "commands/vacuum.h"
|
||||
#include "fmgr.h"
|
||||
#include "hnsw.h"
|
||||
#include "miscadmin.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "storage/lwlock.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/guc.h"
|
||||
#include "utils/relcache.h"
|
||||
#include "utils/selfuncs.h"
|
||||
#include "utils/spccache.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM < 150000
|
||||
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
||||
@@ -260,10 +267,68 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(hnswhandler);
|
||||
Datum
|
||||
hnswhandler(PG_FUNCTION_ARGS)
|
||||
{
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
static const IndexAmRoutine amroutine = {
|
||||
.type = T_IndexAmRoutine,
|
||||
.amstrategies = 0,
|
||||
.amsupport = 3,
|
||||
.amoptsprocnum = 0,
|
||||
.amcanorder = false,
|
||||
.amcanorderbyop = true,
|
||||
.amcanhash = false,
|
||||
.amconsistentequality = false,
|
||||
.amconsistentordering = false,
|
||||
.amcanbackward = false,
|
||||
.amcanunique = false,
|
||||
.amcanmulticol = false,
|
||||
.amoptionalkey = true,
|
||||
.amsearcharray = false,
|
||||
.amsearchnulls = false,
|
||||
.amstorage = false,
|
||||
.amclusterable = false,
|
||||
.ampredlocks = false,
|
||||
.amcanparallel = false,
|
||||
.amcanbuildparallel = true,
|
||||
.amcaninclude = false,
|
||||
.amusemaintenanceworkmem = false,
|
||||
.amsummarizing = false,
|
||||
.amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL,
|
||||
.amkeytype = InvalidOid,
|
||||
|
||||
.ambuild = hnswbuild,
|
||||
.ambuildempty = hnswbuildempty,
|
||||
.aminsert = hnswinsert,
|
||||
.aminsertcleanup = NULL,
|
||||
.ambulkdelete = hnswbulkdelete,
|
||||
.amvacuumcleanup = hnswvacuumcleanup,
|
||||
.amcanreturn = NULL,
|
||||
.amcostestimate = hnswcostestimate,
|
||||
.amgettreeheight = NULL,
|
||||
.amoptions = hnswoptions,
|
||||
.amproperty = NULL,
|
||||
.ambuildphasename = hnswbuildphasename,
|
||||
.amvalidate = hnswvalidate,
|
||||
.amadjustmembers = NULL,
|
||||
.ambeginscan = hnswbeginscan,
|
||||
.amrescan = hnswrescan,
|
||||
.amgettuple = hnswgettuple,
|
||||
.amgetbitmap = NULL,
|
||||
.amendscan = hnswendscan,
|
||||
.ammarkpos = NULL,
|
||||
.amrestrpos = NULL,
|
||||
.amestimateparallelscan = NULL,
|
||||
.aminitparallelscan = NULL,
|
||||
.amparallelrescan = NULL,
|
||||
.amtranslatestrategy = NULL,
|
||||
.amtranslatecmptype = NULL,
|
||||
};
|
||||
|
||||
PG_RETURN_POINTER(&amroutine);
|
||||
#else
|
||||
IndexAmRoutine *amroutine = makeNode(IndexAmRoutine);
|
||||
|
||||
amroutine->amstrategies = 0;
|
||||
amroutine->amsupport = 4;
|
||||
amroutine->amsupport = 3;
|
||||
amroutine->amoptsprocnum = 0;
|
||||
amroutine->amcanorder = false;
|
||||
amroutine->amcanorderbyop = true;
|
||||
@@ -274,7 +339,7 @@ hnswhandler(PG_FUNCTION_ARGS)
|
||||
#endif
|
||||
amroutine->amcanbackward = false; /* can change direction mid-scan */
|
||||
amroutine->amcanunique = false;
|
||||
amroutine->amcanmulticol = true;
|
||||
amroutine->amcanmulticol = false;
|
||||
amroutine->amoptionalkey = true;
|
||||
amroutine->amsearcharray = false;
|
||||
amroutine->amsearchnulls = false;
|
||||
@@ -333,18 +398,5 @@ hnswhandler(PG_FUNCTION_ARGS)
|
||||
#endif
|
||||
|
||||
PG_RETURN_POINTER(amroutine);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the distance between two int4 attributes
|
||||
*/
|
||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(hnsw_int4_attribute_distance);
|
||||
Datum
|
||||
hnsw_int4_attribute_distance(PG_FUNCTION_ARGS)
|
||||
{
|
||||
int32 a = PG_GETARG_INT32(0);
|
||||
int32 b = PG_GETARG_INT32(1);
|
||||
double distance = ((double) a) - ((double) b);
|
||||
|
||||
PG_RETURN_FLOAT8(distance);
|
||||
#endif
|
||||
}
|
||||
|
||||
49
src/hnsw.h
49
src/hnsw.h
@@ -3,15 +3,25 @@
|
||||
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/parallel.h"
|
||||
#include "lib/pairingheap.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "port.h" /* for random() */
|
||||
#include "storage/bufpage.h"
|
||||
#include "storage/condition_variable.h"
|
||||
#include "storage/lwlock.h"
|
||||
#include "storage/s_lock.h"
|
||||
#include "utils/relptr.h"
|
||||
#include "utils/sampling.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
typedef Pointer Item;
|
||||
#endif
|
||||
|
||||
#define HNSW_MAX_DIM 2000
|
||||
#define HNSW_MAX_NNZ 1000
|
||||
|
||||
@@ -19,7 +29,6 @@
|
||||
#define HNSW_DISTANCE_PROC 1
|
||||
#define HNSW_NORM_PROC 2
|
||||
#define HNSW_TYPE_INFO_PROC 3
|
||||
#define HNSW_ATTRIBUTE_DISTANCE_PROC 4
|
||||
|
||||
#define HNSW_VERSION 1
|
||||
#define HNSW_MAGIC_NUMBER 0xA953A953
|
||||
@@ -108,8 +117,6 @@
|
||||
#define HnswPtrPointer(hp) (hp).ptr
|
||||
#define HnswPtrOffset(hp) relptr_offset((hp).relptr)
|
||||
|
||||
#define HnswUseIndexTuple(index) (IndexRelationGetNumberOfAttributes(index) > 1)
|
||||
|
||||
/* Variables */
|
||||
extern int hnsw_ef_search;
|
||||
extern int hnsw_iterative_scan;
|
||||
@@ -137,7 +144,6 @@ HnswPtrDeclare(HnswElementData, HnswElementRelptr, HnswElementPtr);
|
||||
HnswPtrDeclare(HnswNeighborArray, HnswNeighborArrayRelptr, HnswNeighborArrayPtr);
|
||||
HnswPtrDeclare(HnswNeighborArrayPtr, HnswNeighborsRelptr, HnswNeighborsPtr);
|
||||
HnswPtrDeclare(char, DatumRelptr, DatumPtr);
|
||||
HnswPtrDeclare(IndexTupleData, IndexTupleRelptr, IndexTuplePtr);
|
||||
|
||||
struct HnswElementData
|
||||
{
|
||||
@@ -154,7 +160,6 @@ struct HnswElementData
|
||||
OffsetNumber neighborOffno;
|
||||
BlockNumber neighborPage;
|
||||
DatumPtr value;
|
||||
IndexTuplePtr itup;
|
||||
LWLock lock;
|
||||
};
|
||||
|
||||
@@ -180,7 +185,6 @@ typedef struct HnswSearchCandidate
|
||||
pairingheap_node w_node;
|
||||
HnswElementPtr element;
|
||||
double distance;
|
||||
bool matches;
|
||||
} HnswSearchCandidate;
|
||||
|
||||
/* HNSW index options */
|
||||
@@ -259,16 +263,14 @@ typedef struct HnswTypeInfo
|
||||
|
||||
typedef struct HnswSupport
|
||||
{
|
||||
FmgrInfo *procinfo[2];
|
||||
FmgrInfo *procinfo;
|
||||
FmgrInfo *normprocinfo;
|
||||
Oid *collation;
|
||||
Oid collation;
|
||||
} HnswSupport;
|
||||
|
||||
typedef struct HnswQuery
|
||||
{
|
||||
Datum value;
|
||||
IndexTuple itup;
|
||||
ScanKeyData *keyData;
|
||||
} HnswQuery;
|
||||
|
||||
typedef struct HnswBuildState
|
||||
@@ -297,8 +299,6 @@ typedef struct HnswBuildState
|
||||
HnswGraph *graph;
|
||||
double ml;
|
||||
int maxLevel;
|
||||
bool useIndexTuple;
|
||||
TupleDesc tupdesc;
|
||||
|
||||
/* Memory */
|
||||
MemoryContext graphCtx;
|
||||
@@ -372,6 +372,13 @@ typedef union
|
||||
ItemPointerData indextid;
|
||||
} HnswUnvisited;
|
||||
|
||||
typedef struct HnswReadStreamData
|
||||
{
|
||||
HnswUnvisited *unvisited;
|
||||
int unvisitedLength;
|
||||
int visited;
|
||||
} HnswReadStreamData;
|
||||
|
||||
typedef struct HnswScanOpaqueData
|
||||
{
|
||||
const HnswTypeInfo *typeInfo;
|
||||
@@ -427,32 +434,30 @@ bool HnswCheckNorm(HnswSupport * support, Datum value);
|
||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||
void HnswInitPage(Buffer buf, Page page);
|
||||
void HnswInit(void);
|
||||
List *HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, bool inMemory, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples);
|
||||
List *HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples, bool maintenance);
|
||||
HnswElement HnswGetEntryPoint(Relation index);
|
||||
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
||||
void *HnswAlloc(HnswAllocator * allocator, Size size);
|
||||
HnswElement HnswInitElement(char *base, ItemPointer tid, int m, double ml, int maxLevel, HnswAllocator * alloc);
|
||||
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
||||
void HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool inMemory);
|
||||
HnswSearchCandidate *HnswEntryCandidate(char *base, HnswElement em, HnswQuery * q, Relation rel, HnswSupport * support, bool loadVec, bool inMemory);
|
||||
void HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool maintenance);
|
||||
HnswSearchCandidate *HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec);
|
||||
void HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum, bool building);
|
||||
void HnswSetNeighborTuple(char *base, HnswNeighborTuple ntup, HnswElement e, int m);
|
||||
void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
|
||||
HnswNeighborArray *HnswInitNeighborArray(int lm, HnswAllocator * allocator);
|
||||
void HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * alloc);
|
||||
bool HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, ItemPointer heaptid, bool building, TupleDesc tupdesc);
|
||||
bool HnswInsertTupleOnDisk(Relation index, HnswSupport * support, Datum value, ItemPointer heaptid, bool building);
|
||||
void HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e, int m, bool checkExisting, bool building);
|
||||
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec, Relation index);
|
||||
void HnswLoadElement(HnswElement element, double *distance, bool *matches, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance);
|
||||
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element, bool useIndexTuple);
|
||||
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
|
||||
void HnswLoadElement(HnswElement element, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance);
|
||||
bool HnswFormIndexValue(Datum *out, Datum *values, bool *isnull, const HnswTypeInfo * typeInfo, HnswSupport * support);
|
||||
void HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element);
|
||||
void HnswUpdateConnection(char *base, HnswNeighborArray * neighbors, HnswElement newElement, float distance, int lm, int *updateIdx, Relation index, HnswSupport * support);
|
||||
bool HnswFormIndexTuple(IndexTuple *out, Datum *values, bool *isnull, const HnswTypeInfo * typeInfo, HnswSupport * support, TupleDesc tupdesc);
|
||||
bool HnswLoadNeighborTids(HnswElement element, ItemPointerData *indextids, Relation index, int m, int lm, int lc);
|
||||
void HnswInitLockTranche(void);
|
||||
const HnswTypeInfo *HnswGetTypeInfo(Relation index);
|
||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
||||
Size HnswGetElementTupleSize(char *base, HnswElement element, bool useIndexTuple);
|
||||
bool HnswIndexTupleIsEqual(IndexTuple a, IndexTuple b, TupleDesc tupdesc);
|
||||
|
||||
/* Index access methods */
|
||||
IndexBuildResult *hnswbuild(Relation heap, Relation index, IndexInfo *indexInfo);
|
||||
|
||||
110
src/hnswbuild.c
110
src/hnswbuild.c
@@ -36,11 +36,14 @@
|
||||
*/
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <limits.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/parallel.h"
|
||||
#include "access/relscan.h"
|
||||
#include "access/table.h"
|
||||
#include "access/tableam.h"
|
||||
#include "access/tupdesc.h"
|
||||
#include "access/xact.h"
|
||||
#include "access/xloginsert.h"
|
||||
#include "catalog/index.h"
|
||||
@@ -48,11 +51,15 @@
|
||||
#include "commands/progress.h"
|
||||
#include "hnsw.h"
|
||||
#include "miscadmin.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "optimizer/optimizer.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/condition_variable.h"
|
||||
#include "tcop/tcopprot.h"
|
||||
#include "utils/datum.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/rel.h"
|
||||
#include "utils/snapmgr.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
@@ -73,6 +80,8 @@
|
||||
#define PARALLEL_KEY_HNSW_AREA UINT64CONST(0xA000000000000002)
|
||||
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000003)
|
||||
|
||||
#define HNSW_MAX_GRAPH_MEMORY (SIZE_MAX / 2)
|
||||
|
||||
/*
|
||||
* Create the metapage
|
||||
*/
|
||||
@@ -152,7 +161,6 @@ CreateGraphPages(HnswBuildState * buildstate)
|
||||
Page page;
|
||||
HnswElementPtr iter = buildstate->graph->head;
|
||||
char *base = buildstate->hnswarea;
|
||||
bool useIndexTuple = buildstate->useIndexTuple;
|
||||
|
||||
/* Calculate sizes */
|
||||
maxSize = HNSW_MAX_SIZE;
|
||||
@@ -172,6 +180,7 @@ CreateGraphPages(HnswBuildState * buildstate)
|
||||
Size etupSize;
|
||||
Size ntupSize;
|
||||
Size combinedSize;
|
||||
Pointer valuePtr = HnswPtrAccess(base, element->value);
|
||||
|
||||
/* Update iterator */
|
||||
iter = element->next;
|
||||
@@ -180,7 +189,7 @@ CreateGraphPages(HnswBuildState * buildstate)
|
||||
MemSet(etup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
||||
|
||||
/* Calculate sizes */
|
||||
etupSize = HnswGetElementTupleSize(base, element, useIndexTuple);
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(valuePtr));
|
||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||
|
||||
@@ -190,7 +199,7 @@ CreateGraphPages(HnswBuildState * buildstate)
|
||||
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
|
||||
errmsg("index tuple too large")));
|
||||
|
||||
HnswSetElementTuple(base, etup, element, useIndexTuple);
|
||||
HnswSetElementTuple(base, etup, element);
|
||||
|
||||
/* Keep element and neighbors on the same page if possible */
|
||||
if (PageGetFreeSpace(page) < etupSize || (combinedSize <= maxSize && PageGetFreeSpace(page) < combinedSize))
|
||||
@@ -331,18 +340,19 @@ AddDuplicateInMemory(HnswElement element, HnswElement dup)
|
||||
* Find duplicate element
|
||||
*/
|
||||
static bool
|
||||
FindDuplicateInMemory(char *base, HnswElement element, bool useIndexTuple, TupleDesc tupdesc)
|
||||
FindDuplicateInMemory(char *base, HnswElement element)
|
||||
{
|
||||
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
||||
IndexTuple itup = HnswPtrAccess(base, element->itup);
|
||||
Datum value = HnswGetValue(base, element);
|
||||
|
||||
for (int i = 0; i < neighbors->length; i++)
|
||||
{
|
||||
HnswCandidate *neighbor = &neighbors->items[i];
|
||||
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
||||
Datum neighborValue = HnswGetValue(base, neighborElement);
|
||||
|
||||
/* Exit early since ordered by distance */
|
||||
if (!HnswIndexTupleIsEqual(itup, HnswPtrAccess(base, neighborElement->itup), tupdesc))
|
||||
if (!datumIsEqual(value, neighborValue, false, -1))
|
||||
return false;
|
||||
|
||||
/* Check for space */
|
||||
@@ -369,7 +379,7 @@ AddElementInMemory(char *base, HnswGraph * graph, HnswElement element)
|
||||
* Update neighbors
|
||||
*/
|
||||
static void
|
||||
UpdateNeighborsInMemory(char *base, Relation index, HnswSupport * support, HnswElement e, int m)
|
||||
UpdateNeighborsInMemory(char *base, HnswSupport * support, HnswElement e, int m)
|
||||
{
|
||||
for (int lc = e->level; lc >= 0; lc--)
|
||||
{
|
||||
@@ -391,7 +401,7 @@ UpdateNeighborsInMemory(char *base, Relation index, HnswSupport * support, HnswE
|
||||
Assert(neighborElement);
|
||||
|
||||
LWLockAcquire(&neighborElement->lock, LW_EXCLUSIVE);
|
||||
HnswUpdateConnection(base, HnswGetNeighbors(base, neighborElement, lc), e, hc->distance, lm, NULL, index, support);
|
||||
HnswUpdateConnection(base, HnswGetNeighbors(base, neighborElement, lc), e, hc->distance, lm, NULL, NULL, support);
|
||||
LWLockRelease(&neighborElement->lock);
|
||||
}
|
||||
}
|
||||
@@ -407,14 +417,14 @@ UpdateGraphInMemory(HnswSupport * support, HnswElement element, int m, HnswEleme
|
||||
char *base = buildstate->hnswarea;
|
||||
|
||||
/* Look for duplicate */
|
||||
if (FindDuplicateInMemory(base, element, buildstate->useIndexTuple, buildstate->tupdesc))
|
||||
if (FindDuplicateInMemory(base, element))
|
||||
return;
|
||||
|
||||
/* Add element */
|
||||
AddElementInMemory(base, graph, element);
|
||||
|
||||
/* Update neighbors */
|
||||
UpdateNeighborsInMemory(base, buildstate->index, support, element, m);
|
||||
UpdateNeighborsInMemory(base, support, element, m);
|
||||
|
||||
/* Update entry point if needed (already have lock) */
|
||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||
@@ -427,7 +437,6 @@ UpdateGraphInMemory(HnswSupport * support, HnswElement element, int m, HnswEleme
|
||||
static void
|
||||
InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
||||
{
|
||||
Relation index = buildstate->index;
|
||||
HnswGraph *graph = buildstate->graph;
|
||||
HnswSupport *support = &buildstate->support;
|
||||
HnswElement entryPoint;
|
||||
@@ -461,7 +470,7 @@ InsertTupleInMemory(HnswBuildState * buildstate, HnswElement element)
|
||||
}
|
||||
|
||||
/* Find neighbors for element */
|
||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, false, true);
|
||||
HnswFindElementNeighbors(base, element, entryPoint, NULL, support, m, efConstruction, false, true);
|
||||
|
||||
/* Update graph in memory */
|
||||
UpdateGraphInMemory(support, element, m, entryPoint, buildstate);
|
||||
@@ -480,20 +489,22 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
||||
HnswElement element;
|
||||
HnswAllocator *allocator = &buildstate->allocator;
|
||||
HnswSupport *support = &buildstate->support;
|
||||
Size valueSize;
|
||||
Pointer valuePtr;
|
||||
LWLock *flushLock = &graph->flushLock;
|
||||
char *base = buildstate->hnswarea;
|
||||
TupleDesc tupdesc = buildstate->tupdesc;
|
||||
IndexTuple itup;
|
||||
Size itupSize;
|
||||
IndexTuple itupShared;
|
||||
bool unused;
|
||||
Datum value;
|
||||
Size memoryMargin;
|
||||
|
||||
/* Form index tuple */
|
||||
if (!HnswFormIndexTuple(&itup, values, isnull, buildstate->typeInfo, support, tupdesc))
|
||||
/* Form index value */
|
||||
if (!HnswFormIndexValue(&value, values, isnull, buildstate->typeInfo, support))
|
||||
return false;
|
||||
|
||||
/* Get tuple size */
|
||||
itupSize = IndexTupleSize(itup);
|
||||
/* Get datum size */
|
||||
valueSize = VARSIZE_ANY(DatumGetPointer(value));
|
||||
|
||||
/* In a parallel build, add a margin so allocations never fail */
|
||||
memoryMargin = base == NULL ? 0 : 1024 * 1024;
|
||||
|
||||
/* Ensure graph not flushed when inserting */
|
||||
LWLockAcquire(flushLock, LW_SHARED);
|
||||
@@ -503,7 +514,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
||||
{
|
||||
LWLockRelease(flushLock);
|
||||
|
||||
return HnswInsertTupleOnDisk(index, support, itup, heaptid, true, tupdesc);
|
||||
return HnswInsertTupleOnDisk(index, support, value, heaptid, true);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -516,7 +527,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
||||
* Check that we have enough memory available for the new element now that
|
||||
* we have the allocator lock, and flush pages if needed.
|
||||
*/
|
||||
if (graph->memoryUsed >= graph->memoryTotal)
|
||||
if (graph->memoryUsed + memoryMargin >= graph->memoryTotal)
|
||||
{
|
||||
LWLockRelease(&graph->allocatorLock);
|
||||
|
||||
@@ -535,12 +546,12 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
||||
|
||||
LWLockRelease(flushLock);
|
||||
|
||||
return HnswInsertTupleOnDisk(index, support, itup, heaptid, true, tupdesc);
|
||||
return HnswInsertTupleOnDisk(index, support, value, heaptid, true);
|
||||
}
|
||||
|
||||
/* Ok, we can proceed to allocate the element */
|
||||
element = HnswInitElement(base, heaptid, buildstate->m, buildstate->ml, buildstate->maxLevel, allocator);
|
||||
itupShared = HnswAlloc(allocator, itupSize);
|
||||
valuePtr = HnswAlloc(allocator, valueSize);
|
||||
|
||||
/*
|
||||
* We have now allocated the space needed for the element, so we don't
|
||||
@@ -549,10 +560,9 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid, Hn
|
||||
*/
|
||||
LWLockRelease(&graph->allocatorLock);
|
||||
|
||||
/* Copy the tuple */
|
||||
memcpy(itupShared, itup, itupSize);
|
||||
HnswPtrStore(base, element->itup, itupShared);
|
||||
HnswPtrStore(base, element->value, DatumGetPointer(index_getattr(itupShared, 1, tupdesc, &unused)));
|
||||
/* Copy the datum */
|
||||
memcpy(valuePtr, DatumGetPointer(value), valueSize);
|
||||
HnswPtrStore(base, element->value, (char *) valuePtr);
|
||||
|
||||
/* Create a lock for the element */
|
||||
LWLockInitialize(&element->lock, hnsw_lock_tranche_id);
|
||||
@@ -610,7 +620,7 @@ InitGraph(HnswGraph * graph, char *base, Size memoryTotal)
|
||||
HnswPtrStore(base, graph->head, (HnswElement) NULL);
|
||||
HnswPtrStore(base, graph->entryPoint, (HnswElement) NULL);
|
||||
graph->memoryUsed = 0;
|
||||
graph->memoryTotal = memoryTotal;
|
||||
graph->memoryTotal = Min(memoryTotal, HNSW_MAX_GRAPH_MEMORY);
|
||||
graph->flushed = false;
|
||||
graph->indtuples = 0;
|
||||
SpinLockInit(&graph->lock);
|
||||
@@ -651,9 +661,17 @@ static void *
|
||||
HnswSharedMemoryAlloc(Size size, void *state)
|
||||
{
|
||||
HnswBuildState *buildstate = (HnswBuildState *) state;
|
||||
void *chunk = buildstate->hnswarea + buildstate->graph->memoryUsed;
|
||||
Size alignedSize = MAXALIGN(size);
|
||||
void *chunk;
|
||||
|
||||
buildstate->graph->memoryUsed += MAXALIGN(size);
|
||||
if (alignedSize > 1024 * 1024)
|
||||
elog(ERROR, "hnsw allocation too large");
|
||||
|
||||
if (buildstate->graph->memoryUsed + alignedSize > buildstate->graph->memoryTotal)
|
||||
elog(ERROR, "hnsw allocator out of memory");
|
||||
|
||||
chunk = buildstate->hnswarea + buildstate->graph->memoryUsed;
|
||||
buildstate->graph->memoryUsed += alignedSize;
|
||||
return chunk;
|
||||
}
|
||||
|
||||
@@ -679,19 +697,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
||||
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
||||
errmsg("type not supported for hnsw index")));
|
||||
|
||||
/* TODO See if needed */
|
||||
if (IndexRelationGetNumberOfKeyAttributes(index) > 2)
|
||||
elog(ERROR, "index cannot have more than two columns");
|
||||
|
||||
if (!OidIsValid(index_getprocid(index, 1, HNSW_DISTANCE_PROC)))
|
||||
elog(ERROR, "first column must be a vector");
|
||||
|
||||
for (int i = 1; i < IndexRelationGetNumberOfKeyAttributes(index); i++)
|
||||
{
|
||||
if (!OidIsValid(index_getprocid(index, i + 1, HNSW_ATTRIBUTE_DISTANCE_PROC)))
|
||||
elog(ERROR, "column %d cannot be a vector", i + 1);
|
||||
}
|
||||
|
||||
/* Require column to have dimensions to be indexed */
|
||||
if (buildstate->dimensions < 0)
|
||||
ereport(ERROR,
|
||||
@@ -718,8 +723,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
||||
buildstate->graph = &buildstate->graphData;
|
||||
buildstate->ml = HnswGetMl(buildstate->m);
|
||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||
buildstate->useIndexTuple = HnswUseIndexTuple(index);
|
||||
buildstate->tupdesc = RelationGetDescr(index);
|
||||
|
||||
buildstate->graphCtx = GenerationContextCreate(CurrentMemoryContext,
|
||||
"Hnsw build graph context",
|
||||
@@ -800,7 +803,11 @@ HnswParallelScanAndInsert(Relation heapRel, Relation indexRel, HnswShared * hnsw
|
||||
buildstate.hnswarea = hnswarea;
|
||||
InitAllocator(&buildstate.allocator, &HnswSharedMemoryAlloc, &buildstate);
|
||||
scan = table_beginscan_parallel(heapRel,
|
||||
ParallelTableScanFromHnswShared(hnswshared));
|
||||
ParallelTableScanFromHnswShared(hnswshared)
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
,SO_NONE
|
||||
#endif
|
||||
);
|
||||
reltuples = table_index_build_scan(heapRel, indexRel, indexInfo,
|
||||
true, progress, BuildCallback,
|
||||
(void *) &buildstate, scan);
|
||||
@@ -954,6 +961,8 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
||||
if (esthnswarea > estother)
|
||||
esthnswarea -= estother;
|
||||
|
||||
esthnswarea = Min(esthnswarea, HNSW_MAX_GRAPH_MEMORY);
|
||||
|
||||
shm_toc_estimate_chunk(&pcxt->estimator, esthnswarea);
|
||||
shm_toc_estimate_keys(&pcxt->estimator, 2);
|
||||
|
||||
@@ -996,8 +1005,7 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
||||
snapshot);
|
||||
|
||||
hnswarea = (char *) shm_toc_allocate(pcxt->toc, esthnswarea);
|
||||
/* Report less than allocated so never fails */
|
||||
InitGraph(&hnswshared->graphData, hnswarea, esthnswarea - 1024 * 1024);
|
||||
InitGraph(&hnswshared->graphData, hnswarea, esthnswarea);
|
||||
|
||||
/*
|
||||
* Avoid base address for relptr for Postgres < 14.5
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "hnsw.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
#include "storage/lwlock.h"
|
||||
#include "utils/datum.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/rel.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
@@ -160,10 +162,9 @@ AddElementOnDisk(Relation index, HnswElement e, int m, BlockNumber insertPage, B
|
||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||
uint8 tupleVersion;
|
||||
char *base = NULL;
|
||||
bool useIndexTuple = HnswUseIndexTuple(index);
|
||||
|
||||
/* Calculate sizes */
|
||||
etupSize = HnswGetElementTupleSize(base, e, useIndexTuple);
|
||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(HnswPtrAccess(base, e->value)));
|
||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||
maxSize = HNSW_MAX_SIZE;
|
||||
@@ -171,7 +172,7 @@ AddElementOnDisk(Relation index, HnswElement e, int m, BlockNumber insertPage, B
|
||||
|
||||
/* Prepare element tuple */
|
||||
etup = palloc0(etupSize);
|
||||
HnswSetElementTuple(base, etup, e, useIndexTuple);
|
||||
HnswSetElementTuple(base, etup, e);
|
||||
|
||||
/* Prepare neighbor tuple */
|
||||
ntup = palloc0(ntupSize);
|
||||
@@ -388,9 +389,8 @@ LoadElementsForInsert(HnswNeighborArray * neighbors, HnswQuery * q, int *idx, Re
|
||||
HnswCandidate *hc = &neighbors->items[i];
|
||||
HnswElement element = HnswPtrAccess(base, hc->element);
|
||||
double distance;
|
||||
bool matches;
|
||||
|
||||
HnswLoadElement(element, &distance, &matches, q, index, support, true, NULL);
|
||||
HnswLoadElement(element, &distance, q, index, support, true, NULL);
|
||||
hc->distance = distance;
|
||||
|
||||
/* Prune element if being deleted */
|
||||
@@ -434,8 +434,6 @@ GetUpdateIndex(HnswElement element, HnswElement newElement, float distance, int
|
||||
HnswQuery q;
|
||||
|
||||
q.value = HnswGetValue(base, element);
|
||||
q.itup = HnswPtrAccess(base, element->itup);
|
||||
q.keyData = NULL;
|
||||
|
||||
LoadElementsForInsert(neighbors, &q, &idx, index, support);
|
||||
|
||||
@@ -641,30 +639,21 @@ AddDuplicateOnDisk(Relation index, HnswElement element, HnswElement dup, bool bu
|
||||
* Find duplicate element
|
||||
*/
|
||||
static bool
|
||||
FindDuplicateOnDisk(Relation index, HnswElement element, bool building, TupleDesc tupdesc)
|
||||
FindDuplicateOnDisk(Relation index, HnswElement element, bool building)
|
||||
{
|
||||
char *base = NULL;
|
||||
HnswNeighborArray *neighbors = HnswGetNeighbors(base, element, 0);
|
||||
Datum value = HnswGetValue(base, element);
|
||||
IndexTuple itup = HnswPtrAccess(base, element->itup);
|
||||
|
||||
for (int i = 0; i < neighbors->length; i++)
|
||||
{
|
||||
HnswCandidate *neighbor = &neighbors->items[i];
|
||||
HnswElement neighborElement = HnswPtrAccess(base, neighbor->element);
|
||||
Datum neighborValue = HnswGetValue(base, neighborElement);
|
||||
|
||||
if (HnswUseIndexTuple(index))
|
||||
{
|
||||
/* Exit early since ordered by distance */
|
||||
if (!HnswIndexTupleIsEqual(itup, HnswPtrAccess(base, neighborElement->itup), tupdesc))
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Exit early since ordered by distance */
|
||||
if (!datumIsEqual(value, HnswGetValue(base, neighborElement), false, -1))
|
||||
return false;
|
||||
}
|
||||
/* Exit early since ordered by distance */
|
||||
if (!datumIsEqual(value, neighborValue, false, -1))
|
||||
return false;
|
||||
|
||||
if (AddDuplicateOnDisk(index, element, neighborElement, building))
|
||||
return true;
|
||||
@@ -677,12 +666,12 @@ FindDuplicateOnDisk(Relation index, HnswElement element, bool building, TupleDes
|
||||
* Update graph on disk
|
||||
*/
|
||||
static void
|
||||
UpdateGraphOnDisk(Relation index, HnswSupport * support, HnswElement element, int m, HnswElement entryPoint, bool building, TupleDesc tupdesc)
|
||||
UpdateGraphOnDisk(Relation index, HnswSupport * support, HnswElement element, int m, HnswElement entryPoint, bool building)
|
||||
{
|
||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||
|
||||
/* Look for duplicate */
|
||||
if (FindDuplicateOnDisk(index, element, building, tupdesc))
|
||||
if (FindDuplicateOnDisk(index, element, building))
|
||||
return;
|
||||
|
||||
/* Add element */
|
||||
@@ -704,7 +693,7 @@ UpdateGraphOnDisk(Relation index, HnswSupport * support, HnswElement element, in
|
||||
* Insert a tuple into the index
|
||||
*/
|
||||
bool
|
||||
HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, ItemPointer heaptid, bool building, TupleDesc tupdesc)
|
||||
HnswInsertTupleOnDisk(Relation index, HnswSupport * support, Datum value, ItemPointer heaptid, bool building)
|
||||
{
|
||||
HnswElement entryPoint;
|
||||
HnswElement element;
|
||||
@@ -712,7 +701,6 @@ HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, It
|
||||
int efConstruction = HnswGetEfConstruction(index);
|
||||
LOCKMODE lockmode = ShareLock;
|
||||
char *base = NULL;
|
||||
bool unused;
|
||||
|
||||
/*
|
||||
* Get a shared lock. This allows vacuum to ensure no in-flight inserts
|
||||
@@ -726,8 +714,7 @@ HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, It
|
||||
|
||||
/* Create an element */
|
||||
element = HnswInitElement(base, heaptid, m, HnswGetMl(m), HnswGetMaxLevel(m), NULL);
|
||||
HnswPtrStore(base, element->itup, itup);
|
||||
HnswPtrStore(base, element->value, DatumGetPointer(index_getattr(itup, 1, tupdesc, &unused)));
|
||||
HnswPtrStore(base, element->value, (char *) DatumGetPointer(value));
|
||||
|
||||
/* Prevent concurrent inserts when likely updating entry point */
|
||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||
@@ -744,10 +731,10 @@ HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, It
|
||||
}
|
||||
|
||||
/* Find neighbors for element */
|
||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, false, false);
|
||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, false, building);
|
||||
|
||||
/* Update graph on disk */
|
||||
UpdateGraphOnDisk(index, support, element, m, entryPoint, building, tupdesc);
|
||||
UpdateGraphOnDisk(index, support, element, m, entryPoint, building);
|
||||
|
||||
/* Release lock */
|
||||
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||
@@ -761,18 +748,17 @@ HnswInsertTupleOnDisk(Relation index, HnswSupport * support, IndexTuple itup, It
|
||||
static void
|
||||
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heaptid)
|
||||
{
|
||||
IndexTuple itup;
|
||||
Datum value;
|
||||
const HnswTypeInfo *typeInfo = HnswGetTypeInfo(index);
|
||||
TupleDesc tupdesc = RelationGetDescr(index);
|
||||
HnswSupport support;
|
||||
|
||||
HnswInitSupport(&support, index);
|
||||
|
||||
/* Form index tuple */
|
||||
if (!HnswFormIndexTuple(&itup, values, isnull, typeInfo, &support, tupdesc))
|
||||
/* Form index value */
|
||||
if (!HnswFormIndexValue(&value, values, isnull, typeInfo, &support))
|
||||
return;
|
||||
|
||||
HnswInsertTupleOnDisk(index, &support, itup, heaptid, false, tupdesc);
|
||||
HnswInsertTupleOnDisk(index, &support, value, heaptid, false);
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/relscan.h"
|
||||
#include "hnsw.h"
|
||||
#include "lib/pairingheap.h"
|
||||
#include "miscadmin.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "pgstat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/relcache.h"
|
||||
#include "utils/snapmgr.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Algorithm 5 from paper
|
||||
@@ -22,30 +33,26 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
||||
int m;
|
||||
HnswElement entryPoint;
|
||||
char *base = NULL;
|
||||
bool inMemory = false;
|
||||
HnswQuery *q = &so->q;
|
||||
|
||||
q->value = value;
|
||||
q->itup = NULL;
|
||||
q->keyData = scan->keyData;
|
||||
|
||||
/* Get m and entry point */
|
||||
HnswGetMetaPageInfo(index, &m, &entryPoint);
|
||||
|
||||
q->value = value;
|
||||
so->m = m;
|
||||
|
||||
if (entryPoint == NULL)
|
||||
return NIL;
|
||||
|
||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, q, index, support, false, inMemory));
|
||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, q, index, support, false));
|
||||
|
||||
for (int lc = entryPoint->level; lc >= 1; lc--)
|
||||
{
|
||||
w = HnswSearchLayer(base, q, ep, 1, lc, index, support, m, false, NULL, inMemory, NULL, NULL, true, NULL);
|
||||
w = HnswSearchLayer(base, q, ep, 1, lc, index, support, m, false, NULL, NULL, NULL, true, NULL, false);
|
||||
ep = w;
|
||||
}
|
||||
|
||||
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, support, m, false, NULL, inMemory, &so->v, hnsw_iterative_scan != HNSW_ITERATIVE_SCAN_OFF ? &so->discarded : NULL, true, &so->tuples);
|
||||
return HnswSearchLayer(base, q, ep, hnsw_ef_search, 0, index, support, m, false, NULL, &so->v, hnsw_iterative_scan != HNSW_ITERATIVE_SCAN_OFF ? &so->discarded : NULL, true, &so->tuples, false);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -76,7 +83,7 @@ ResumeScanItems(IndexScanDesc scan)
|
||||
ep = lappend(ep, sc);
|
||||
}
|
||||
|
||||
return HnswSearchLayer(base, &so->q, ep, batch_size, 0, index, &so->support, so->m, false, NULL, false, &so->v, &so->discarded, false, &so->tuples);
|
||||
return HnswSearchLayer(base, &so->q, ep, batch_size, 0, index, &so->support, so->m, false, NULL, &so->v, &so->discarded, false, &so->tuples, false);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -100,7 +107,7 @@ GetScanValue(IndexScanDesc scan)
|
||||
|
||||
/* Normalize if needed */
|
||||
if (so->support.normprocinfo != NULL)
|
||||
value = HnswNormValue(so->typeInfo, so->support.collation[0], value);
|
||||
value = HnswNormValue(so->typeInfo, so->support.collation, value);
|
||||
}
|
||||
|
||||
return value;
|
||||
@@ -146,7 +153,7 @@ hnswbeginscan(Relation index, int nkeys, int norderbys)
|
||||
/* Calculate max memory */
|
||||
/* Add 256 extra bytes to fill last block when close */
|
||||
maxMemory = (double) work_mem * hnsw_scan_mem_multiplier * 1024.0 + 256;
|
||||
so->maxMemory = Min(maxMemory, (double) SIZE_MAX);
|
||||
so->maxMemory = Min(maxMemory, (double) (SIZE_MAX / 2));
|
||||
|
||||
scan->opaque = so;
|
||||
|
||||
@@ -287,7 +294,7 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
||||
element = HnswPtrAccess(base, sc->element);
|
||||
|
||||
/* Move to next element if no valid heap TIDs */
|
||||
if (!sc->matches || element->heaptidsLength == 0)
|
||||
if (element->heaptidsLength == 0)
|
||||
{
|
||||
so->w = list_delete_last(so->w);
|
||||
|
||||
|
||||
421
src/hnswutils.c
421
src/hnswutils.c
@@ -2,23 +2,29 @@
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "catalog/pg_type.h"
|
||||
#include "catalog/pg_type_d.h"
|
||||
#include "common/hashfn.h"
|
||||
#include "fmgr.h"
|
||||
#include "hnsw.h"
|
||||
#include "lib/pairingheap.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "port/atomics.h"
|
||||
#include "sparsevec.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "utils/datum.h"
|
||||
#include "utils/memdebug.h"
|
||||
#include "utils/rel.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
#include "storage/read_stream.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM < 170000
|
||||
static inline uint64
|
||||
murmurhash64(uint64 data)
|
||||
@@ -150,39 +156,11 @@ HnswOptionalProcInfo(Relation index, uint16 procnum)
|
||||
void
|
||||
HnswInitSupport(HnswSupport * support, Relation index)
|
||||
{
|
||||
support->procinfo[0] = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
||||
|
||||
if (IndexRelationGetNumberOfKeyAttributes(index) > 1)
|
||||
support->procinfo[1] = index_getprocinfo(index, 2, HNSW_ATTRIBUTE_DISTANCE_PROC);
|
||||
|
||||
support->collation = index->rd_indcollation;
|
||||
support->procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
||||
support->collation = index->rd_indcollation[0];
|
||||
support->normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get element tuple size
|
||||
*/
|
||||
Size
|
||||
HnswGetElementTupleSize(char *base, HnswElement element, bool useIndexTuple)
|
||||
{
|
||||
Size size;
|
||||
|
||||
if (useIndexTuple)
|
||||
{
|
||||
IndexTuple itup = HnswPtrAccess(base, element->itup);
|
||||
|
||||
size = IndexTupleSize(itup);
|
||||
}
|
||||
else
|
||||
{
|
||||
Pointer valuePtr = HnswPtrAccess(base, element->value);
|
||||
|
||||
size = VARSIZE_ANY(valuePtr);
|
||||
}
|
||||
|
||||
return HNSW_ELEMENT_TUPLE_SIZE(size);
|
||||
}
|
||||
|
||||
/*
|
||||
* Normalize value
|
||||
*/
|
||||
@@ -198,38 +176,7 @@ HnswNormValue(const HnswTypeInfo * typeInfo, Oid collation, Datum value)
|
||||
bool
|
||||
HnswCheckNorm(HnswSupport * support, Datum value)
|
||||
{
|
||||
return DatumGetFloat8(FunctionCall1Coll(support->normprocinfo, support->collation[0], value)) > 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Check if index tuples are equal
|
||||
*/
|
||||
bool
|
||||
HnswIndexTupleIsEqual(IndexTuple a, IndexTuple b, TupleDesc tupdesc)
|
||||
{
|
||||
for (int i = 0; i < tupdesc->natts; i++)
|
||||
{
|
||||
bool nullA;
|
||||
bool nullB;
|
||||
|
||||
Datum datumA = index_getattr(a, i + 1, tupdesc, &nullA);
|
||||
Datum datumB = index_getattr(b, i + 1, tupdesc, &nullB);
|
||||
|
||||
if (nullA || nullB)
|
||||
{
|
||||
if (nullA != nullB)
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
Form_pg_attribute att = TupleDescAttr(tupdesc, i);
|
||||
|
||||
if (!datumIsEqual(datumA, datumB, att->attbyval, att->attlen))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
return DatumGetFloat8(FunctionCall1Coll(support->normprocinfo, support->collation, value)) > 0;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -319,8 +266,7 @@ HnswInitElement(char *base, ItemPointer heaptid, int m, double ml, int maxLevel,
|
||||
|
||||
HnswInitNeighbors(base, element, m, allocator);
|
||||
|
||||
HnswPtrStore(base, element->value, (Pointer) NULL);
|
||||
HnswPtrStore(base, element->itup, (IndexTuple) NULL);
|
||||
HnswPtrStore(base, element->value, (char *) NULL);
|
||||
|
||||
return element;
|
||||
}
|
||||
@@ -346,8 +292,7 @@ HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno)
|
||||
element->blkno = blkno;
|
||||
element->offno = offno;
|
||||
HnswPtrStore(base, element->neighbors, (HnswNeighborArrayPtr *) NULL);
|
||||
HnswPtrStore(base, element->value, (Pointer) NULL);
|
||||
HnswPtrStore(base, element->itup, (IndexTuple) NULL);
|
||||
HnswPtrStore(base, element->value, (char *) NULL);
|
||||
return element;
|
||||
}
|
||||
|
||||
@@ -460,13 +405,11 @@ HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, Bloc
|
||||
}
|
||||
|
||||
/*
|
||||
* Form index tuple
|
||||
* Form index value
|
||||
*/
|
||||
bool
|
||||
HnswFormIndexTuple(IndexTuple *out, Datum *values, bool *isnull, const HnswTypeInfo * typeInfo, HnswSupport * support, TupleDesc tupdesc)
|
||||
HnswFormIndexValue(Datum *out, Datum *values, bool *isnull, const HnswTypeInfo * typeInfo, HnswSupport * support)
|
||||
{
|
||||
Datum newValues[2];
|
||||
|
||||
/* Detoast once for all calls */
|
||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||
|
||||
@@ -480,14 +423,10 @@ HnswFormIndexTuple(IndexTuple *out, Datum *values, bool *isnull, const HnswTypeI
|
||||
if (!HnswCheckNorm(support, value))
|
||||
return false;
|
||||
|
||||
value = HnswNormValue(typeInfo, support->collation[0], value);
|
||||
value = HnswNormValue(typeInfo, support->collation, value);
|
||||
}
|
||||
|
||||
newValues[0] = value;
|
||||
for (int i = 1; i < tupdesc->natts; i++)
|
||||
newValues[i] = values[i];
|
||||
|
||||
*out = index_form_tuple(tupdesc, newValues, isnull);
|
||||
*out = value;
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -496,8 +435,10 @@ HnswFormIndexTuple(IndexTuple *out, Datum *values, bool *isnull, const HnswTypeI
|
||||
* Set element tuple, except for neighbor info
|
||||
*/
|
||||
void
|
||||
HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element, bool useIndexTuple)
|
||||
HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element)
|
||||
{
|
||||
Pointer valuePtr = HnswPtrAccess(base, element->value);
|
||||
|
||||
etup->type = HNSW_ELEMENT_TUPLE_TYPE;
|
||||
etup->level = element->level;
|
||||
etup->deleted = 0;
|
||||
@@ -509,19 +450,7 @@ HnswSetElementTuple(char *base, HnswElementTuple etup, HnswElement element, bool
|
||||
else
|
||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||
}
|
||||
|
||||
if (useIndexTuple)
|
||||
{
|
||||
IndexTuple itup = HnswPtrAccess(base, element->itup);
|
||||
|
||||
memcpy(&etup->data, itup, IndexTupleSize(itup));
|
||||
}
|
||||
else
|
||||
{
|
||||
Pointer valuePtr = HnswPtrAccess(base, element->value);
|
||||
|
||||
memcpy(&etup->data, valuePtr, VARSIZE_ANY(valuePtr));
|
||||
}
|
||||
memcpy(&etup->data, valuePtr, VARSIZE_ANY(valuePtr));
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -563,7 +492,7 @@ HnswSetNeighborTuple(char *base, HnswNeighborTuple ntup, HnswElement e, int m)
|
||||
* Load an element from a tuple
|
||||
*/
|
||||
void
|
||||
HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec, Relation index)
|
||||
HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec)
|
||||
{
|
||||
element->level = etup->level;
|
||||
element->deleted = etup->deleted;
|
||||
@@ -587,135 +516,31 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
||||
if (loadVec)
|
||||
{
|
||||
char *base = NULL;
|
||||
Datum value = datumCopy(PointerGetDatum(&etup->data), false, -1);
|
||||
|
||||
if (HnswUseIndexTuple(index))
|
||||
{
|
||||
IndexTuple itup = CopyIndexTuple((IndexTuple) &etup->data);
|
||||
TupleDesc tupdesc = RelationGetDescr(index);
|
||||
bool unused;
|
||||
|
||||
HnswPtrStore(base, element->itup, itup);
|
||||
HnswPtrStore(base, element->value, DatumGetPointer(index_getattr(itup, 1, tupdesc, &unused)));
|
||||
}
|
||||
else
|
||||
{
|
||||
Datum value = datumCopy(PointerGetDatum(&etup->data), false, -1);
|
||||
|
||||
HnswPtrStore(base, element->value, DatumGetPointer(value));
|
||||
}
|
||||
HnswPtrStore(base, element->value, (char *) DatumGetPointer(value));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the attribute distance
|
||||
*/
|
||||
static inline double
|
||||
AttributeDistance(double e)
|
||||
{
|
||||
/* TODO Better bias */
|
||||
/* must be >> max(w * g) + 1 / log10(2) */
|
||||
double bias = 4.32;
|
||||
|
||||
return e > 0 ? bias - 1.0 / log10(e + 1) : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate the distance between values
|
||||
*/
|
||||
static double
|
||||
HnswGetDistance(IndexTuple itup, Datum vec, HnswQuery * q, Relation index, HnswSupport * support, bool *matches)
|
||||
static inline double
|
||||
HnswGetDistance(Datum a, Datum b, HnswSupport * support)
|
||||
{
|
||||
double g;
|
||||
|
||||
if (DatumGetPointer(q->value) == NULL)
|
||||
g = 0;
|
||||
else
|
||||
g = DatumGetFloat8(FunctionCall2Coll(support->procinfo[0], support->collation[0], q->value, vec));
|
||||
|
||||
Assert(PointerIsValid(matches));
|
||||
*matches = true;
|
||||
|
||||
if (IndexRelationGetNumberOfKeyAttributes(index) > 1)
|
||||
{
|
||||
double w = 0.25;
|
||||
double e = 0.0;
|
||||
TupleDesc tupdesc = RelationGetDescr(index);
|
||||
|
||||
if (q->keyData)
|
||||
{
|
||||
/* TODO need to pass length of key data */
|
||||
int keyCount = 1;
|
||||
|
||||
for (int i = 0; i < keyCount; i++)
|
||||
{
|
||||
ScanKey key = &q->keyData[i];
|
||||
bool isnull;
|
||||
Datum value = index_getattr(itup, key->sk_attno, tupdesc, &isnull);
|
||||
bool attnull = key->sk_flags & SK_ISNULL;
|
||||
|
||||
if (isnull || attnull)
|
||||
{
|
||||
if (isnull != attnull)
|
||||
{
|
||||
e += 1000;
|
||||
*matches = false;
|
||||
}
|
||||
}
|
||||
else if (!DatumGetBool(FunctionCall2Coll(&key->sk_func, key->sk_collation, value, key->sk_argument)))
|
||||
{
|
||||
double ei = fabs(DatumGetFloat8(FunctionCall2Coll(support->procinfo[key->sk_attno - 1], support->collation[key->sk_attno - 1], value, key->sk_argument)));
|
||||
|
||||
if (ei > 0)
|
||||
e += ei;
|
||||
else
|
||||
/* Distance is zero for inequality */
|
||||
e += 1000;
|
||||
|
||||
*matches = false;
|
||||
}
|
||||
}
|
||||
|
||||
return w * g + AttributeDistance(e);
|
||||
}
|
||||
else if (q->itup)
|
||||
{
|
||||
int keyCount = IndexRelationGetNumberOfKeyAttributes(index) - 1;
|
||||
|
||||
for (int i = 0; i < keyCount; i++)
|
||||
{
|
||||
bool isnull;
|
||||
bool attnull;
|
||||
Datum value = index_getattr(itup, i + 2, tupdesc, &isnull);
|
||||
Datum value2 = index_getattr(q->itup, i + 2, tupdesc, &attnull);
|
||||
|
||||
if (isnull || attnull)
|
||||
{
|
||||
if (isnull != attnull)
|
||||
e += 1000;
|
||||
}
|
||||
else
|
||||
e += fabs(DatumGetFloat8(FunctionCall2Coll(support->procinfo[i + 1], support->collation[i + 1], value, value2)));
|
||||
}
|
||||
|
||||
return w * g + AttributeDistance(e);
|
||||
}
|
||||
}
|
||||
|
||||
return g;
|
||||
return DatumGetFloat8(FunctionCall2Coll(support->procinfo, support->collation, a, b));
|
||||
}
|
||||
|
||||
/*
|
||||
* Load an element and optionally get its distance from q
|
||||
*/
|
||||
static void
|
||||
HnswLoadElementImpl(BlockNumber blkno, OffsetNumber offno, double *distance, bool *matches, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance, HnswElement * element)
|
||||
HnswLoadElementImpl(Buffer buf, OffsetNumber offno, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance, HnswElement * element)
|
||||
{
|
||||
Buffer buf;
|
||||
Page page;
|
||||
HnswElementTuple etup;
|
||||
|
||||
/* Read vector */
|
||||
buf = ReadBuffer(index, blkno);
|
||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||
page = BufferGetPage(buf);
|
||||
|
||||
@@ -726,32 +551,19 @@ HnswLoadElementImpl(BlockNumber blkno, OffsetNumber offno, double *distance, boo
|
||||
/* Calculate distance */
|
||||
if (distance != NULL)
|
||||
{
|
||||
IndexTuple itup = NULL;
|
||||
Datum value;
|
||||
|
||||
if (HnswUseIndexTuple(index))
|
||||
{
|
||||
TupleDesc tupdesc = RelationGetDescr(index);
|
||||
bool unused;
|
||||
|
||||
itup = (IndexTuple) &etup->data;
|
||||
value = index_getattr(itup, 1, tupdesc, &unused);
|
||||
}
|
||||
if (DatumGetPointer(q->value) == NULL)
|
||||
*distance = 0;
|
||||
else
|
||||
{
|
||||
value = PointerGetDatum(&etup->data);
|
||||
}
|
||||
|
||||
*distance = HnswGetDistance(itup, value, q, index, support, matches);
|
||||
*distance = HnswGetDistance(q->value, PointerGetDatum(&etup->data), support);
|
||||
}
|
||||
|
||||
/* Load element */
|
||||
if (distance == NULL || maxDistance == NULL || *distance < *maxDistance)
|
||||
{
|
||||
if (*element == NULL)
|
||||
*element = HnswInitElementFromBlock(blkno, offno);
|
||||
*element = HnswInitElementFromBlock(BufferGetBlockNumber(buf), offno);
|
||||
|
||||
HnswLoadElementFromTuple(*element, etup, true, loadVec, index);
|
||||
HnswLoadElementFromTuple(*element, etup, true, loadVec);
|
||||
}
|
||||
|
||||
UnlockReleaseBuffer(buf);
|
||||
@@ -761,34 +573,34 @@ HnswLoadElementImpl(BlockNumber blkno, OffsetNumber offno, double *distance, boo
|
||||
* Load an element and optionally get its distance from q
|
||||
*/
|
||||
void
|
||||
HnswLoadElement(HnswElement element, double *distance, bool *matches, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance)
|
||||
HnswLoadElement(HnswElement element, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance)
|
||||
{
|
||||
HnswLoadElementImpl(element->blkno, element->offno, distance, matches, q, index, support, loadVec, maxDistance, &element);
|
||||
Buffer buf = ReadBuffer(index, element->blkno);
|
||||
|
||||
HnswLoadElementImpl(buf, element->offno, distance, q, index, support, loadVec, maxDistance, &element);
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the distance for an element
|
||||
*/
|
||||
static double
|
||||
GetElementDistance(char *base, HnswElement element, bool *matches, HnswQuery * q, Relation index, HnswSupport * support)
|
||||
GetElementDistance(char *base, HnswElement element, HnswQuery * q, HnswSupport * support)
|
||||
{
|
||||
Datum value = HnswGetValue(base, element);
|
||||
IndexTuple itup = HnswPtrAccess(base, element->itup);
|
||||
|
||||
return HnswGetDistance(itup, value, q, index, support, matches);
|
||||
return HnswGetDistance(q->value, value, support);
|
||||
}
|
||||
|
||||
/*
|
||||
* Allocate a search candidate
|
||||
*/
|
||||
static HnswSearchCandidate *
|
||||
HnswInitSearchCandidate(char *base, HnswElement element, double distance, bool matches)
|
||||
HnswInitSearchCandidate(char *base, HnswElement element, double distance)
|
||||
{
|
||||
HnswSearchCandidate *sc = palloc(sizeof(HnswSearchCandidate));
|
||||
|
||||
HnswPtrStore(base, sc->element, element);
|
||||
sc->distance = distance;
|
||||
sc->matches = matches;
|
||||
return sc;
|
||||
}
|
||||
|
||||
@@ -796,17 +608,17 @@ HnswInitSearchCandidate(char *base, HnswElement element, double distance, bool m
|
||||
* Create a candidate for the entry point
|
||||
*/
|
||||
HnswSearchCandidate *
|
||||
HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, bool inMemory)
|
||||
HnswEntryCandidate(char *base, HnswElement entryPoint, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec)
|
||||
{
|
||||
bool inMemory = index == NULL;
|
||||
double distance;
|
||||
bool matches;
|
||||
|
||||
if (inMemory)
|
||||
distance = GetElementDistance(base, entryPoint, &matches, q, index, support);
|
||||
distance = GetElementDistance(base, entryPoint, q, support);
|
||||
else
|
||||
HnswLoadElement(entryPoint, &distance, &matches, q, index, support, loadVec, NULL);
|
||||
HnswLoadElement(entryPoint, &distance, q, index, support, loadVec, NULL);
|
||||
|
||||
return HnswInitSearchCandidate(base, entryPoint, distance, matches);
|
||||
return HnswInitSearchCandidate(base, entryPoint, distance);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -1005,11 +817,31 @@ HnswLoadUnvisitedFromDisk(HnswElement element, HnswUnvisited * unvisited, int *u
|
||||
}
|
||||
}
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
/*
|
||||
* Get next block number for read stream
|
||||
*/
|
||||
static BlockNumber
|
||||
HnswReadStreamNextBlock(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
|
||||
{
|
||||
HnswReadStreamData *streamData = callback_private_data;
|
||||
OffsetNumber *offno = per_buffer_data;
|
||||
HnswUnvisited *uv;
|
||||
|
||||
if (streamData->visited == streamData->unvisitedLength)
|
||||
return InvalidBlockNumber;
|
||||
|
||||
uv = &streamData->unvisited[streamData->visited++];
|
||||
*offno = ItemPointerGetOffsetNumber(&uv->indextid);
|
||||
return ItemPointerGetBlockNumber(&uv->indextid);
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Algorithm 2 from paper
|
||||
*/
|
||||
List *
|
||||
HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, bool inMemory, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples)
|
||||
HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation index, HnswSupport * support, int m, bool inserting, HnswElement skipElement, visited_hash * v, pairingheap **discarded, bool initVisited, int64 *tuples, bool maintenance)
|
||||
{
|
||||
List *w = NIL;
|
||||
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||
@@ -1022,8 +854,22 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
int lm = HnswGetLayerM(m, lc);
|
||||
HnswUnvisited *unvisited = palloc(lm * sizeof(HnswUnvisited));
|
||||
int unvisitedLength;
|
||||
uint64 additional = 0;
|
||||
uint64 maxAdditional = q->keyData && lc == 0 ? 10000 : 0;
|
||||
bool inMemory = index == NULL;
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
HnswReadStreamData streamData;
|
||||
ReadStream *stream = NULL;
|
||||
|
||||
if (!inMemory)
|
||||
{
|
||||
int flags = READ_STREAM_USE_BATCHING;
|
||||
|
||||
if (maintenance)
|
||||
flags |= READ_STREAM_MAINTENANCE;
|
||||
|
||||
stream = read_stream_begin_relation(flags, NULL, index, MAIN_FORKNUM, HnswReadStreamNextBlock, &streamData, sizeof(OffsetNumber));
|
||||
}
|
||||
#endif
|
||||
|
||||
if (v == NULL)
|
||||
{
|
||||
@@ -1064,10 +910,6 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
pairingheap_add(C, &sc->c_node);
|
||||
pairingheap_add(W, &sc->w_node);
|
||||
|
||||
/* Do not count elements that do not match filter towards ef */
|
||||
if (!sc->matches && ++additional <= maxAdditional)
|
||||
continue;
|
||||
|
||||
/*
|
||||
* Do not count elements being deleted towards ef when vacuuming. It
|
||||
* would be ideal to do this for inserts as well, but this could
|
||||
@@ -1091,47 +933,78 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
if (inMemory)
|
||||
HnswLoadUnvisitedFromMemory(base, cElement, unvisited, &unvisitedLength, v, lc, localNeighborhood, neighborhoodSize);
|
||||
else
|
||||
{
|
||||
HnswLoadUnvisitedFromDisk(cElement, unvisited, &unvisitedLength, v, index, m, lm, lc);
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
read_stream_resume(stream);
|
||||
|
||||
streamData.unvisited = unvisited;
|
||||
streamData.unvisitedLength = unvisitedLength;
|
||||
streamData.visited = 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* OK to count elements instead of tuples */
|
||||
if (tuples != NULL)
|
||||
(*tuples) += unvisitedLength;
|
||||
|
||||
for (int i = 0; i < unvisitedLength; i++)
|
||||
for (int i = 0;; i++)
|
||||
{
|
||||
HnswElement eElement;
|
||||
HnswSearchCandidate *e;
|
||||
double eDistance;
|
||||
bool eMatches;
|
||||
bool alwaysAdd = wlen < ef;
|
||||
|
||||
f = HnswGetSearchCandidate(w_node, pairingheap_first(W));
|
||||
|
||||
if (inMemory)
|
||||
{
|
||||
if (i == unvisitedLength)
|
||||
break;
|
||||
|
||||
eElement = unvisited[i].element;
|
||||
eDistance = GetElementDistance(base, eElement, &eMatches, q, index, support);
|
||||
eDistance = GetElementDistance(base, eElement, q, support);
|
||||
}
|
||||
else
|
||||
{
|
||||
ItemPointer indextid = &unvisited[i].indextid;
|
||||
BlockNumber blkno = ItemPointerGetBlockNumber(indextid);
|
||||
OffsetNumber offno = ItemPointerGetOffsetNumber(indextid);
|
||||
Buffer buf;
|
||||
OffsetNumber offno;
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
void *offnoPtr;
|
||||
|
||||
buf = read_stream_next_buffer(stream, &offnoPtr);
|
||||
|
||||
if (!BufferIsValid(buf))
|
||||
break;
|
||||
|
||||
offno = *((OffsetNumber *) offnoPtr);
|
||||
#else
|
||||
ItemPointer indextid;
|
||||
|
||||
if (i == unvisitedLength)
|
||||
break;
|
||||
|
||||
indextid = &unvisited[i].indextid;
|
||||
buf = ReadBuffer(index, ItemPointerGetBlockNumber(indextid));
|
||||
offno = ItemPointerGetOffsetNumber(indextid);
|
||||
#endif
|
||||
|
||||
/* Avoid any allocations if not adding */
|
||||
eElement = NULL;
|
||||
HnswLoadElementImpl(blkno, offno, &eDistance, &eMatches, q, index, support, inserting, alwaysAdd || discarded != NULL ? NULL : &f->distance, &eElement);
|
||||
HnswLoadElementImpl(buf, offno, &eDistance, q, index, support, inserting, alwaysAdd || discarded != NULL ? NULL : &f->distance, &eElement);
|
||||
|
||||
if (eElement == NULL)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (eElement == NULL || !(eDistance < f->distance || alwaysAdd))
|
||||
if (!(eDistance < f->distance || alwaysAdd))
|
||||
{
|
||||
if (discarded != NULL)
|
||||
{
|
||||
/* Create a new candidate */
|
||||
e = HnswInitSearchCandidate(base, eElement, eDistance, eMatches);
|
||||
e = HnswInitSearchCandidate(base, eElement, eDistance);
|
||||
pairingheap_add(*discarded, &e->w_node);
|
||||
}
|
||||
|
||||
@@ -1143,7 +1016,7 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
continue;
|
||||
|
||||
/* Create a new candidate */
|
||||
e = HnswInitSearchCandidate(base, eElement, eDistance, eMatches);
|
||||
e = HnswInitSearchCandidate(base, eElement, eDistance);
|
||||
pairingheap_add(C, &e->c_node);
|
||||
pairingheap_add(W, &e->w_node);
|
||||
|
||||
@@ -1154,10 +1027,6 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
*/
|
||||
if (CountElement(skipElement, eElement))
|
||||
{
|
||||
/* Do not count elements that do not match filter towards ef */
|
||||
if (!e->matches && ++additional <= maxAdditional)
|
||||
continue;
|
||||
|
||||
wlen++;
|
||||
|
||||
/* No need to decrement wlen */
|
||||
@@ -1180,6 +1049,11 @@ HnswSearchLayer(char *base, HnswQuery * q, List *ep, int ef, int lc, Relation in
|
||||
w = lappend(w, sc);
|
||||
}
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
if (!inMemory)
|
||||
read_stream_end(stream);
|
||||
#endif
|
||||
|
||||
return w;
|
||||
}
|
||||
|
||||
@@ -1235,24 +1109,18 @@ CompareCandidateDistancesOffset(const ListCell *a, const ListCell *b)
|
||||
* Check if an element is closer to q than any element from R
|
||||
*/
|
||||
static bool
|
||||
CheckElementCloser(char *base, HnswCandidate * e, List *r, Relation index, HnswSupport * support)
|
||||
CheckElementCloser(char *base, HnswCandidate * e, List *r, HnswSupport * support)
|
||||
{
|
||||
HnswElement eElement = HnswPtrAccess(base, e->element);
|
||||
HnswQuery q;
|
||||
Datum eValue = HnswGetValue(base, eElement);
|
||||
ListCell *lc2;
|
||||
|
||||
q.value = HnswGetValue(base, eElement);
|
||||
q.itup = HnswPtrAccess(base, eElement->itup);
|
||||
q.keyData = NULL;
|
||||
|
||||
foreach(lc2, r)
|
||||
{
|
||||
HnswCandidate *ri = lfirst(lc2);
|
||||
HnswElement riElement = HnswPtrAccess(base, ri->element);
|
||||
Datum riValue = HnswGetValue(base, riElement);
|
||||
IndexTuple ritup = HnswPtrAccess(base, riElement->itup);
|
||||
bool matches;
|
||||
float distance = HnswGetDistance(ritup, riValue, &q, index, support, &matches);
|
||||
float distance = HnswGetDistance(eValue, riValue, support);
|
||||
|
||||
if (distance <= e->distance)
|
||||
return false;
|
||||
@@ -1265,7 +1133,7 @@ CheckElementCloser(char *base, HnswCandidate * e, List *r, Relation index, HnswS
|
||||
* Algorithm 4 from paper
|
||||
*/
|
||||
static List *
|
||||
SelectNeighbors(char *base, List *c, int lm, Relation index, HnswSupport * support, bool *closerSet, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
||||
SelectNeighbors(char *base, List *c, int lm, HnswSupport * support, bool *closerSet, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
||||
{
|
||||
List *r = NIL;
|
||||
List *w = list_copy(c);
|
||||
@@ -1299,7 +1167,7 @@ SelectNeighbors(char *base, List *c, int lm, Relation index, HnswSupport * suppo
|
||||
|
||||
/* Use previous state of r and wd to skip work when possible */
|
||||
if (mustCalculate)
|
||||
e->closer = CheckElementCloser(base, e, r, index, support);
|
||||
e->closer = CheckElementCloser(base, e, r, support);
|
||||
else if (list_length(added) > 0)
|
||||
{
|
||||
/* Keep Valgrind happy for in-memory, parallel builds */
|
||||
@@ -1312,7 +1180,8 @@ SelectNeighbors(char *base, List *c, int lm, Relation index, HnswSupport * suppo
|
||||
*/
|
||||
if (e->closer)
|
||||
{
|
||||
e->closer = CheckElementCloser(base, e, added, index, support);
|
||||
e->closer = CheckElementCloser(base, e, added, support);
|
||||
|
||||
if (!e->closer)
|
||||
removedAny = true;
|
||||
}
|
||||
@@ -1324,7 +1193,7 @@ SelectNeighbors(char *base, List *c, int lm, Relation index, HnswSupport * suppo
|
||||
*/
|
||||
if (removedAny)
|
||||
{
|
||||
e->closer = CheckElementCloser(base, e, r, index, support);
|
||||
e->closer = CheckElementCloser(base, e, r, support);
|
||||
if (e->closer)
|
||||
added = lappend(added, e);
|
||||
}
|
||||
@@ -1332,7 +1201,7 @@ SelectNeighbors(char *base, List *c, int lm, Relation index, HnswSupport * suppo
|
||||
}
|
||||
else if (e == newCandidate)
|
||||
{
|
||||
e->closer = CheckElementCloser(base, e, r, index, support);
|
||||
e->closer = CheckElementCloser(base, e, r, support);
|
||||
if (e->closer)
|
||||
added = lappend(added, e);
|
||||
}
|
||||
@@ -1409,7 +1278,7 @@ HnswUpdateConnection(char *base, HnswNeighborArray * neighbors, HnswElement newE
|
||||
c = lappend(c, &neighbors->items[i]);
|
||||
c = lappend(c, &newHc);
|
||||
|
||||
SelectNeighbors(base, c, lm, index, support, &neighbors->closerSet, &newHc, &pruned, true);
|
||||
SelectNeighbors(base, c, lm, support, &neighbors->closerSet, &newHc, &pruned, true);
|
||||
|
||||
/* Should not happen */
|
||||
if (pruned == NULL)
|
||||
@@ -1480,19 +1349,17 @@ PrecomputeHash(char *base, HnswElement element)
|
||||
* Algorithm 1 from paper
|
||||
*/
|
||||
void
|
||||
HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool inMemory)
|
||||
HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint, Relation index, HnswSupport * support, int m, int efConstruction, bool existing, bool maintenance)
|
||||
{
|
||||
List *ep;
|
||||
List *w;
|
||||
int level = element->level;
|
||||
int entryLevel;
|
||||
HnswQuery q;
|
||||
|
||||
HnswElement skipElement = existing ? element : NULL;
|
||||
bool inMemory = index == NULL;
|
||||
|
||||
q.value = HnswGetValue(base, element);
|
||||
q.itup = HnswPtrAccess(base, element->itup);
|
||||
q.keyData = NULL;
|
||||
|
||||
/* Precompute hash */
|
||||
if (inMemory)
|
||||
@@ -1503,13 +1370,13 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
||||
return;
|
||||
|
||||
/* Get entry point and level */
|
||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, &q, index, support, true, inMemory));
|
||||
ep = list_make1(HnswEntryCandidate(base, entryPoint, &q, index, support, true));
|
||||
entryLevel = entryPoint->level;
|
||||
|
||||
/* 1st phase: greedy search to insert level */
|
||||
for (int lc = entryLevel; lc >= level + 1; lc--)
|
||||
{
|
||||
w = HnswSearchLayer(base, &q, ep, 1, lc, index, support, m, true, skipElement, inMemory, NULL, NULL, true, NULL);
|
||||
w = HnswSearchLayer(base, &q, ep, 1, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL, maintenance);
|
||||
ep = w;
|
||||
}
|
||||
|
||||
@@ -1528,7 +1395,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
||||
List *lw = NIL;
|
||||
ListCell *lc2;
|
||||
|
||||
w = HnswSearchLayer(base, &q, ep, efConstruction, lc, index, support, m, true, skipElement, inMemory, NULL, NULL, true, NULL);
|
||||
w = HnswSearchLayer(base, &q, ep, efConstruction, lc, index, support, m, true, skipElement, NULL, NULL, true, NULL, maintenance);
|
||||
|
||||
/* Convert search candidates to candidates */
|
||||
foreach(lc2, w)
|
||||
@@ -1552,7 +1419,7 @@ HnswFindElementNeighbors(char *base, HnswElement element, HnswElement entryPoint
|
||||
* sortCandidates to true for in-memory builds to enable closer
|
||||
* caching, but there does not seem to be a difference in performance.
|
||||
*/
|
||||
neighbors = SelectNeighbors(base, lw, lm, index, support, &HnswGetNeighbors(base, element, lc)->closerSet, NULL, NULL, false);
|
||||
neighbors = SelectNeighbors(base, lw, lm, support, &HnswGetNeighbors(base, element, lc)->closerSet, NULL, NULL, false);
|
||||
|
||||
AddConnections(base, element, neighbors, lc);
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "commands/vacuum.h"
|
||||
#include "hnsw.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/rel.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
@@ -178,7 +179,12 @@ NeedsUpdated(HnswVacuumState * vacuumstate, HnswElement element)
|
||||
/* Also update if layer 0 is not full */
|
||||
/* This could indicate too many candidates being deleted during insert */
|
||||
if (!needsUpdated)
|
||||
{
|
||||
/* Keep clang-tidy happy */
|
||||
Assert(ntup->count > 0);
|
||||
|
||||
needsUpdated = !ItemPointerIsValid(&ntup->indextids[ntup->count - 1]);
|
||||
}
|
||||
|
||||
UnlockReleaseBuffer(buf);
|
||||
|
||||
@@ -212,7 +218,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
||||
element->heaptidsLength = 0;
|
||||
|
||||
/* Find neighbors for element, skipping itself */
|
||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, true, false);
|
||||
HnswFindElementNeighbors(base, element, entryPoint, index, support, m, efConstruction, true, true);
|
||||
|
||||
/* Zero memory for each element */
|
||||
MemSet(ntup, 0, HNSW_TUPLE_ALLOC_SIZE);
|
||||
@@ -264,7 +270,7 @@ RepairGraphEntryPoint(HnswVacuumState * vacuumstate)
|
||||
LockPage(index, HNSW_UPDATE_LOCK, ShareLock);
|
||||
|
||||
/* Load element */
|
||||
HnswLoadElement(highestPoint, NULL, NULL, NULL, index, support, true, NULL);
|
||||
HnswLoadElement(highestPoint, NULL, NULL, index, support, true, NULL);
|
||||
|
||||
/* Repair if needed */
|
||||
if (NeedsUpdated(vacuumstate, highestPoint))
|
||||
@@ -302,7 +308,7 @@ RepairGraphEntryPoint(HnswVacuumState * vacuumstate)
|
||||
* is outdated, this can remove connections at higher levels in
|
||||
* the graph until they are repaired, but this should be fine.
|
||||
*/
|
||||
HnswLoadElement(entryPoint, NULL, NULL, NULL, index, support, true, NULL);
|
||||
HnswLoadElement(entryPoint, NULL, NULL, index, support, true, NULL);
|
||||
|
||||
if (NeedsUpdated(vacuumstate, entryPoint))
|
||||
{
|
||||
@@ -378,7 +384,7 @@ RepairGraph(HnswVacuumState * vacuumstate)
|
||||
|
||||
/* Create an element */
|
||||
element = HnswInitElementFromBlock(blkno, offno);
|
||||
HnswLoadElementFromTuple(element, etup, false, true, index);
|
||||
HnswLoadElementFromTuple(element, etup, false, true);
|
||||
|
||||
elements = lappend(elements, element);
|
||||
}
|
||||
@@ -448,7 +454,6 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
BlockNumber insertPage = InvalidBlockNumber;
|
||||
Relation index = vacuumstate->index;
|
||||
BufferAccessStrategy bas = vacuumstate->bas;
|
||||
bool useIndexTuple = HnswUseIndexTuple(index);
|
||||
|
||||
/*
|
||||
* Wait for index scans to complete. Scans before this point may contain
|
||||
@@ -529,15 +534,9 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
||||
ntup = (HnswNeighborTuple) PageGetItem(npage, PageGetItemId(npage, neighborOffno));
|
||||
|
||||
/* Overwrite element */
|
||||
/* Use memset instead of MemSet to keep clang-tidy happy */
|
||||
etup->deleted = 1;
|
||||
if (useIndexTuple)
|
||||
{
|
||||
IndexTuple itup = (IndexTuple) &etup->data;
|
||||
|
||||
MemSet(itup, 0, IndexTupleSize(itup));
|
||||
}
|
||||
else
|
||||
MemSet(&etup->data, 0, VARSIZE_ANY(&etup->data));
|
||||
memset(&etup->data, 0, VARSIZE_ANY(&etup->data));
|
||||
|
||||
/* Overwrite neighbors */
|
||||
for (int i = 0; i < ntup->count; i++)
|
||||
|
||||
@@ -2,23 +2,33 @@
|
||||
|
||||
#include <float.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "access/itup.h"
|
||||
#include "access/relscan.h"
|
||||
#include "access/table.h"
|
||||
#include "access/tableam.h"
|
||||
#include "access/tupdesc.h"
|
||||
#include "access/parallel.h"
|
||||
#include "access/xact.h"
|
||||
#include "bitvec.h"
|
||||
#include "access/xloginsert.h"
|
||||
#include "catalog/index.h"
|
||||
#include "catalog/pg_operator_d.h"
|
||||
#include "catalog/pg_type_d.h"
|
||||
#include "commands/progress.h"
|
||||
#include "halfvec.h"
|
||||
#include "fmgr.h"
|
||||
#include "ivfflat.h"
|
||||
#include "miscadmin.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "optimizer/optimizer.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/condition_variable.h"
|
||||
#include "tcop/tcopprot.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "vector.h"
|
||||
#include "utils/rel.h"
|
||||
#include "utils/sampling.h"
|
||||
#include "utils/snapmgr.h"
|
||||
#include "utils/tuplesort.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
@@ -53,15 +63,13 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||
|
||||
/*
|
||||
* Normalize with KMEANS_NORM_PROC since spherical distance function
|
||||
* expects unit vectors
|
||||
* Check with KMEANS_NORM_PROC that the value can be normalized since
|
||||
* spherical distance function expects unit vectors
|
||||
*/
|
||||
if (buildstate->kmeansnormprocinfo != NULL)
|
||||
{
|
||||
if (!IvfflatCheckNorm(buildstate->kmeansnormprocinfo, buildstate->collation, value))
|
||||
return;
|
||||
|
||||
value = IvfflatNormValue(buildstate->typeInfo, buildstate->collation, value);
|
||||
}
|
||||
|
||||
if (samples->length < targsamples)
|
||||
@@ -72,7 +80,7 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
||||
else
|
||||
{
|
||||
if (buildstate->rowstoskip < 0)
|
||||
buildstate->rowstoskip = reservoir_get_next_S(&buildstate->rstate, samples->length, targsamples);
|
||||
buildstate->rowstoskip = reservoir_get_next_S(&buildstate->rstate, buildstate->samplerows, targsamples);
|
||||
|
||||
if (buildstate->rowstoskip <= 0)
|
||||
{
|
||||
@@ -88,6 +96,9 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
|
||||
|
||||
buildstate->rowstoskip -= 1;
|
||||
}
|
||||
|
||||
/* Increment after reservoir_get_next_S */
|
||||
buildstate->samplerows += 1;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -124,6 +135,7 @@ SampleRows(IvfflatBuildState * buildstate)
|
||||
int targsamples = buildstate->samples->maxlen;
|
||||
BlockNumber totalblocks = RelationGetNumberOfBlocks(buildstate->heap);
|
||||
|
||||
buildstate->samplerows = 0;
|
||||
buildstate->rowstoskip = -1;
|
||||
|
||||
BlockSampler_Init(&buildstate->bs, totalblocks, targsamples, RandomInt());
|
||||
@@ -136,6 +148,21 @@ SampleRows(IvfflatBuildState * buildstate)
|
||||
table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||
false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
|
||||
}
|
||||
|
||||
/* Normalize if needed */
|
||||
if (buildstate->kmeansnormprocinfo != NULL)
|
||||
{
|
||||
VectorArray samples = buildstate->samples;
|
||||
|
||||
for (int i = 0; i < samples->length; i++)
|
||||
{
|
||||
Datum value = PointerGetDatum(VectorArrayGet(samples, i));
|
||||
Datum normValue = IvfflatNormValue(buildstate->typeInfo, buildstate->collation, value);
|
||||
|
||||
VectorArraySet(samples, i, DatumGetPointer(normValue));
|
||||
pfree(DatumGetPointer(normValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -365,6 +392,9 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
|
||||
TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
|
||||
TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
|
||||
TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 3, "vector", TupleDescAttr(buildstate->tupdesc, 0)->atttypid, -1, 0);
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
TupleDescFinalize(buildstate->sortdesc);
|
||||
#endif
|
||||
|
||||
buildstate->slot = MakeSingleTupleTableSlot(buildstate->sortdesc, &TTSOpsVirtual);
|
||||
|
||||
@@ -426,7 +456,7 @@ ComputeCenters(IvfflatBuildState * buildstate)
|
||||
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions, buildstate->centers->itemsize);
|
||||
if (buildstate->heap != NULL)
|
||||
{
|
||||
SampleRows(buildstate);
|
||||
IvfflatBench("sample rows", SampleRows(buildstate));
|
||||
|
||||
if (buildstate->samples->length < buildstate->lists)
|
||||
{
|
||||
@@ -641,7 +671,11 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
|
||||
ivfspool->sortstate = InitBuildSortState(buildstate.sortdesc, sortmem, coordinate);
|
||||
buildstate.sortstate = ivfspool->sortstate;
|
||||
scan = table_beginscan_parallel(ivfspool->heap,
|
||||
ParallelTableScanFromIvfflatShared(ivfshared));
|
||||
ParallelTableScanFromIvfflatShared(ivfshared)
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
,SO_NONE
|
||||
#endif
|
||||
);
|
||||
reltuples = table_index_build_scan(ivfspool->heap, ivfspool->index, indexInfo,
|
||||
true, progress, BuildCallback,
|
||||
(void *) &buildstate, scan);
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
#include <float.h>
|
||||
|
||||
#include "access/amapi.h"
|
||||
#include "access/genam.h"
|
||||
#include "access/reloptions.h"
|
||||
#include "commands/progress.h"
|
||||
#include "commands/vacuum.h"
|
||||
#include "fmgr.h"
|
||||
#include "ivfflat.h"
|
||||
#include "nodes/pg_list.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/guc.h"
|
||||
#include "utils/relcache.h"
|
||||
#include "utils/selfuncs.h"
|
||||
#include "utils/spccache.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM < 150000
|
||||
#define MarkGUCPrefixReserved(x) EmitWarningsOnPlaceholders(x)
|
||||
@@ -179,6 +184,64 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(ivfflathandler);
|
||||
Datum
|
||||
ivfflathandler(PG_FUNCTION_ARGS)
|
||||
{
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
static const IndexAmRoutine amroutine = {
|
||||
.type = T_IndexAmRoutine,
|
||||
.amstrategies = 0,
|
||||
.amsupport = 5,
|
||||
.amoptsprocnum = 0,
|
||||
.amcanorder = false,
|
||||
.amcanorderbyop = true,
|
||||
.amcanhash = false,
|
||||
.amconsistentequality = false,
|
||||
.amconsistentordering = false,
|
||||
.amcanbackward = false,
|
||||
.amcanunique = false,
|
||||
.amcanmulticol = false,
|
||||
.amoptionalkey = true,
|
||||
.amsearcharray = false,
|
||||
.amsearchnulls = false,
|
||||
.amstorage = false,
|
||||
.amclusterable = false,
|
||||
.ampredlocks = false,
|
||||
.amcanparallel = false,
|
||||
.amcanbuildparallel = true,
|
||||
.amcaninclude = false,
|
||||
.amusemaintenanceworkmem = false,
|
||||
.amsummarizing = false,
|
||||
.amparallelvacuumoptions = VACUUM_OPTION_PARALLEL_BULKDEL,
|
||||
.amkeytype = InvalidOid,
|
||||
|
||||
.ambuild = ivfflatbuild,
|
||||
.ambuildempty = ivfflatbuildempty,
|
||||
.aminsert = ivfflatinsert,
|
||||
.aminsertcleanup = NULL,
|
||||
.ambulkdelete = ivfflatbulkdelete,
|
||||
.amvacuumcleanup = ivfflatvacuumcleanup,
|
||||
.amcanreturn = NULL,
|
||||
.amcostestimate = ivfflatcostestimate,
|
||||
.amgettreeheight = NULL,
|
||||
.amoptions = ivfflatoptions,
|
||||
.amproperty = NULL,
|
||||
.ambuildphasename = ivfflatbuildphasename,
|
||||
.amvalidate = ivfflatvalidate,
|
||||
.amadjustmembers = NULL,
|
||||
.ambeginscan = ivfflatbeginscan,
|
||||
.amrescan = ivfflatrescan,
|
||||
.amgettuple = ivfflatgettuple,
|
||||
.amgetbitmap = NULL,
|
||||
.amendscan = ivfflatendscan,
|
||||
.ammarkpos = NULL,
|
||||
.amrestrpos = NULL,
|
||||
.amestimateparallelscan = NULL,
|
||||
.aminitparallelscan = NULL,
|
||||
.amparallelrescan = NULL,
|
||||
.amtranslatestrategy = NULL,
|
||||
.amtranslatecmptype = NULL,
|
||||
};
|
||||
|
||||
PG_RETURN_POINTER(&amroutine);
|
||||
#else
|
||||
IndexAmRoutine *amroutine = makeNode(IndexAmRoutine);
|
||||
|
||||
amroutine->amstrategies = 0;
|
||||
@@ -252,4 +315,5 @@ ivfflathandler(PG_FUNCTION_ARGS)
|
||||
#endif
|
||||
|
||||
PG_RETURN_POINTER(amroutine);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "lib/pairingheap.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "port.h" /* for random() */
|
||||
#include "storage/condition_variable.h"
|
||||
#include "utils/sampling.h"
|
||||
#include "utils/tuplesort.h"
|
||||
#include "vector.h"
|
||||
@@ -25,6 +26,10 @@
|
||||
#include "portability/instr_time.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
typedef Pointer Item;
|
||||
#endif
|
||||
|
||||
#define IVFFLAT_MAX_DIM 2000
|
||||
|
||||
/* Support functions */
|
||||
@@ -209,7 +214,8 @@ typedef struct IvfflatBuildState
|
||||
/* Sampling */
|
||||
BlockSamplerData bs;
|
||||
ReservoirStateData rstate;
|
||||
int rowstoskip;
|
||||
double samplerows;
|
||||
double rowstoskip;
|
||||
|
||||
/* Sorting */
|
||||
Tuplesortstate *sortstate;
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
|
||||
#include <float.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "access/itup.h"
|
||||
#include "fmgr.h"
|
||||
#include "ivfflat.h"
|
||||
#include "nodes/execnodes.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "storage/lmgr.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/rel.h"
|
||||
|
||||
/*
|
||||
* Find the list that minimizes the distance function
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "bitvec.h"
|
||||
#include "halfutils.h"
|
||||
#include "halfvec.h"
|
||||
#include "access/genam.h"
|
||||
#include "fmgr.h"
|
||||
#include "ivfflat.h"
|
||||
#include "miscadmin.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/datum.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "vector.h"
|
||||
#include "utils/relcache.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
|
||||
@@ -2,15 +2,26 @@
|
||||
|
||||
#include <float.h>
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/itup.h"
|
||||
#include "access/relscan.h"
|
||||
#include "access/tupdesc.h"
|
||||
#include "catalog/pg_operator_d.h"
|
||||
#include "catalog/pg_type_d.h"
|
||||
#include "fmgr.h"
|
||||
#include "lib/pairingheap.h"
|
||||
#include "ivfflat.h"
|
||||
#include "miscadmin.h"
|
||||
#include "pgstat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "utils/memutils.h"
|
||||
#include "utils/rel.h"
|
||||
#include "utils/snapmgr.h"
|
||||
#include "utils/tuplesort.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
#define GetScanList(ptr) pairingheap_container(IvfflatScanList, ph_node, ptr)
|
||||
#define GetScanListConst(ptr) pairingheap_const_container(IvfflatScanList, ph_node, ptr)
|
||||
@@ -287,6 +298,9 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
||||
so->tupdesc = CreateTemplateTupleDesc(2);
|
||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
|
||||
#if PG_VERSION_NUM >= 190000
|
||||
TupleDescFinalize(so->tupdesc);
|
||||
#endif
|
||||
|
||||
/* Prep sort */
|
||||
so->sortstate = InitScanSortState(so->tupdesc);
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "bitvec.h"
|
||||
#include "catalog/pg_type.h"
|
||||
#include "fmgr.h"
|
||||
#include "halfutils.h"
|
||||
#include "halfvec.h"
|
||||
#include "ivfflat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "utils/relcache.h"
|
||||
#include "utils/varbit.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Allocate a vector array
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#include "postgres.h"
|
||||
|
||||
#include "access/genam.h"
|
||||
#include "access/generic_xlog.h"
|
||||
#include "access/itup.h"
|
||||
#include "commands/vacuum.h"
|
||||
#include "ivfflat.h"
|
||||
#include "storage/bufmgr.h"
|
||||
#include "utils/relcache.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 180000
|
||||
#define vacuum_delay_point() vacuum_delay_point(false)
|
||||
|
||||
@@ -5,18 +5,27 @@
|
||||
|
||||
#include "catalog/pg_type.h"
|
||||
#include "common/shortest_dec.h"
|
||||
#include "common/string.h"
|
||||
#include "fmgr.h"
|
||||
#include "halfutils.h"
|
||||
#include "halfvec.h"
|
||||
#include "lib/stringinfo.h"
|
||||
#include "libpq/pqformat.h"
|
||||
#include "sparsevec.h"
|
||||
#include "utils/array.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/fmgrprotos.h"
|
||||
#include "utils/lsyscache.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#include "parser/scansup.h"
|
||||
#endif
|
||||
|
||||
typedef struct SparseInputElement
|
||||
{
|
||||
int32 index;
|
||||
@@ -150,9 +159,9 @@ InitSparseVector(int dim, int nnz)
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* Check for whitespace, since array_isspace() is static
|
||||
*/
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#define sparsevec_isspace(ch) scanner_isspace(ch)
|
||||
#else
|
||||
static inline bool
|
||||
sparsevec_isspace(char ch)
|
||||
{
|
||||
@@ -165,6 +174,7 @@ sparsevec_isspace(char ch)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Compare indices
|
||||
|
||||
17
src/vector.c
17
src/vector.c
@@ -16,16 +16,20 @@
|
||||
#include "port.h" /* for strtof() */
|
||||
#include "sparsevec.h"
|
||||
#include "utils/array.h"
|
||||
#include "utils/builtins.h"
|
||||
#include "utils/float.h"
|
||||
#include "utils/fmgrprotos.h"
|
||||
#include "utils/lsyscache.h"
|
||||
#include "utils/numeric.h"
|
||||
#include "utils/varbit.h"
|
||||
#include "vector.h"
|
||||
|
||||
#if PG_VERSION_NUM >= 160000
|
||||
#include "varatt.h"
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#include "parser/scansup.h"
|
||||
#endif
|
||||
|
||||
#define STATE_DIMS(x) (ARR_DIMS(x)[0] - 1)
|
||||
#define CreateStateDatums(dim) palloc(sizeof(Datum) * (dim + 1))
|
||||
|
||||
@@ -36,7 +40,7 @@
|
||||
#endif
|
||||
|
||||
#if PG_VERSION_NUM >= 180000
|
||||
PG_MODULE_MAGIC_EXT(.name = "vector",.version = "0.8.1");
|
||||
PG_MODULE_MAGIC_EXT(.name = "vector",.version = "0.8.2");
|
||||
#else
|
||||
PG_MODULE_MAGIC;
|
||||
#endif
|
||||
@@ -129,9 +133,9 @@ InitVector(int dim)
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
* Check for whitespace, since array_isspace() is static
|
||||
*/
|
||||
#if PG_VERSION_NUM >= 170000
|
||||
#define vector_isspace(ch) scanner_isspace(ch)
|
||||
#else
|
||||
static inline bool
|
||||
vector_isspace(char ch)
|
||||
{
|
||||
@@ -144,6 +148,7 @@ vector_isspace(char ch)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Check state array
|
||||
|
||||
@@ -16,29 +16,19 @@ $node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
|
||||
);
|
||||
|
||||
# Check each index type
|
||||
my @operators = ("<->", "<#>", "<=>");
|
||||
my @opclasses = ("vector_l2_ops", "vector_ip_ops", "vector_cosine_ops");
|
||||
# Add index
|
||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v vector_l2_ops);");
|
||||
|
||||
for my $i (0 .. $#operators)
|
||||
# Test 100% recall
|
||||
for (1 .. 20)
|
||||
{
|
||||
my $operator = $operators[$i];
|
||||
my $opclass = $opclasses[$i];
|
||||
|
||||
# Add index
|
||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v $opclass);");
|
||||
|
||||
# Test 100% recall
|
||||
for (1 .. 20)
|
||||
{
|
||||
my $id = int(rand() * 100000);
|
||||
my $query = $node->safe_psql("postgres", "SELECT v FROM tst WHERE i = $id;");
|
||||
my $res = $node->safe_psql("postgres", qq(
|
||||
SET enable_seqscan = off;
|
||||
SELECT v FROM tst ORDER BY v <-> '$query' LIMIT 1;
|
||||
));
|
||||
is($res, $query);
|
||||
}
|
||||
my $id = int(rand() * 100000);
|
||||
my $query = $node->safe_psql("postgres", "SELECT v FROM tst WHERE i = $id;");
|
||||
my $res = $node->safe_psql("postgres", qq(
|
||||
SET enable_seqscan = off;
|
||||
SELECT v FROM tst ORDER BY v <-> '$query' LIMIT 1;
|
||||
));
|
||||
is($res, $query);
|
||||
}
|
||||
|
||||
done_testing();
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
use strict;
|
||||
use warnings FATAL => 'all';
|
||||
use PostgreSQL::Test::Cluster;
|
||||
use PostgreSQL::Test::Utils;
|
||||
use Test::More;
|
||||
|
||||
my $node;
|
||||
my @queries = ();
|
||||
my @cs = ();
|
||||
my @expected;
|
||||
my $limit = 20;
|
||||
my $dim = 3;
|
||||
my $array_sql = join(",", ('random()') x $dim);
|
||||
my $nc = 1000;
|
||||
|
||||
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 WHERE c = $cs[0] ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||
));
|
||||
like($explain, qr/Index Cond/);
|
||||
|
||||
for my $i (0 .. $#queries)
|
||||
{
|
||||
my $actual = $node->safe_psql("postgres", qq(
|
||||
SET enable_seqscan = off;
|
||||
SELECT i FROM tst WHERE c = $cs[$i] ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||
));
|
||||
my @actual_ids = split("\n", $actual);
|
||||
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||
|
||||
is(scalar(@actual_ids), $limit);
|
||||
|
||||
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 = PostgreSQL::Test::Cluster->new('node');
|
||||
$node->init;
|
||||
$node->start;
|
||||
|
||||
# Create table
|
||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim), c int4);");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT i, ARRAY[$array_sql], i % $nc FROM generate_series(1, 20000) i;"
|
||||
);
|
||||
|
||||
# Generate queries
|
||||
for (1 .. 20)
|
||||
{
|
||||
my @r = ();
|
||||
for (1 .. $dim)
|
||||
{
|
||||
push(@r, rand());
|
||||
}
|
||||
push(@queries, "[" . join(",", @r) . "]");
|
||||
push(@cs, int(rand() * $nc));
|
||||
}
|
||||
|
||||
# Get exact results
|
||||
@expected = ();
|
||||
for my $i (0 .. $#queries)
|
||||
{
|
||||
my $res = $node->safe_psql("postgres", "SELECT i FROM tst WHERE c = $cs[$i] ORDER BY v <=> '$queries[$i]' LIMIT $limit;");
|
||||
push(@expected, $res);
|
||||
}
|
||||
|
||||
# Add index
|
||||
$node->safe_psql("postgres", qq(
|
||||
SET maintenance_work_mem = '256MB';
|
||||
SET max_parallel_maintenance_workers = 2;
|
||||
CREATE INDEX ON tst USING hnsw (v vector_cosine_ops, c);
|
||||
));
|
||||
|
||||
# Test recall
|
||||
test_recall(0.99, '<=>');
|
||||
|
||||
# Test vacuum
|
||||
$node->safe_psql("postgres", "DELETE FROM tst WHERE c > 5;");
|
||||
$node->safe_psql("postgres", "VACUUM tst;");
|
||||
|
||||
# Test columns
|
||||
my ($ret, $stdout, $stderr) = $node->psql("postgres", "CREATE INDEX ON tst USING hnsw (c);");
|
||||
like($stderr, qr/first column must be a vector/);
|
||||
|
||||
($ret, $stdout, $stderr) = $node->psql("postgres", "CREATE INDEX ON tst USING hnsw (c, v vector_cosine_ops);");
|
||||
like($stderr, qr/first column must be a vector/);
|
||||
|
||||
($ret, $stdout, $stderr) = $node->psql("postgres", "CREATE INDEX ON tst USING hnsw (v vector_cosine_ops, c, c);");
|
||||
like($stderr, qr/index cannot have more than two columns/);
|
||||
|
||||
($ret, $stdout, $stderr) = $node->psql("postgres", "CREATE INDEX ON tst USING hnsw (v vector_cosine_ops, v vector_cosine_ops);");
|
||||
like($stderr, qr/column 2 cannot be a vector/);
|
||||
|
||||
done_testing();
|
||||
29
test/t/045_hnsw_low_memory_build.pl
Normal file
29
test/t/045_hnsw_low_memory_build.pl
Normal file
@@ -0,0 +1,29 @@
|
||||
use strict;
|
||||
use warnings FATAL => 'all';
|
||||
use PostgreSQL::Test::Cluster;
|
||||
use PostgreSQL::Test::Utils;
|
||||
use Test::More;
|
||||
|
||||
# Initialize node
|
||||
my $node = PostgreSQL::Test::Cluster->new('node');
|
||||
$node->init;
|
||||
$node->start;
|
||||
|
||||
# Create table
|
||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||
$node->safe_psql("postgres", "CREATE TABLE tst (v vector(3));");
|
||||
$node->safe_psql("postgres",
|
||||
"INSERT INTO tst SELECT ARRAY[random(), random(), random()] FROM generate_series(1, 1000) i;"
|
||||
);
|
||||
|
||||
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||
SET client_min_messages = DEBUG;
|
||||
SET maintenance_work_mem = '3073kB';
|
||||
ALTER TABLE tst SET (parallel_workers = 1);
|
||||
CREATE INDEX ON tst USING hnsw (v vector_l2_ops);
|
||||
));
|
||||
is($ret, 0, $stderr);
|
||||
like($stderr, qr/using \d+ parallel workers/);
|
||||
like($stderr, qr/hnsw graph no longer fits into maintenance_work_mem after 0 tuples/);
|
||||
|
||||
done_testing();
|
||||
@@ -1,4 +1,4 @@
|
||||
comment = 'vector data type and ivfflat and hnsw access methods'
|
||||
default_version = '0.8.1'
|
||||
default_version = '0.8.2'
|
||||
module_pathname = '$libdir/vector'
|
||||
relocatable = true
|
||||
|
||||
Reference in New Issue
Block a user