mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
3 Commits
index-limi
...
hnsw-paral
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8714dd1410 | ||
|
|
65e04acab6 | ||
|
|
86d72d15c2 |
8
.github/workflows/build.yml
vendored
8
.github/workflows/build.yml
vendored
@@ -8,8 +8,6 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- postgres: 17
|
|
||||||
os: ubuntu-22.04
|
|
||||||
- postgres: 16
|
- postgres: 16
|
||||||
os: ubuntu-22.04
|
os: ubuntu-22.04
|
||||||
- postgres: 15
|
- postgres: 15
|
||||||
@@ -23,7 +21,7 @@ jobs:
|
|||||||
- postgres: 11
|
- postgres: 11
|
||||||
os: ubuntu-20.04
|
os: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: ${{ matrix.postgres }}
|
postgres-version: ${{ matrix.postgres }}
|
||||||
@@ -45,7 +43,7 @@ jobs:
|
|||||||
runs-on: macos-latest
|
runs-on: macos-latest
|
||||||
if: ${{ !startsWith(github.ref_name, 'windows') }}
|
if: ${{ !startsWith(github.ref_name, 'windows') }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: 14
|
postgres-version: 14
|
||||||
@@ -67,7 +65,7 @@ jobs:
|
|||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
if: ${{ !startsWith(github.ref_name, 'mac') }}
|
if: ${{ !startsWith(github.ref_name, 'mac') }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v3
|
||||||
- uses: ankane/setup-postgres@v1
|
- uses: ankane/setup-postgres@v1
|
||||||
with:
|
with:
|
||||||
postgres-version: 14
|
postgres-version: 14
|
||||||
|
|||||||
14
CHANGELOG.md
14
CHANGELOG.md
@@ -1,17 +1,3 @@
|
|||||||
## 0.5.2 (unreleased)
|
|
||||||
|
|
||||||
- Improved performance of HNSW
|
|
||||||
- Added support for on-disk parallel index builds for HNSW
|
|
||||||
- Reduced memory usage for HNSW index builds
|
|
||||||
- Reduced WAL generation for HNSW index builds
|
|
||||||
- Fixed error with logical replication
|
|
||||||
- Fixed `invalid memory alloc request size` error with HNSW index build
|
|
||||||
|
|
||||||
## 0.5.1 (2023-10-10)
|
|
||||||
|
|
||||||
- Improved performance of HNSW index builds
|
|
||||||
- Added check for MVCC-compliant snapshot for index scans
|
|
||||||
|
|
||||||
## 0.5.0 (2023-08-28)
|
## 0.5.0 (2023-08-28)
|
||||||
|
|
||||||
- Added HNSW index type
|
- Added HNSW index type
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "vector",
|
"name": "vector",
|
||||||
"abstract": "Open-source vector similarity search for Postgres",
|
"abstract": "Open-source vector similarity search for Postgres",
|
||||||
"description": "Supports L2 distance, inner product, and cosine distance",
|
"description": "Supports L2 distance, inner product, and cosine distance",
|
||||||
"version": "0.5.1",
|
"version": "0.5.0",
|
||||||
"maintainer": [
|
"maintainer": [
|
||||||
"Andrew Kane <andrew@ankane.org>"
|
"Andrew Kane <andrew@ankane.org>"
|
||||||
],
|
],
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"vector": {
|
"vector": {
|
||||||
"file": "sql/vector.sql",
|
"file": "sql/vector.sql",
|
||||||
"docfile": "README.md",
|
"docfile": "README.md",
|
||||||
"version": "0.5.1",
|
"version": "0.5.0",
|
||||||
"abstract": "Open-source vector similarity search for Postgres"
|
"abstract": "Open-source vector similarity search for Postgres"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
4
Makefile
4
Makefile
@@ -1,5 +1,5 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.5.1
|
EXTVERSION = 0.5.0
|
||||||
|
|
||||||
MODULE_big = vector
|
MODULE_big = vector
|
||||||
DATA = $(wildcard sql/*--*.sql)
|
DATA = $(wildcard sql/*--*.sql)
|
||||||
@@ -8,7 +8,7 @@ HEADERS = src/vector.h
|
|||||||
|
|
||||||
TESTS = $(wildcard test/sql/*.sql)
|
TESTS = $(wildcard test/sql/*.sql)
|
||||||
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
REGRESS = $(patsubst test/sql/%.sql,%,$(TESTS))
|
||||||
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
REGRESS_OPTS = --inputdir=test --load-extension=vector
|
||||||
|
|
||||||
OPTFLAGS = -march=native
|
OPTFLAGS = -march=native
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
EXTENSION = vector
|
EXTENSION = vector
|
||||||
EXTVERSION = 0.5.1
|
EXTVERSION = 0.5.0
|
||||||
|
|
||||||
OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
|
OBJS = src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj
|
||||||
HEADERS = src\vector.h
|
HEADERS = src\vector.h
|
||||||
|
|
||||||
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
|
REGRESS = btree cast copy functions input ivfflat_cosine ivfflat_ip ivfflat_l2 ivfflat_options ivfflat_unlogged
|
||||||
REGRESS_OPTS = --inputdir=test --load-extension=$(EXTENSION)
|
REGRESS_OPTS = --inputdir=test --load-extension=vector
|
||||||
|
|
||||||
# For /arch flags
|
# For /arch flags
|
||||||
# https://learn.microsoft.com/en-us/cpp/build/reference/arch-minimum-cpu-architecture
|
# https://learn.microsoft.com/en-us/cpp/build/reference/arch-minimum-cpu-architecture
|
||||||
@@ -56,7 +56,7 @@ install:
|
|||||||
copy $(EXTENSION).control "$(SHAREDIR)\extension"
|
copy $(EXTENSION).control "$(SHAREDIR)\extension"
|
||||||
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
|
copy sql\$(EXTENSION)--*.sql "$(SHAREDIR)\extension"
|
||||||
mkdir "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
mkdir "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||||
for %f in ($(HEADERS)) do copy %f "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
copy $(HEADERS) "$(INCLUDEDIR_SERVER)\extension\$(EXTENSION)"
|
||||||
|
|
||||||
installcheck:
|
installcheck:
|
||||||
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
|
"$(BINDIR)\pg_regress" --bindir="$(BINDIR)" $(REGRESS_OPTS) $(REGRESS)
|
||||||
|
|||||||
302
README.md
302
README.md
@@ -10,7 +10,7 @@ Store your vectors with the rest of your data. Supports:
|
|||||||
|
|
||||||
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
Plus [ACID](https://en.wikipedia.org/wiki/ACID) compliance, point-in-time recovery, JOINs, and all of the other [great features](https://www.postgresql.org/about/) of Postgres
|
||||||
|
|
||||||
[](https://github.com/pgvector/pgvector/actions)
|
[](https://github.com/pgvector/pgvector/actions)
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ Compile and install the extension (supports Postgres 11+)
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
cd /tmp
|
cd /tmp
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
make
|
make
|
||||||
make install # may need sudo
|
make install # may need sudo
|
||||||
@@ -26,7 +26,7 @@ make install # may need sudo
|
|||||||
|
|
||||||
See the [installation notes](#installation-notes) if you run into issues
|
See the [installation notes](#installation-notes) if you run into issues
|
||||||
|
|
||||||
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres). There are also instructions for [GitHub Actions](https://github.com/pgvector/setup-pgvector).
|
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [APT](#apt), [Yum](#yum), or [conda-forge](#conda-forge), and it comes preinstalled with [Postgres.app](#postgresapp) and many [hosted providers](#hosted-postgres)
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
@@ -161,97 +161,8 @@ You can add an index to use approximate nearest neighbor search, which trades so
|
|||||||
|
|
||||||
Supported index types are:
|
Supported index types are:
|
||||||
|
|
||||||
- [HNSW](#hnsw) - added in 0.5.0
|
|
||||||
- [IVFFlat](#ivfflat)
|
- [IVFFlat](#ivfflat)
|
||||||
|
- [HNSW](#hnsw) - added in 0.5.0
|
||||||
## HNSW
|
|
||||||
|
|
||||||
An HNSW index creates a multilayer graph. It has better query performance than IVFFlat (in terms of speed-recall tradeoff), but has slower build times and uses more memory. Also, an index can be created without any data in the table since there isn’t a training step like IVFFlat.
|
|
||||||
|
|
||||||
Add an index for each distance function you want to use.
|
|
||||||
|
|
||||||
L2 distance
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
Inner product
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding vector_ip_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
Cosine distance
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
Vectors with up to 2,000 dimensions can be indexed.
|
|
||||||
|
|
||||||
### Index Options
|
|
||||||
|
|
||||||
Specify HNSW parameters
|
|
||||||
|
|
||||||
- `m` - the max number of connections per layer (16 by default)
|
|
||||||
- `ef_construction` - the size of the dynamic candidate list for constructing the graph (64 by default)
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);
|
|
||||||
```
|
|
||||||
|
|
||||||
A higher value of `ef_construction` provides better recall at the cost of index build time / insert speed.
|
|
||||||
|
|
||||||
### Query Options
|
|
||||||
|
|
||||||
Specify the size of the dynamic candidate list for search (40 by default)
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SET hnsw.ef_search = 100;
|
|
||||||
```
|
|
||||||
|
|
||||||
A higher value provides better recall at the cost of speed.
|
|
||||||
|
|
||||||
Use `SET LOCAL` inside a transaction to set it for a single query
|
|
||||||
|
|
||||||
```sql
|
|
||||||
BEGIN;
|
|
||||||
SET LOCAL hnsw.ef_search = 100;
|
|
||||||
SELECT ...
|
|
||||||
COMMIT;
|
|
||||||
```
|
|
||||||
|
|
||||||
### Index Build Time
|
|
||||||
|
|
||||||
Indexes build significantly faster when the graph fits into `maintenance_work_mem`
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SET maintenance_work_mem = '8GB';
|
|
||||||
```
|
|
||||||
|
|
||||||
A notice is shown when the graph no longer fits
|
|
||||||
|
|
||||||
```text
|
|
||||||
NOTICE: hnsw graph no longer fits into maintenance_work_mem after 100000 tuples
|
|
||||||
DETAIL: Building will take significantly more time.
|
|
||||||
HINT: Increase maintenance_work_mem to speed up builds.
|
|
||||||
```
|
|
||||||
|
|
||||||
Note: Do not set `maintenance_work_mem` so high that it exhausts the memory on the server
|
|
||||||
|
|
||||||
### Indexing Progress
|
|
||||||
|
|
||||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;
|
|
||||||
```
|
|
||||||
|
|
||||||
The phases for HNSW are:
|
|
||||||
|
|
||||||
1. `initializing`
|
|
||||||
2. `loading tuples`
|
|
||||||
|
|
||||||
## IVFFlat
|
## IVFFlat
|
||||||
|
|
||||||
@@ -304,32 +215,78 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Index Build Time
|
## HNSW
|
||||||
|
|
||||||
Speed up index creation on large tables by increasing the number of parallel workers (2 by default)
|
An HNSW index creates a multilayer graph. It has slower build times and uses more memory than IVFFlat, but has better query performance (in terms of speed-recall tradeoff). There’s no training step like IVFFlat, so the index can be created without any data in the table.
|
||||||
|
|
||||||
|
Add an index for each distance function you want to use.
|
||||||
|
|
||||||
|
L2 distance
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
SET max_parallel_maintenance_workers = 7; -- plus leader
|
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);
|
||||||
```
|
```
|
||||||
|
|
||||||
For a large number of workers, you may also need to increase `max_parallel_workers` (8 by default)
|
Inner product
|
||||||
|
|
||||||
### Indexing Progress
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw (embedding vector_ip_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
Cosine distance
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
Vectors with up to 2,000 dimensions can be indexed.
|
||||||
|
|
||||||
|
### Index Options
|
||||||
|
|
||||||
|
Specify HNSW parameters
|
||||||
|
|
||||||
|
- `m` - the max number of connections per layer (16 by default)
|
||||||
|
- `ef_construction` - the size of the dynamic candidate list for constructing the graph (64 by default)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Query Options
|
||||||
|
|
||||||
|
Specify the size of the dynamic candidate list for search (40 by default)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SET hnsw.ef_search = 100;
|
||||||
|
```
|
||||||
|
|
||||||
|
A higher value provides better recall at the cost of speed.
|
||||||
|
|
||||||
|
Use `SET LOCAL` inside a transaction to set it for a single query
|
||||||
|
|
||||||
|
```sql
|
||||||
|
BEGIN;
|
||||||
|
SET LOCAL hnsw.ef_search = 100;
|
||||||
|
SELECT ...
|
||||||
|
COMMIT;
|
||||||
|
```
|
||||||
|
|
||||||
|
## Indexing Progress
|
||||||
|
|
||||||
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
Check [indexing progress](https://www.postgresql.org/docs/current/progress-reporting.html#CREATE-INDEX-PROGRESS-REPORTING) with Postgres 12+
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
SELECT phase, round(100.0 * tuples_done / nullif(tuples_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;
|
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
|
||||||
```
|
```
|
||||||
|
|
||||||
The phases for IVFFlat are:
|
The phases are:
|
||||||
|
|
||||||
1. `initializing`
|
1. `initializing`
|
||||||
2. `performing k-means`
|
2. `performing k-means` - IVFFlat only
|
||||||
3. `assigning tuples`
|
3. `assigning tuples` - IVFFlat only
|
||||||
4. `loading tuples`
|
4. `loading tuples`
|
||||||
|
|
||||||
Note: `%` is only populated during the `loading tuples` phase
|
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
|
||||||
|
|
||||||
## Filtering
|
## Filtering
|
||||||
|
|
||||||
@@ -348,7 +305,8 @@ CREATE INDEX ON items (category_id);
|
|||||||
Or a [partial index](https://www.postgresql.org/docs/current/indexes-partial.html) on the vector column for approximate search
|
Or a [partial index](https://www.postgresql.org/docs/current/indexes-partial.html) on the vector column for approximate search
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WHERE (category_id = 123);
|
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)
|
||||||
|
WHERE (category_id = 123);
|
||||||
```
|
```
|
||||||
|
|
||||||
Use [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) for approximate search on many different values of the `WHERE` columns
|
Use [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) for approximate search on many different values of the `WHERE` columns
|
||||||
@@ -359,15 +317,13 @@ CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(cate
|
|||||||
|
|
||||||
## Hybrid Search
|
## Hybrid Search
|
||||||
|
|
||||||
Use together with Postgres [full-text search](https://www.postgresql.org/docs/current/textsearch-intro.html) for hybrid search.
|
Use together with Postgres [full-text search](https://www.postgresql.org/docs/current/textsearch-intro.html) for hybrid search ([Python example](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search.py)).
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
SELECT id, content FROM items, plainto_tsquery('hello search') query
|
SELECT id, content FROM items, plainto_tsquery('hello search') query
|
||||||
WHERE textsearch @@ query ORDER BY ts_rank_cd(textsearch, query) DESC LIMIT 5;
|
WHERE textsearch @@ query ORDER BY ts_rank_cd(textsearch, query) DESC LIMIT 5;
|
||||||
```
|
```
|
||||||
|
|
||||||
You can use [Reciprocal Rank Fusion](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search_rrf.py) or a [cross-encoder](https://github.com/pgvector/pgvector-python/blob/master/examples/hybrid_search.py) to combine results.
|
|
||||||
|
|
||||||
## Performance
|
## Performance
|
||||||
|
|
||||||
Use `EXPLAIN ANALYZE` to debug performance.
|
Use `EXPLAIN ANALYZE` to debug performance.
|
||||||
@@ -404,21 +360,17 @@ Use pgvector from any language with a Postgres client. You can even generate and
|
|||||||
|
|
||||||
Language | Libraries / Examples
|
Language | Libraries / Examples
|
||||||
--- | ---
|
--- | ---
|
||||||
C | [pgvector-c](https://github.com/pgvector/pgvector-c)
|
|
||||||
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
|
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
|
||||||
C#, F#, Visual Basic | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
|
C# | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
|
||||||
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
|
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
|
||||||
Dart | [pgvector-dart](https://github.com/pgvector/pgvector-dart)
|
Dart | [pgvector-dart](https://github.com/pgvector/pgvector-dart)
|
||||||
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
|
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
|
||||||
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
|
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
|
||||||
Haskell | [pgvector-haskell](https://github.com/pgvector/pgvector-haskell)
|
Haskell | [pgvector-haskell](https://github.com/pgvector/pgvector-haskell)
|
||||||
Java, Kotlin, Groovy, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
|
Java, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
|
||||||
JavaScript, TypeScript | [pgvector-node](https://github.com/pgvector/pgvector-node)
|
|
||||||
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
|
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
|
||||||
Lisp | [pgvector-lisp](https://github.com/pgvector/pgvector-lisp)
|
|
||||||
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
|
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
|
||||||
Nim | [pgvector-nim](https://github.com/pgvector/pgvector-nim)
|
Node.js | [pgvector-node](https://github.com/pgvector/pgvector-node)
|
||||||
OCaml | [pgvector-ocaml](https://github.com/pgvector/pgvector-ocaml)
|
|
||||||
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
|
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
|
||||||
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
|
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
|
||||||
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
|
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
|
||||||
@@ -426,7 +378,6 @@ R | [pgvector-r](https://github.com/pgvector/pgvector-r)
|
|||||||
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
|
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
|
||||||
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
|
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
|
||||||
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
|
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
|
||||||
Zig | [pgvector-zig](https://github.com/pgvector/pgvector-zig)
|
|
||||||
|
|
||||||
## Frequently Asked Questions
|
## Frequently Asked Questions
|
||||||
|
|
||||||
@@ -442,63 +393,6 @@ Yes, pgvector uses the write-ahead log (WAL), which allows for replication and p
|
|||||||
|
|
||||||
You’ll need to use [dimensionality reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction) at the moment.
|
You’ll need to use [dimensionality reduction](https://en.wikipedia.org/wiki/Dimensionality_reduction) at the moment.
|
||||||
|
|
||||||
#### Can I store vectors with different dimensions in the same column?
|
|
||||||
|
|
||||||
You can use `vector` as the type (instead of `vector(3)`).
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE TABLE embeddings (model_id bigint, item_id bigint, embedding vector, PRIMARY KEY (model_id, item_id));
|
|
||||||
```
|
|
||||||
|
|
||||||
However, you can only create indexes on rows with the same number of dimensions (using [expression](https://www.postgresql.org/docs/current/indexes-expressional.html) and [partial](https://www.postgresql.org/docs/current/indexes-partial.html) indexing):
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON embeddings USING hnsw ((embedding::vector(3)) vector_l2_ops) WHERE (model_id = 123);
|
|
||||||
```
|
|
||||||
|
|
||||||
and query with:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT * FROM embeddings WHERE model_id = 123 ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Can I store vectors with more precision?
|
|
||||||
|
|
||||||
You can use the `double precision[]` or `numeric[]` type to store vectors with more precision.
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE TABLE items (id bigserial PRIMARY KEY, embedding double precision[]);
|
|
||||||
|
|
||||||
-- use {} instead of [] for Postgres arrays
|
|
||||||
INSERT INTO items (embedding) VALUES ('{1,2,3}'), ('{4,5,6}');
|
|
||||||
```
|
|
||||||
|
|
||||||
Optionally, add a [check constraint](https://www.postgresql.org/docs/current/ddl-constraints.html) to ensure data can be converted to the `vector` type and has the expected dimensions.
|
|
||||||
|
|
||||||
```sql
|
|
||||||
ALTER TABLE items ADD CHECK (vector_dims(embedding::vector) = 3);
|
|
||||||
```
|
|
||||||
|
|
||||||
Use [expression indexing](https://www.postgresql.org/docs/current/indexes-expressional.html) to index (at a lower precision):
|
|
||||||
|
|
||||||
```sql
|
|
||||||
CREATE INDEX ON items USING hnsw ((embedding::vector(3)) vector_l2_ops);
|
|
||||||
```
|
|
||||||
|
|
||||||
and query with:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT * FROM items ORDER BY embedding::vector(3) <-> '[3,1,2]' LIMIT 5;
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Do indexes need to fit into memory?
|
|
||||||
|
|
||||||
No, but like other index types, you’ll likely see better performance if they do. You can get the size of an index with:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT pg_size_pretty(pg_relation_size('index_name'));
|
|
||||||
```
|
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
#### Why isn’t a query using an index?
|
#### Why isn’t a query using an index?
|
||||||
@@ -512,8 +406,6 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
Also, if the table is small, a table scan may be faster.
|
|
||||||
|
|
||||||
#### Why isn’t a query using a parallel table scan?
|
#### Why isn’t a query using a parallel table scan?
|
||||||
|
|
||||||
The planner doesn’t consider [out-of-line storage](https://www.postgresql.org/docs/current/storage-toast.html) in cost estimates, which can make a serial scan look cheaper. You can reduce the cost of a parallel scan for a query with:
|
The planner doesn’t consider [out-of-line storage](https://www.postgresql.org/docs/current/storage-toast.html) in cost estimates, which can make a serial scan look cheaper. You can reduce the cost of a parallel scan for a query with:
|
||||||
@@ -582,7 +474,7 @@ sum(vector) → vector | sum | 0.5.0
|
|||||||
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
|
If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
export PG_CONFIG=/Library/PostgreSQL/16/bin/pg_config
|
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
|
||||||
```
|
```
|
||||||
|
|
||||||
Then re-run the installation instructions (run `make clean` before `make` if needed). If `sudo` is needed for `make install`, use:
|
Then re-run the installation instructions (run `make clean` before `make` if needed). If `sudo` is needed for `make install`, use:
|
||||||
@@ -591,14 +483,6 @@ Then re-run the installation instructions (run `make clean` before `make` if nee
|
|||||||
sudo --preserve-env=PG_CONFIG make install
|
sudo --preserve-env=PG_CONFIG make install
|
||||||
```
|
```
|
||||||
|
|
||||||
A few common paths on Mac are:
|
|
||||||
|
|
||||||
- EDB installer - `/Library/PostgreSQL/16/bin/pg_config`
|
|
||||||
- Homebrew (arm64) - `/opt/homebrew/opt/postgresql@16/bin/pg_config`
|
|
||||||
- Homebrew (x86-64) - `/usr/local/opt/postgresql@16/bin/pg_config`
|
|
||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
|
||||||
|
|
||||||
### Missing Header
|
### Missing Header
|
||||||
|
|
||||||
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
|
If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
|
||||||
@@ -606,14 +490,10 @@ If compilation fails with `fatal error: postgres.h: No such file or directory`,
|
|||||||
For Ubuntu and Debian, use:
|
For Ubuntu and Debian, use:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt install postgresql-server-dev-16
|
sudo apt install postgresql-server-dev-15
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `15` with your Postgres server version
|
||||||
|
|
||||||
### Missing SDK
|
|
||||||
|
|
||||||
If compilation fails and the output includes `warning: no such sysroot directory` on Mac, reinstall Xcode Command Line Tools.
|
|
||||||
|
|
||||||
### Windows
|
### Windows
|
||||||
|
|
||||||
@@ -628,8 +508,8 @@ Note: The exact path will vary depending on your Visual Studio version and editi
|
|||||||
Then use `nmake` to build:
|
Then use `nmake` to build:
|
||||||
|
|
||||||
```cmd
|
```cmd
|
||||||
set "PGROOT=C:\Program Files\PostgreSQL\16"
|
set "PGROOT=C:\Program Files\PostgreSQL\15"
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
nmake /F Makefile.win
|
nmake /F Makefile.win
|
||||||
nmake /F Makefile.win install
|
nmake /F Makefile.win install
|
||||||
@@ -650,7 +530,7 @@ This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (r
|
|||||||
You can also build the image manually:
|
You can also build the image manually:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
|
git clone --branch v0.5.0 https://github.com/pgvector/pgvector.git
|
||||||
cd pgvector
|
cd pgvector
|
||||||
docker build --build-arg PG_MAJOR=15 -t myuser/pgvector .
|
docker build --build-arg PG_MAJOR=15 -t myuser/pgvector .
|
||||||
```
|
```
|
||||||
@@ -678,22 +558,22 @@ pgxn install vector
|
|||||||
Debian and Ubuntu packages are available from the [PostgreSQL APT Repository](https://wiki.postgresql.org/wiki/Apt). Follow the [setup instructions](https://wiki.postgresql.org/wiki/Apt#Quickstart) and run:
|
Debian and Ubuntu packages are available from the [PostgreSQL APT Repository](https://wiki.postgresql.org/wiki/Apt). Follow the [setup instructions](https://wiki.postgresql.org/wiki/Apt#Quickstart) and run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo apt install postgresql-16-pgvector
|
sudo apt install postgresql-15-pgvector
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `15` with your Postgres server version
|
||||||
|
|
||||||
### Yum
|
### Yum
|
||||||
|
|
||||||
RPM packages are available from the [PostgreSQL Yum Repository](https://yum.postgresql.org/). Follow the [setup instructions](https://www.postgresql.org/download/linux/redhat/) for your distribution and run:
|
RPM packages are available from the [PostgreSQL Yum Repository](https://yum.postgresql.org/). Follow the [setup instructions](https://www.postgresql.org/download/linux/redhat/) for your distribution and run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo yum install pgvector_16
|
sudo yum install pgvector_15
|
||||||
# or
|
# or
|
||||||
sudo dnf install pgvector_16
|
sudo dnf install pgvector_15
|
||||||
```
|
```
|
||||||
|
|
||||||
Note: Replace `16` with your Postgres server version
|
Note: Replace `15` with your Postgres server version
|
||||||
|
|
||||||
### conda-forge
|
### conda-forge
|
||||||
|
|
||||||
@@ -715,18 +595,12 @@ pgvector is available on [these providers](https://github.com/pgvector/pgvector/
|
|||||||
|
|
||||||
## Upgrading
|
## Upgrading
|
||||||
|
|
||||||
[Install](#installation) the latest version (use the same method as the original installation). Then in each database you want to upgrade, run:
|
Install the latest version and run:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
ALTER EXTENSION vector UPDATE;
|
ALTER EXTENSION vector UPDATE;
|
||||||
```
|
```
|
||||||
|
|
||||||
You can check the version in the current database with:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
SELECT extversion FROM pg_extension WHERE extname = 'vector';
|
|
||||||
```
|
|
||||||
|
|
||||||
## Upgrade Notes
|
## Upgrade Notes
|
||||||
|
|
||||||
### 0.4.0
|
### 0.4.0
|
||||||
@@ -803,25 +677,7 @@ make prove_installcheck PROVE_TESTS=test/t/001_wal.pl # TAP test
|
|||||||
To enable benchmarking:
|
To enable benchmarking:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make clean && PG_CFLAGS="-DIVFFLAT_BENCH" make && make install
|
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
|
||||||
```
|
|
||||||
|
|
||||||
To show memory usage:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DHNSW_MEMORY -DIVFFLAT_MEMORY" make && make install
|
|
||||||
```
|
|
||||||
|
|
||||||
To enable assertions:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DUSE_ASSERT_CHECKING" make && make install
|
|
||||||
```
|
|
||||||
|
|
||||||
To get k-means metrics:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make clean && PG_CFLAGS="-DIVFFLAT_KMEANS_DEBUG" make && make install
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Resources for contributors
|
Resources for contributors
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
|
||||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.5.1'" to load this file. \quit
|
|
||||||
24
src/hnsw.c
24
src/hnsw.c
@@ -14,7 +14,6 @@
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
int hnsw_ef_search;
|
int hnsw_ef_search;
|
||||||
bool hnsw_enable_parallel_build;
|
|
||||||
static relopt_kind hnsw_relopt_kind;
|
static relopt_kind hnsw_relopt_kind;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -40,11 +39,6 @@ HnswInit(void)
|
|||||||
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
|
DefineCustomIntVariable("hnsw.ef_search", "Sets the size of the dynamic candidate list for search",
|
||||||
"Valid range is 1..1000.", &hnsw_ef_search,
|
"Valid range is 1..1000.", &hnsw_ef_search,
|
||||||
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
|
HNSW_DEFAULT_EF_SEARCH, HNSW_MIN_EF_SEARCH, HNSW_MAX_EF_SEARCH, PGC_USERSET, 0, NULL, NULL, NULL);
|
||||||
|
|
||||||
/* Behind a variable for now since can be slower than building in memory */
|
|
||||||
DefineCustomBoolVariable("hnsw.enable_parallel_build", "Enables or disables building indexes in parallel",
|
|
||||||
NULL, &hnsw_enable_parallel_build,
|
|
||||||
false, PGC_USERSET, 0, NULL, NULL, NULL);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -94,24 +88,10 @@ hnswcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Do not use index if no limit or limit + offset > ef_search unless
|
|
||||||
* enable_seqscan = off
|
|
||||||
*/
|
|
||||||
if (root->limit_tuples < 0 || root->limit_tuples > hnsw_ef_search)
|
|
||||||
{
|
|
||||||
*indexStartupCost = 1.0e10 - 1;
|
|
||||||
*indexTotalCost = 1.0e10 - 1;
|
|
||||||
*indexSelectivity = 0;
|
|
||||||
*indexCorrelation = 0;
|
|
||||||
*indexPages = 0;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
MemSet(&costs, 0, sizeof(costs));
|
MemSet(&costs, 0, sizeof(costs));
|
||||||
|
|
||||||
index = index_open(path->indexinfo->indexoid, NoLock);
|
index = index_open(path->indexinfo->indexoid, NoLock);
|
||||||
HnswGetMetaPageInfo(index, &m, NULL);
|
m = HnswGetM(index);
|
||||||
index_close(index, NoLock);
|
index_close(index, NoLock);
|
||||||
|
|
||||||
/* Approximate entry level */
|
/* Approximate entry level */
|
||||||
@@ -216,7 +196,7 @@ hnswhandler(PG_FUNCTION_ARGS)
|
|||||||
amroutine->aminsert = hnswinsert;
|
amroutine->aminsert = hnswinsert;
|
||||||
amroutine->ambulkdelete = hnswbulkdelete;
|
amroutine->ambulkdelete = hnswbulkdelete;
|
||||||
amroutine->amvacuumcleanup = hnswvacuumcleanup;
|
amroutine->amvacuumcleanup = hnswvacuumcleanup;
|
||||||
amroutine->amcanreturn = NULL;
|
amroutine->amcanreturn = NULL; /* tuple not included in heapsort */
|
||||||
amroutine->amcostestimate = hnswcostestimate;
|
amroutine->amcostestimate = hnswcostestimate;
|
||||||
amroutine->amoptions = hnswoptions;
|
amroutine->amoptions = hnswoptions;
|
||||||
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
amroutine->amproperty = NULL; /* TODO AMPROP_DISTANCE_ORDERABLE */
|
||||||
|
|||||||
94
src/hnsw.h
94
src/hnsw.h
@@ -6,7 +6,6 @@
|
|||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
#include "access/parallel.h"
|
#include "access/parallel.h"
|
||||||
#include "access/reloptions.h"
|
#include "access/reloptions.h"
|
||||||
#include "lib/ilist.h"
|
|
||||||
#include "nodes/execnodes.h"
|
#include "nodes/execnodes.h"
|
||||||
#include "port.h" /* for random() */
|
#include "port.h" /* for random() */
|
||||||
#include "utils/sampling.h"
|
#include "utils/sampling.h"
|
||||||
@@ -63,9 +62,7 @@
|
|||||||
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
/* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
|
||||||
#define PROGRESS_HNSW_PHASE_LOAD 2
|
#define PROGRESS_HNSW_PHASE_LOAD 2
|
||||||
|
|
||||||
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
#define HNSW_ELEMENT_TUPLE_SIZE(_dim) MAXALIGN(offsetof(HnswElementTupleData, vec) + VECTOR_SIZE(_dim))
|
||||||
|
|
||||||
#define HNSW_ELEMENT_TUPLE_SIZE(size) MAXALIGN(offsetof(HnswElementTupleData, data) + (size))
|
|
||||||
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
#define HNSW_NEIGHBOR_TUPLE_SIZE(level, m) MAXALIGN(offsetof(HnswNeighborTupleData, indextids) + ((level) + 2) * (m) * sizeof(ItemPointerData))
|
||||||
|
|
||||||
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
#define HnswPageGetOpaque(page) ((HnswPageOpaque) PageGetSpecialPointer(page))
|
||||||
@@ -73,10 +70,8 @@
|
|||||||
|
|
||||||
#if PG_VERSION_NUM >= 150000
|
#if PG_VERSION_NUM >= 150000
|
||||||
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
|
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
|
||||||
#define SeedRandom(seed) pg_prng_seed(&pg_global_prng_state, seed)
|
|
||||||
#else
|
#else
|
||||||
#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
|
#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
|
||||||
#define SeedRandom(seed) srandom(seed)
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
#if PG_VERSION_NUM < 130000
|
||||||
@@ -94,28 +89,24 @@
|
|||||||
#define HnswGetMl(m) (1 / log(m))
|
#define HnswGetMl(m) (1 / log(m))
|
||||||
|
|
||||||
/* Ensure fits on page and in uint8 */
|
/* Ensure fits on page and in uint8 */
|
||||||
#define HnswGetMaxLevel(m) Min(((BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - offsetof(HnswNeighborTupleData, indextids) - sizeof(ItemIdData)) / (sizeof(ItemPointerData)) / (m)) - 2, 255)
|
#define HnswGetMaxLevel(m) Min(((BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - offsetof(HnswNeighborTupleData, indextids) - sizeof(ItemIdData)) / (sizeof(ItemPointerData)) / m) - 2, 255)
|
||||||
|
|
||||||
#define HnswGetNeighbors(element, lc) (AssertMacro((element)->level >= (lc)), &(element)->neighbors[lc])
|
|
||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
extern int hnsw_ef_search;
|
extern int hnsw_ef_search;
|
||||||
extern bool hnsw_enable_parallel_build;
|
|
||||||
|
typedef struct HnswNeighborArray HnswNeighborArray;
|
||||||
|
|
||||||
typedef struct HnswElementData
|
typedef struct HnswElementData
|
||||||
{
|
{
|
||||||
slist_node next;
|
List *heaptids;
|
||||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
|
||||||
uint8 heaptidsLength;
|
|
||||||
uint8 level;
|
uint8 level;
|
||||||
uint8 deleted;
|
uint8 deleted;
|
||||||
uint32 hash;
|
HnswNeighborArray *neighbors;
|
||||||
struct HnswNeighborArray *neighbors;
|
|
||||||
BlockNumber blkno;
|
BlockNumber blkno;
|
||||||
OffsetNumber offno;
|
OffsetNumber offno;
|
||||||
OffsetNumber neighborOffno;
|
OffsetNumber neighborOffno;
|
||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
Datum value;
|
Vector *vec;
|
||||||
} HnswElementData;
|
} HnswElementData;
|
||||||
|
|
||||||
typedef HnswElementData * HnswElement;
|
typedef HnswElementData * HnswElement;
|
||||||
@@ -124,13 +115,11 @@ typedef struct HnswCandidate
|
|||||||
{
|
{
|
||||||
HnswElement element;
|
HnswElement element;
|
||||||
float distance;
|
float distance;
|
||||||
bool closer;
|
|
||||||
} HnswCandidate;
|
} HnswCandidate;
|
||||||
|
|
||||||
typedef struct HnswNeighborArray
|
typedef struct HnswNeighborArray
|
||||||
{
|
{
|
||||||
int length;
|
int length;
|
||||||
bool closerSet;
|
|
||||||
HnswCandidate *items;
|
HnswCandidate *items;
|
||||||
} HnswNeighborArray;
|
} HnswNeighborArray;
|
||||||
|
|
||||||
@@ -148,16 +137,6 @@ typedef struct HnswOptions
|
|||||||
int efConstruction; /* size of dynamic candidate list */
|
int efConstruction; /* size of dynamic candidate list */
|
||||||
} HnswOptions;
|
} HnswOptions;
|
||||||
|
|
||||||
typedef struct HnswGraph
|
|
||||||
{
|
|
||||||
slist_head elements;
|
|
||||||
HnswElement entryPoint;
|
|
||||||
long memoryUsed;
|
|
||||||
long memoryTotal;
|
|
||||||
bool flushed;
|
|
||||||
double indtuples;
|
|
||||||
} HnswGraph;
|
|
||||||
|
|
||||||
typedef struct HnswSpool
|
typedef struct HnswSpool
|
||||||
{
|
{
|
||||||
Relation heap;
|
Relation heap;
|
||||||
@@ -181,7 +160,7 @@ typedef struct HnswShared
|
|||||||
/* Mutable state */
|
/* Mutable state */
|
||||||
int nparticipantsdone;
|
int nparticipantsdone;
|
||||||
double reltuples;
|
double reltuples;
|
||||||
HnswGraph graphData;
|
double indtuples;
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 120000
|
#if PG_VERSION_NUM < 120000
|
||||||
ParallelHeapScanDescData heapdesc; /* must come last */
|
ParallelHeapScanDescData heapdesc; /* must come last */
|
||||||
@@ -224,19 +203,19 @@ typedef struct HnswBuildState
|
|||||||
Oid collation;
|
Oid collation;
|
||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
HnswGraph graphData;
|
List *elements;
|
||||||
HnswGraph *graph;
|
HnswElement entryPoint;
|
||||||
double ml;
|
double ml;
|
||||||
int maxLevel;
|
int maxLevel;
|
||||||
|
double maxInMemoryElements;
|
||||||
|
bool flushed;
|
||||||
Vector *normvec;
|
Vector *normvec;
|
||||||
|
|
||||||
/* Memory */
|
/* Memory */
|
||||||
MemoryContext graphCtx;
|
|
||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
|
|
||||||
/* Parallel builds */
|
/* Parallel builds */
|
||||||
HnswLeader *hnswleader;
|
HnswLeader *hnswleader;
|
||||||
HnswShared *hnswshared;
|
|
||||||
} HnswBuildState;
|
} HnswBuildState;
|
||||||
|
|
||||||
typedef struct HnswMetaPageData
|
typedef struct HnswMetaPageData
|
||||||
@@ -272,7 +251,7 @@ typedef struct HnswElementTupleData
|
|||||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
||||||
ItemPointerData neighbortid;
|
ItemPointerData neighbortid;
|
||||||
uint16 unused2;
|
uint16 unused2;
|
||||||
Vector data;
|
Vector vec;
|
||||||
} HnswElementTupleData;
|
} HnswElementTupleData;
|
||||||
|
|
||||||
typedef HnswElementTupleData * HnswElementTuple;
|
typedef HnswElementTupleData * HnswElementTuple;
|
||||||
@@ -290,6 +269,7 @@ typedef HnswNeighborTupleData * HnswNeighborTuple;
|
|||||||
typedef struct HnswScanOpaqueData
|
typedef struct HnswScanOpaqueData
|
||||||
{
|
{
|
||||||
bool first;
|
bool first;
|
||||||
|
Buffer buf;
|
||||||
List *w;
|
List *w;
|
||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
|
|
||||||
@@ -318,7 +298,7 @@ typedef struct HnswVacuumState
|
|||||||
Oid collation;
|
Oid collation;
|
||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
struct tidhash_hash *deleted;
|
HTAB *deleted;
|
||||||
BufferAccessStrategy bas;
|
BufferAccessStrategy bas;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
HnswElementData highestPoint;
|
HnswElementData highestPoint;
|
||||||
@@ -330,29 +310,32 @@ typedef struct HnswVacuumState
|
|||||||
/* Methods */
|
/* Methods */
|
||||||
int HnswGetM(Relation index);
|
int HnswGetM(Relation index);
|
||||||
int HnswGetEfConstruction(Relation index);
|
int HnswGetEfConstruction(Relation index);
|
||||||
FmgrInfo *HnswOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *HnswOptionalProcInfo(Relation rel, uint16 procnum);
|
||||||
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
bool HnswNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||||
|
void HnswCommitBuffer(Buffer buf, GenericXLogState *state);
|
||||||
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
Buffer HnswNewBuffer(Relation index, ForkNumber forkNum);
|
||||||
void HnswInitPage(Buffer buf, Page page);
|
void HnswInitPage(Buffer buf, Page page);
|
||||||
|
void HnswInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state);
|
||||||
void HnswInit(void);
|
void HnswInit(void);
|
||||||
List *HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement);
|
List *HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, bool inserting, HnswElement skipElement);
|
||||||
HnswElement HnswGetEntryPoint(Relation index);
|
HnswElement HnswGetEntryPoint(Relation index);
|
||||||
void HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint);
|
|
||||||
HnswElement HnswInitElement(ItemPointer tid, int m, double ml, int maxLevel);
|
HnswElement HnswInitElement(ItemPointer tid, int m, double ml, int maxLevel);
|
||||||
|
void HnswFreeElement(HnswElement element);
|
||||||
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
HnswElement HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno);
|
||||||
void HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing);
|
void HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, FmgrInfo *procinfo, Oid collation, int m, int efConstruction, bool existing);
|
||||||
|
HnswElement HnswFindDuplicate(HnswElement e);
|
||||||
HnswCandidate *HnswEntryCandidate(HnswElement em, Datum q, Relation rel, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
HnswCandidate *HnswEntryCandidate(HnswElement em, Datum q, Relation rel, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
||||||
void HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum, bool building);
|
void HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum);
|
||||||
void HnswSetNeighborTuple(HnswNeighborTuple ntup, HnswElement e, int m);
|
void HnswSetNeighborTuple(HnswNeighborTuple ntup, HnswElement e, int m);
|
||||||
void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
|
void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
|
||||||
void HnswInitNeighbors(HnswElement element, int m);
|
void HnswInitNeighbors(HnswElement element, int m);
|
||||||
bool HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel, bool building);
|
bool HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel);
|
||||||
void HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building);
|
void HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting);
|
||||||
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
|
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
|
||||||
void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index, FmgrInfo *procinfo, Oid collation, bool loadVec);
|
||||||
void HnswSetElementTuple(HnswElementTuple etup, HnswElement element);
|
void HnswSetElementTuple(HnswElementTuple etup, HnswElement element);
|
||||||
void HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
void HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation);
|
||||||
void HnswLoadNeighbors(HnswElement element, Relation index, int m);
|
void HnswLoadNeighbors(HnswElement element, Relation index);
|
||||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
||||||
|
|
||||||
/* Index access methods */
|
/* Index access methods */
|
||||||
@@ -371,31 +354,4 @@ void hnswrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys,
|
|||||||
bool hnswgettuple(IndexScanDesc scan, ScanDirection dir);
|
bool hnswgettuple(IndexScanDesc scan, ScanDirection dir);
|
||||||
void hnswendscan(IndexScanDesc scan);
|
void hnswendscan(IndexScanDesc scan);
|
||||||
|
|
||||||
/* Hash tables */
|
|
||||||
typedef struct TidHashEntry
|
|
||||||
{
|
|
||||||
ItemPointerData tid;
|
|
||||||
char status;
|
|
||||||
} TidHashEntry;
|
|
||||||
|
|
||||||
#define SH_PREFIX tidhash
|
|
||||||
#define SH_ELEMENT_TYPE TidHashEntry
|
|
||||||
#define SH_KEY_TYPE ItemPointerData
|
|
||||||
#define SH_SCOPE extern
|
|
||||||
#define SH_DECLARE
|
|
||||||
#include "lib/simplehash.h"
|
|
||||||
|
|
||||||
typedef struct PointerHashEntry
|
|
||||||
{
|
|
||||||
uintptr_t ptr;
|
|
||||||
char status;
|
|
||||||
} PointerHashEntry;
|
|
||||||
|
|
||||||
#define SH_PREFIX pointerhash
|
|
||||||
#define SH_ELEMENT_TYPE PointerHashEntry
|
|
||||||
#define SH_KEY_TYPE uintptr_t
|
|
||||||
#define SH_SCOPE extern
|
|
||||||
#define SH_DECLARE
|
|
||||||
#include "lib/simplehash.h"
|
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
400
src/hnswbuild.c
400
src/hnswbuild.c
@@ -11,7 +11,6 @@
|
|||||||
#include "nodes/pg_list.h"
|
#include "nodes/pg_list.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
#include "tcop/tcopprot.h"
|
||||||
#include "utils/datum.h"
|
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
@@ -56,10 +55,6 @@
|
|||||||
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
||||||
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000002)
|
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000002)
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
|
||||||
#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create the metapage
|
* Create the metapage
|
||||||
*/
|
*/
|
||||||
@@ -70,11 +65,11 @@ CreateMetaPage(HnswBuildState * buildstate)
|
|||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
|
GenericXLogState *state;
|
||||||
HnswMetaPage metap;
|
HnswMetaPage metap;
|
||||||
|
|
||||||
buf = HnswNewBuffer(index, forkNum);
|
buf = HnswNewBuffer(index, forkNum);
|
||||||
page = BufferGetPage(buf);
|
HnswInitRegisterPage(index, &buf, &page, &state);
|
||||||
HnswInitPage(buf, page);
|
|
||||||
|
|
||||||
/* Set metapage data */
|
/* Set metapage data */
|
||||||
metap = HnswPageGetMeta(page);
|
metap = HnswPageGetMeta(page);
|
||||||
@@ -90,15 +85,14 @@ CreateMetaPage(HnswBuildState * buildstate)
|
|||||||
((PageHeader) page)->pd_lower =
|
((PageHeader) page)->pd_lower =
|
||||||
((char *) metap + sizeof(HnswMetaPageData)) - (char *) page;
|
((char *) metap + sizeof(HnswMetaPageData)) - (char *) page;
|
||||||
|
|
||||||
MarkBufferDirty(buf);
|
HnswCommitBuffer(buf, state);
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add a new page
|
* Add a new page
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, ForkNumber forkNum)
|
HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum)
|
||||||
{
|
{
|
||||||
/* Add a new page */
|
/* Add a new page */
|
||||||
Buffer newbuf = HnswNewBuffer(index, forkNum);
|
Buffer newbuf = HnswNewBuffer(index, forkNum);
|
||||||
@@ -108,6 +102,7 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, ForkNumber forkNum)
|
|||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
MarkBufferDirty(*buf);
|
MarkBufferDirty(*buf);
|
||||||
|
GenericXLogFinish(*state);
|
||||||
UnlockReleaseBuffer(*buf);
|
UnlockReleaseBuffer(*buf);
|
||||||
|
|
||||||
/* Can take a while, so ensure we can interrupt */
|
/* Can take a while, so ensure we can interrupt */
|
||||||
@@ -118,7 +113,8 @@ HnswBuildAppendPage(Relation index, Buffer *buf, Page *page, ForkNumber forkNum)
|
|||||||
|
|
||||||
/* Prepare new page */
|
/* Prepare new page */
|
||||||
*buf = newbuf;
|
*buf = newbuf;
|
||||||
*page = BufferGetPage(*buf);
|
*state = GenericXLogStart(index);
|
||||||
|
*page = GenericXLogRegisterBuffer(*state, *buf, GENERIC_XLOG_FULL_IMAGE);
|
||||||
HnswInitPage(*buf, *page);
|
HnswInitPage(*buf, *page);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,52 +126,46 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
Size etupAllocSize;
|
int dimensions = buildstate->dimensions;
|
||||||
|
Size etupSize;
|
||||||
Size maxSize;
|
Size maxSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
BlockNumber insertPage;
|
BlockNumber insertPage;
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
slist_iter iter;
|
GenericXLogState *state;
|
||||||
|
ListCell *lc;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupAllocSize = BLCKSZ;
|
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||||
maxSize = HNSW_MAX_SIZE;
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
etup = palloc0(etupAllocSize);
|
etup = palloc0(etupSize);
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(maxSize);
|
||||||
|
|
||||||
/* Prepare first page */
|
/* Prepare first page */
|
||||||
buf = HnswNewBuffer(index, forkNum);
|
buf = HnswNewBuffer(index, forkNum);
|
||||||
page = BufferGetPage(buf);
|
state = GenericXLogStart(index);
|
||||||
|
page = GenericXLogRegisterBuffer(state, buf, GENERIC_XLOG_FULL_IMAGE);
|
||||||
HnswInitPage(buf, page);
|
HnswInitPage(buf, page);
|
||||||
|
|
||||||
slist_foreach(iter, &buildstate->graph->elements)
|
foreach(lc, buildstate->elements)
|
||||||
{
|
{
|
||||||
HnswElement element = slist_container(HnswElementData, next, iter.cur);
|
HnswElement element = lfirst(lc);
|
||||||
Size etupSize;
|
|
||||||
Size ntupSize;
|
Size ntupSize;
|
||||||
Size combinedSize;
|
Size combinedSize;
|
||||||
|
|
||||||
/* Zero memory for each element */
|
HnswSetElementTuple(etup, element);
|
||||||
MemSet(etup, 0, etupAllocSize);
|
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(DatumGetPointer(element->value)));
|
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* Initial size check */
|
|
||||||
if (etupSize > etupAllocSize)
|
|
||||||
elog(ERROR, "index tuple too large");
|
|
||||||
|
|
||||||
HnswSetElementTuple(etup, element);
|
|
||||||
|
|
||||||
/* Keep element and neighbors on the same page if possible */
|
/* Keep element and neighbors on the same page if possible */
|
||||||
if (PageGetFreeSpace(page) < etupSize || (combinedSize <= maxSize && PageGetFreeSpace(page) < combinedSize))
|
if (PageGetFreeSpace(page) < etupSize || (combinedSize <= maxSize && PageGetFreeSpace(page) < combinedSize))
|
||||||
HnswBuildAppendPage(index, &buf, &page, forkNum);
|
HnswBuildAppendPage(index, &buf, &page, &state, forkNum);
|
||||||
|
|
||||||
/* Calculate offsets */
|
/* Calculate offsets */
|
||||||
element->blkno = BufferGetBlockNumber(buf);
|
element->blkno = BufferGetBlockNumber(buf);
|
||||||
@@ -199,7 +189,7 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
|
|
||||||
/* Add new page if needed */
|
/* Add new page if needed */
|
||||||
if (PageGetFreeSpace(page) < ntupSize)
|
if (PageGetFreeSpace(page) < ntupSize)
|
||||||
HnswBuildAppendPage(index, &buf, &page, forkNum);
|
HnswBuildAppendPage(index, &buf, &page, &state, forkNum);
|
||||||
|
|
||||||
/* Add placeholder for neighbors */
|
/* Add placeholder for neighbors */
|
||||||
if (PageAddItem(page, (Item) ntup, ntupSize, InvalidOffsetNumber, false, false) != element->neighborOffno)
|
if (PageAddItem(page, (Item) ntup, ntupSize, InvalidOffsetNumber, false, false) != element->neighborOffno)
|
||||||
@@ -210,9 +200,10 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(buf);
|
||||||
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_ALWAYS, buildstate->graph->entryPoint, insertPage, forkNum, true);
|
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_ALWAYS, buildstate->entryPoint, insertPage, forkNum);
|
||||||
|
|
||||||
pfree(etup);
|
pfree(etup);
|
||||||
pfree(ntup);
|
pfree(ntup);
|
||||||
@@ -227,17 +218,18 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
|||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
int m = buildstate->m;
|
int m = buildstate->m;
|
||||||
slist_iter iter;
|
ListCell *lc;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(BLCKSZ);
|
||||||
|
|
||||||
slist_foreach(iter, &buildstate->graph->elements)
|
foreach(lc, buildstate->elements)
|
||||||
{
|
{
|
||||||
HnswElement e = slist_container(HnswElementData, next, iter.cur);
|
HnswElement e = lfirst(lc);
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
|
GenericXLogState *state;
|
||||||
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
Size ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||||
|
|
||||||
/* Can take a while, so ensure we can interrupt */
|
/* Can take a while, so ensure we can interrupt */
|
||||||
@@ -246,7 +238,8 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
|||||||
|
|
||||||
buf = ReadBufferExtended(index, forkNum, e->neighborPage, RBM_NORMAL, NULL);
|
buf = ReadBufferExtended(index, forkNum, e->neighborPage, RBM_NORMAL, NULL);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
page = BufferGetPage(buf);
|
state = GenericXLogStart(index);
|
||||||
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
|
|
||||||
HnswSetNeighborTuple(ntup, e, m);
|
HnswSetNeighborTuple(ntup, e, m);
|
||||||
|
|
||||||
@@ -255,29 +248,26 @@ CreateNeighborPages(HnswBuildState * buildstate)
|
|||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(buf);
|
||||||
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
pfree(ntup);
|
pfree(ntup);
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef HNSW_MEMORY
|
|
||||||
/*
|
/*
|
||||||
* Show memory usage
|
* Free elements
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
ShowMemoryUsage(HnswBuildState * buildstate)
|
FreeElements(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
#if PG_VERSION_NUM >= 130000
|
ListCell *lc;
|
||||||
elog(INFO, "graph memory: %zu MB, total memory: %zu MB",
|
|
||||||
MemoryContextMemAllocated(buildstate->graphCtx, false) / (1024 * 1024),
|
foreach(lc, buildstate->elements)
|
||||||
MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024));
|
HnswFreeElement(lfirst(lc));
|
||||||
#else
|
|
||||||
MemoryContextStats(CurrentMemoryContext);
|
list_free(buildstate->elements);
|
||||||
elog(INFO, "estimated memory: %zu MB", buildstate->memoryUsed / (1024 * 1024));
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Flush pages
|
* Flush pages
|
||||||
@@ -285,78 +275,25 @@ ShowMemoryUsage(HnswBuildState * buildstate)
|
|||||||
static void
|
static void
|
||||||
FlushPages(HnswBuildState * buildstate)
|
FlushPages(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
#ifdef HNSW_MEMORY
|
|
||||||
ShowMemoryUsage(buildstate);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
CreateMetaPage(buildstate);
|
CreateMetaPage(buildstate);
|
||||||
CreateElementPages(buildstate);
|
CreateElementPages(buildstate);
|
||||||
CreateNeighborPages(buildstate);
|
CreateNeighborPages(buildstate);
|
||||||
|
|
||||||
buildstate->graph->flushed = true;
|
buildstate->flushed = true;
|
||||||
MemoryContextReset(buildstate->graphCtx);
|
FreeElements(buildstate);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
|
||||||
/*
|
/*
|
||||||
* Get the memory used by an element
|
* Insert tuple
|
||||||
*/
|
|
||||||
static long
|
|
||||||
HnswElementMemory(HnswElement e, int m)
|
|
||||||
{
|
|
||||||
long elementSize = sizeof(HnswElementData);
|
|
||||||
|
|
||||||
elementSize += sizeof(HnswNeighborArray) * (e->level + 1);
|
|
||||||
elementSize += sizeof(HnswCandidate) * (m * (e->level + 2));
|
|
||||||
elementSize += VARSIZE_ANY(DatumGetPointer(e->value));
|
|
||||||
/* Each allocation has a chunk header */
|
|
||||||
elementSize += (e->level + 4) * GENERATIONCHUNK_RAWSIZE;
|
|
||||||
/* Add an extra 5% for alignment and other overhead */
|
|
||||||
return elementSize * 1.05;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Find duplicate element
|
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswFindDuplicateInMemory(HnswElement element)
|
InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState * buildstate, HnswElement * dup)
|
||||||
{
|
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(element, 0);
|
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
|
||||||
{
|
|
||||||
HnswCandidate *neighbor = &neighbors->items[i];
|
|
||||||
|
|
||||||
/* Exit early since ordered by distance */
|
|
||||||
if (!datumIsEqual(element->value, neighbor->element->value, false, -1))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
/* Check for space */
|
|
||||||
if (neighbor->element->heaptidsLength < HNSW_HEAPTIDS)
|
|
||||||
{
|
|
||||||
HnswAddHeapTid(neighbor->element, &element->heaptids[0]);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Insert tuple into in-memory graph
|
|
||||||
*/
|
|
||||||
static bool
|
|
||||||
InsertTupleInMemory(Relation index, Datum *values, ItemPointer heaptid, HnswBuildState * buildstate)
|
|
||||||
{
|
{
|
||||||
FmgrInfo *procinfo = buildstate->procinfo;
|
FmgrInfo *procinfo = buildstate->procinfo;
|
||||||
Oid collation = buildstate->collation;
|
Oid collation = buildstate->collation;
|
||||||
HnswGraph *graph = buildstate->graph;
|
HnswElement entryPoint = buildstate->entryPoint;
|
||||||
HnswElement entryPoint = graph->entryPoint;
|
|
||||||
int efConstruction = buildstate->efConstruction;
|
int efConstruction = buildstate->efConstruction;
|
||||||
int m = buildstate->m;
|
int m = buildstate->m;
|
||||||
MemoryContext oldCtx;
|
|
||||||
HnswElement element;
|
|
||||||
|
|
||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
@@ -368,67 +305,35 @@ InsertTupleInMemory(Relation index, Datum *values, ItemPointer heaptid, HnswBuil
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Allocate element in graph memory context */
|
/* Copy value to element so accessible outside of memory context */
|
||||||
oldCtx = MemoryContextSwitchTo(buildstate->graphCtx);
|
memcpy(element->vec, DatumGetVector(value), VECTOR_SIZE(buildstate->dimensions));
|
||||||
element = HnswInitElement(heaptid, buildstate->m, buildstate->ml, buildstate->maxLevel);
|
|
||||||
element->value = datumCopy(value, false, -1);
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
|
||||||
|
|
||||||
/* Update memory usage */
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
graph->memoryUsed = MemoryContextMemAllocated(buildstate->graphCtx, false);
|
|
||||||
#else
|
|
||||||
graph->memoryUsed += HnswElementMemory(element, buildstate->m);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Insert element in graph */
|
/* Insert element in graph */
|
||||||
HnswInsertElement(element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
HnswInsertElement(element, entryPoint, NULL, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
/* Look for duplicate */
|
/* Look for duplicate */
|
||||||
if (HnswFindDuplicateInMemory(element))
|
*dup = HnswFindDuplicate(element);
|
||||||
|
|
||||||
|
/* Update neighbors if needed */
|
||||||
|
if (*dup == NULL)
|
||||||
{
|
{
|
||||||
/* No need to free element since memory unlikely to be reallocated */
|
for (int lc = element->level; lc >= 0; lc--)
|
||||||
return true;
|
{
|
||||||
}
|
int lm = HnswGetLayerM(m, lc);
|
||||||
|
HnswNeighborArray *neighbors = &element->neighbors[lc];
|
||||||
|
|
||||||
/* Add element */
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
slist_push_head(&graph->elements, &element->next);
|
HnswUpdateConnection(element, &neighbors->items[i], lm, lc, NULL, NULL, procinfo, collation);
|
||||||
|
}
|
||||||
/* Update neighbors */
|
|
||||||
for (int lc = element->level; lc >= 0; lc--)
|
|
||||||
{
|
|
||||||
int lm = HnswGetLayerM(m, lc);
|
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(element, lc);
|
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
|
||||||
HnswUpdateConnection(element, &neighbors->items[i], lm, lc, NULL, NULL, procinfo, collation);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Update entry point if needed */
|
/* Update entry point if needed */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (*dup == NULL && (entryPoint == NULL || element->level > entryPoint->level))
|
||||||
graph->entryPoint = element;
|
buildstate->entryPoint = element;
|
||||||
|
|
||||||
return true;
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
return *dup == NULL;
|
||||||
* Acquire a lock if needed
|
|
||||||
*/
|
|
||||||
static inline void
|
|
||||||
HnswLockAcquire(HnswShared * hnswshared)
|
|
||||||
{
|
|
||||||
if (hnswshared)
|
|
||||||
SpinLockAcquire(&hnswshared->mutex);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Release a lock if needed
|
|
||||||
*/
|
|
||||||
static inline void
|
|
||||||
HnswLockRelease(HnswShared * hnswshared)
|
|
||||||
{
|
|
||||||
if (hnswshared)
|
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -439,9 +344,9 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
bool *isnull, bool tupleIsAlive, void *state)
|
bool *isnull, bool tupleIsAlive, void *state)
|
||||||
{
|
{
|
||||||
HnswBuildState *buildstate = (HnswBuildState *) state;
|
HnswBuildState *buildstate = (HnswBuildState *) state;
|
||||||
HnswGraph *graph = buildstate->graph;
|
|
||||||
HnswShared *hnswshared = buildstate->hnswshared;
|
|
||||||
MemoryContext oldCtx;
|
MemoryContext oldCtx;
|
||||||
|
HnswElement element;
|
||||||
|
HnswElement dup = NULL;
|
||||||
bool inserted;
|
bool inserted;
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 130000
|
#if PG_VERSION_NUM < 130000
|
||||||
@@ -452,50 +357,70 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
if (isnull[0])
|
if (isnull[0])
|
||||||
return;
|
return;
|
||||||
|
|
||||||
/* Flush pages if needed */
|
if (buildstate->indtuples >= buildstate->maxInMemoryElements)
|
||||||
if (!graph->flushed && graph->memoryUsed >= graph->memoryTotal)
|
|
||||||
{
|
{
|
||||||
ereport(NOTICE,
|
if (!buildstate->flushed)
|
||||||
(errmsg("hnsw graph no longer fits into maintenance_work_mem after " INT64_FORMAT " tuples", (int64) graph->indtuples),
|
{
|
||||||
errdetail("Building will take significantly more time."),
|
ereport(NOTICE,
|
||||||
errhint("Increase maintenance_work_mem to speed up builds.")));
|
(errmsg("hnsw graph no longer fits into maintenance_work_mem after " INT64_FORMAT " tuples", (int64) buildstate->indtuples),
|
||||||
|
errdetail("Building will take significantly more time."),
|
||||||
|
errhint("Increase maintenance_work_mem to speed up builds.")));
|
||||||
|
|
||||||
FlushPages(buildstate);
|
FlushPages(buildstate);
|
||||||
|
}
|
||||||
|
|
||||||
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
|
|
||||||
|
/* TODO Fix progress for parallel builds */
|
||||||
|
if (HnswInsertTuple(buildstate->index, values, isnull, tid, buildstate->heap))
|
||||||
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
||||||
|
|
||||||
|
/* Reset memory context */
|
||||||
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
MemoryContextReset(buildstate->tmpCtx);
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Allocate necessary memory outside of memory context */
|
||||||
|
element = HnswInitElement(tid, buildstate->m, buildstate->ml, buildstate->maxLevel);
|
||||||
|
element->vec = palloc(VECTOR_SIZE(buildstate->dimensions));
|
||||||
|
|
||||||
|
/* Use memory context since detoast can allocate */
|
||||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
|
|
||||||
/* Insert tuple */
|
/* Insert tuple */
|
||||||
if (graph->flushed)
|
inserted = InsertTuple(index, values, element, buildstate, &dup);
|
||||||
inserted = HnswInsertTuple(index, values, isnull, tid, buildstate->heap, true);
|
|
||||||
else
|
|
||||||
inserted = InsertTupleInMemory(index, values, tid, buildstate);
|
|
||||||
|
|
||||||
/* Update progress */
|
|
||||||
if (inserted)
|
|
||||||
{
|
|
||||||
HnswLockAcquire(hnswshared);
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++graph->indtuples);
|
|
||||||
HnswLockRelease(hnswshared);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Reset memory context */
|
/* Reset memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
MemoryContextReset(buildstate->tmpCtx);
|
MemoryContextReset(buildstate->tmpCtx);
|
||||||
|
|
||||||
|
/* Add outside memory context */
|
||||||
|
if (dup != NULL)
|
||||||
|
HnswAddHeapTid(dup, tid);
|
||||||
|
|
||||||
|
/* Add to buildstate or free */
|
||||||
|
if (inserted)
|
||||||
|
buildstate->elements = lappend(buildstate->elements, element);
|
||||||
|
else
|
||||||
|
HnswFreeElement(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Initialize the graph
|
* Get the max number of elements that fit into maintenance_work_mem
|
||||||
*/
|
*/
|
||||||
static void
|
static double
|
||||||
InitGraph(HnswGraph * graph)
|
HnswGetMaxInMemoryElements(int m, double ml, int dimensions)
|
||||||
{
|
{
|
||||||
slist_init(&graph->elements);
|
Size elementSize = sizeof(HnswElementData);
|
||||||
graph->entryPoint = NULL;
|
double avgLevel = -log(0.5) * ml;
|
||||||
graph->memoryUsed = 0;
|
|
||||||
graph->memoryTotal = maintenance_work_mem * 1024L;
|
elementSize += sizeof(HnswNeighborArray) * (avgLevel + 1);
|
||||||
graph->flushed = false;
|
elementSize += sizeof(HnswCandidate) * (m * (avgLevel + 2));
|
||||||
graph->indtuples = 0;
|
elementSize += sizeof(ItemPointerData);
|
||||||
|
elementSize += VECTOR_SIZE(dimensions);
|
||||||
|
return (maintenance_work_mem * 1024L) / elementSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -531,26 +456,21 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
buildstate->normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
buildstate->normprocinfo = HnswOptionalProcInfo(index, HNSW_NORM_PROC);
|
||||||
buildstate->collation = index->rd_indcollation[0];
|
buildstate->collation = index->rd_indcollation[0];
|
||||||
|
|
||||||
InitGraph(&buildstate->graphData);
|
buildstate->elements = NIL;
|
||||||
buildstate->graph = &buildstate->graphData;
|
buildstate->entryPoint = NULL;
|
||||||
buildstate->ml = HnswGetMl(buildstate->m);
|
buildstate->ml = HnswGetMl(buildstate->m);
|
||||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||||
|
buildstate->maxInMemoryElements = HnswGetMaxInMemoryElements(buildstate->m, buildstate->ml, buildstate->dimensions);
|
||||||
|
buildstate->flushed = false;
|
||||||
|
|
||||||
/* Reuse for each tuple */
|
/* Reuse for each tuple */
|
||||||
buildstate->normvec = InitVector(buildstate->dimensions);
|
buildstate->normvec = InitVector(buildstate->dimensions);
|
||||||
|
|
||||||
buildstate->graphCtx = GenerationContextCreate(CurrentMemoryContext,
|
|
||||||
"Hnsw build graph context",
|
|
||||||
#if PG_VERSION_NUM >= 150000
|
|
||||||
1024 * 1024, 1024 * 1024,
|
|
||||||
#endif
|
|
||||||
1024 * 1024);
|
|
||||||
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
buildstate->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Hnsw build temporary context",
|
"Hnsw build temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
|
|
||||||
buildstate->hnswleader = NULL;
|
buildstate->hnswleader = NULL;
|
||||||
buildstate->hnswshared = NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -560,7 +480,6 @@ static void
|
|||||||
FreeBuildState(HnswBuildState * buildstate)
|
FreeBuildState(HnswBuildState * buildstate)
|
||||||
{
|
{
|
||||||
pfree(buildstate->normvec);
|
pfree(buildstate->normvec);
|
||||||
MemoryContextDelete(buildstate->graphCtx);
|
|
||||||
MemoryContextDelete(buildstate->tmpCtx);
|
MemoryContextDelete(buildstate->tmpCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,7 +499,7 @@ ParallelHeapScan(HnswBuildState * buildstate)
|
|||||||
SpinLockAcquire(&hnswshared->mutex);
|
SpinLockAcquire(&hnswshared->mutex);
|
||||||
if (hnswshared->nparticipantsdone == nparticipanttuplesorts)
|
if (hnswshared->nparticipantsdone == nparticipanttuplesorts)
|
||||||
{
|
{
|
||||||
buildstate->graph = &hnswshared->graphData;
|
buildstate->indtuples = hnswshared->indtuples;
|
||||||
reltuples = hnswshared->reltuples;
|
reltuples = hnswshared->reltuples;
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
SpinLockRelease(&hnswshared->mutex);
|
||||||
break;
|
break;
|
||||||
@@ -615,8 +534,9 @@ HnswParallelScanAndInsert(HnswSpool * hnswspool, HnswShared * hnswshared, bool p
|
|||||||
indexInfo = BuildIndexInfo(hnswspool->index);
|
indexInfo = BuildIndexInfo(hnswspool->index);
|
||||||
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
||||||
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
||||||
buildstate.graph = &hnswshared->graphData;
|
/* TODO Support in-memory builds */
|
||||||
buildstate.hnswshared = hnswshared;
|
buildstate.maxInMemoryElements = 0;
|
||||||
|
buildstate.flushed = true;
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan = table_beginscan_parallel(hnswspool->heap,
|
scan = table_beginscan_parallel(hnswspool->heap,
|
||||||
ParallelTableScanFromHnswShared(hnswshared));
|
ParallelTableScanFromHnswShared(hnswshared));
|
||||||
@@ -634,6 +554,7 @@ HnswParallelScanAndInsert(HnswSpool * hnswspool, HnswShared * hnswshared, bool p
|
|||||||
SpinLockAcquire(&hnswshared->mutex);
|
SpinLockAcquire(&hnswshared->mutex);
|
||||||
hnswshared->nparticipantsdone++;
|
hnswshared->nparticipantsdone++;
|
||||||
hnswshared->reltuples += reltuples;
|
hnswshared->reltuples += reltuples;
|
||||||
|
hnswshared->indtuples += buildstate.indtuples;
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
SpinLockRelease(&hnswshared->mutex);
|
||||||
|
|
||||||
/* Log statistics */
|
/* Log statistics */
|
||||||
@@ -840,10 +761,7 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
/* Initialize mutable state */
|
/* Initialize mutable state */
|
||||||
hnswshared->nparticipantsdone = 0;
|
hnswshared->nparticipantsdone = 0;
|
||||||
hnswshared->reltuples = 0;
|
hnswshared->reltuples = 0;
|
||||||
InitGraph(&hnswshared->graphData);
|
hnswshared->indtuples = 0;
|
||||||
/* TODO Support in-memory builds */
|
|
||||||
hnswshared->graphData.memoryTotal = 0;
|
|
||||||
hnswshared->graphData.flushed = true;
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
table_parallelscan_initialize(buildstate->heap,
|
table_parallelscan_initialize(buildstate->heap,
|
||||||
ParallelTableScanFromHnswShared(hnswshared),
|
ParallelTableScanFromHnswShared(hnswshared),
|
||||||
@@ -894,27 +812,6 @@ HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|||||||
WaitForParallelWorkersToAttach(pcxt);
|
WaitForParallelWorkersToAttach(pcxt);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Compute parallel workers
|
|
||||||
*/
|
|
||||||
static int
|
|
||||||
ComputeParallelWorkers(Relation heap, Relation index)
|
|
||||||
{
|
|
||||||
int parallel_workers;
|
|
||||||
|
|
||||||
/* Make sure it's safe to use parallel workers */
|
|
||||||
parallel_workers = plan_create_index_workers(RelationGetRelid(heap), RelationGetRelid(index));
|
|
||||||
if (parallel_workers == 0)
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
/* Use parallel_workers storage parameter on table if set */
|
|
||||||
parallel_workers = RelationGetParallelWorkers(heap, -1);
|
|
||||||
if (parallel_workers != -1)
|
|
||||||
return Min(parallel_workers, max_parallel_maintenance_workers);
|
|
||||||
|
|
||||||
return max_parallel_maintenance_workers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Build graph
|
* Build graph
|
||||||
*/
|
*/
|
||||||
@@ -926,8 +823,7 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
/* Calculate parallel workers */
|
||||||
if (buildstate->heap != NULL && hnsw_enable_parallel_build)
|
parallel_workers = plan_create_index_workers(RelationGetRelid(buildstate->heap), RelationGetRelid(buildstate->index));
|
||||||
parallel_workers = ComputeParallelWorkers(buildstate->heap, buildstate->index);
|
|
||||||
|
|
||||||
/* Attempt to launch parallel worker scan when required */
|
/* Attempt to launch parallel worker scan when required */
|
||||||
if (parallel_workers > 0)
|
if (parallel_workers > 0)
|
||||||
@@ -937,50 +833,25 @@ BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
|||||||
HnswBeginParallel(buildstate, buildstate->indexInfo->ii_Concurrent, parallel_workers);
|
HnswBeginParallel(buildstate, buildstate->indexInfo->ii_Concurrent, parallel_workers);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add tuples to graph */
|
/* Add tuples to sort */
|
||||||
if (buildstate->heap != NULL)
|
if (buildstate->hnswleader)
|
||||||
|
buildstate->reltuples = ParallelHeapScan(buildstate);
|
||||||
|
else
|
||||||
{
|
{
|
||||||
if (buildstate->hnswleader)
|
|
||||||
buildstate->reltuples = ParallelHeapScan(buildstate);
|
|
||||||
else
|
|
||||||
{
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
true, true, BuildCallback, (void *) buildstate, NULL);
|
true, true, BuildCallback, (void *) buildstate, NULL);
|
||||||
#else
|
#else
|
||||||
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
buildstate->reltuples = IndexBuildHeapScan(buildstate->heap, buildstate->index, buildstate->indexInfo,
|
||||||
true, BuildCallback, (void *) buildstate, NULL);
|
true, BuildCallback, (void *) buildstate, NULL);
|
||||||
#endif
|
#endif
|
||||||
}
|
|
||||||
|
|
||||||
buildstate->indtuples = buildstate->graph->indtuples;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Flush pages */
|
|
||||||
if (!buildstate->graph->flushed)
|
|
||||||
FlushPages(buildstate);
|
|
||||||
|
|
||||||
/* End parallel build */
|
/* End parallel build */
|
||||||
if (buildstate->hnswleader)
|
if (buildstate->hnswleader)
|
||||||
HnswEndParallel(buildstate->hnswleader);
|
HnswEndParallel(buildstate->hnswleader);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 110008
|
|
||||||
void
|
|
||||||
log_newpage_range(Relation rel, ForkNumber forkNum, BlockNumber startblk, BlockNumber endblk, bool page_std)
|
|
||||||
{
|
|
||||||
for (BlockNumber blkno = startblk; blkno < endblk; blkno++)
|
|
||||||
{
|
|
||||||
Buffer buf = ReadBufferExtended(rel, forkNum, blkno, RBM_NORMAL, NULL);
|
|
||||||
|
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
|
||||||
MarkBufferDirty(buf);
|
|
||||||
log_newpage_buffer(buf, page_std);
|
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Build the index
|
* Build the index
|
||||||
*/
|
*/
|
||||||
@@ -988,16 +859,13 @@ static void
|
|||||||
BuildIndex(Relation heap, Relation index, IndexInfo *indexInfo,
|
BuildIndex(Relation heap, Relation index, IndexInfo *indexInfo,
|
||||||
HnswBuildState * buildstate, ForkNumber forkNum)
|
HnswBuildState * buildstate, ForkNumber forkNum)
|
||||||
{
|
{
|
||||||
#ifdef HNSW_MEMORY
|
|
||||||
SeedRandom(42);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
InitBuildState(buildstate, heap, index, indexInfo, forkNum);
|
InitBuildState(buildstate, heap, index, indexInfo, forkNum);
|
||||||
|
|
||||||
BuildGraph(buildstate, forkNum);
|
if (buildstate->heap != NULL)
|
||||||
|
BuildGraph(buildstate, forkNum);
|
||||||
|
|
||||||
if (RelationNeedsWAL(index))
|
if (!buildstate->flushed)
|
||||||
log_newpage_range(index, forkNum, 0, RelationGetNumberOfBlocks(index), true);
|
FlushPages(buildstate);
|
||||||
|
|
||||||
FreeBuildState(buildstate);
|
FreeBuildState(buildstate);
|
||||||
}
|
}
|
||||||
|
|||||||
202
src/hnswinsert.c
202
src/hnswinsert.c
@@ -5,7 +5,6 @@
|
|||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "storage/lmgr.h"
|
#include "storage/lmgr.h"
|
||||||
#include "utils/datum.h"
|
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -93,7 +92,7 @@ HnswFreeOffset(Relation index, Buffer buf, Page page, HnswElement element, Size
|
|||||||
* Add a new page
|
* Add a new page
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
HnswInsertAppendPage(Relation index, Buffer *nbuf, Page *npage, GenericXLogState *state, Page page, bool building)
|
HnswInsertAppendPage(Relation index, Buffer *nbuf, Page *npage, GenericXLogState *state, Page page)
|
||||||
{
|
{
|
||||||
/* Add a new page */
|
/* Add a new page */
|
||||||
LockRelationForExtension(index, ExclusiveLock);
|
LockRelationForExtension(index, ExclusiveLock);
|
||||||
@@ -101,11 +100,7 @@ HnswInsertAppendPage(Relation index, Buffer *nbuf, Page *npage, GenericXLogState
|
|||||||
UnlockRelationForExtension(index, ExclusiveLock);
|
UnlockRelationForExtension(index, ExclusiveLock);
|
||||||
|
|
||||||
/* Init new page */
|
/* Init new page */
|
||||||
if (building)
|
*npage = GenericXLogRegisterBuffer(state, *nbuf, GENERIC_XLOG_FULL_IMAGE);
|
||||||
*npage = BufferGetPage(*nbuf);
|
|
||||||
else
|
|
||||||
*npage = GenericXLogRegisterBuffer(state, *nbuf, GENERIC_XLOG_FULL_IMAGE);
|
|
||||||
|
|
||||||
HnswInitPage(*nbuf, *npage);
|
HnswInitPage(*nbuf, *npage);
|
||||||
|
|
||||||
/* Update previous buffer */
|
/* Update previous buffer */
|
||||||
@@ -116,7 +111,7 @@ HnswInsertAppendPage(Relation index, Buffer *nbuf, Page *npage, GenericXLogState
|
|||||||
* Add to element and neighbor pages
|
* Add to element and neighbor pages
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage, bool building)
|
WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPage, BlockNumber *updatedInsertPage)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -128,6 +123,7 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
Size minCombinedSize;
|
Size minCombinedSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
BlockNumber currentPage = insertPage;
|
BlockNumber currentPage = insertPage;
|
||||||
|
int dimensions = e->vec->dim;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
Buffer nbuf;
|
Buffer nbuf;
|
||||||
Page npage;
|
Page npage;
|
||||||
@@ -136,10 +132,10 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = HNSW_ELEMENT_TUPLE_SIZE(VARSIZE_ANY(DatumGetPointer(e->value)));
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(dimensions);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData));
|
||||||
minCombinedSize = etupSize + HNSW_NEIGHBOR_TUPLE_SIZE(0, m) + sizeof(ItemIdData);
|
minCombinedSize = etupSize + HNSW_NEIGHBOR_TUPLE_SIZE(0, m) + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* Prepare element tuple */
|
/* Prepare element tuple */
|
||||||
@@ -156,16 +152,8 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
buf = ReadBuffer(index, currentPage);
|
buf = ReadBuffer(index, currentPage);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
|
|
||||||
if (building)
|
state = GenericXLogStart(index);
|
||||||
{
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
state = NULL;
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state = GenericXLogStart(index);
|
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Keep track of first page where element at level 0 can fit */
|
/* Keep track of first page where element at level 0 can fit */
|
||||||
if (!BlockNumberIsValid(newInsertPage) && PageGetFreeSpace(page) >= minCombinedSize)
|
if (!BlockNumberIsValid(newInsertPage) && PageGetFreeSpace(page) >= minCombinedSize)
|
||||||
@@ -185,12 +173,7 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
if (HnswFreeOffset(index, buf, page, e, ntupSize, &nbuf, &npage, &freeOffno, &freeNeighborOffno, &newInsertPage))
|
if (HnswFreeOffset(index, buf, page, e, ntupSize, &nbuf, &npage, &freeOffno, &freeNeighborOffno, &newInsertPage))
|
||||||
{
|
{
|
||||||
if (nbuf != buf)
|
if (nbuf != buf)
|
||||||
{
|
npage = GenericXLogRegisterBuffer(state, nbuf, 0);
|
||||||
if (building)
|
|
||||||
npage = BufferGetPage(nbuf);
|
|
||||||
else
|
|
||||||
npage = GenericXLogRegisterBuffer(state, nbuf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -199,7 +182,7 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
/* Skip if both tuples can fit on the same page */
|
/* Skip if both tuples can fit on the same page */
|
||||||
if (combinedSize > maxSize && PageGetFreeSpace(page) >= etupSize && !BlockNumberIsValid(HnswPageGetOpaque(page)->nextblkno))
|
if (combinedSize > maxSize && PageGetFreeSpace(page) >= etupSize && !BlockNumberIsValid(HnswPageGetOpaque(page)->nextblkno))
|
||||||
{
|
{
|
||||||
HnswInsertAppendPage(index, &nbuf, &npage, state, page, building);
|
HnswInsertAppendPage(index, &nbuf, &npage, state, page);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,8 +191,7 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
if (BlockNumberIsValid(currentPage))
|
if (BlockNumberIsValid(currentPage))
|
||||||
{
|
{
|
||||||
/* Move to next page */
|
/* Move to next page */
|
||||||
if (!building)
|
GenericXLogAbort(state);
|
||||||
GenericXLogAbort(state);
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -217,33 +199,24 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
Buffer newbuf;
|
Buffer newbuf;
|
||||||
Page newpage;
|
Page newpage;
|
||||||
|
|
||||||
HnswInsertAppendPage(index, &newbuf, &newpage, state, page, building);
|
HnswInsertAppendPage(index, &newbuf, &newpage, state, page);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
MarkBufferDirty(newbuf);
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(buf);
|
||||||
else
|
GenericXLogFinish(state);
|
||||||
GenericXLogFinish(state);
|
|
||||||
|
|
||||||
/* Unlock previous buffer */
|
/* Unlock previous buffer */
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
/* Prepare new buffer */
|
/* Prepare new buffer */
|
||||||
|
state = GenericXLogStart(index);
|
||||||
buf = newbuf;
|
buf = newbuf;
|
||||||
if (building)
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
{
|
|
||||||
state = NULL;
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state = GenericXLogStart(index);
|
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Create new page for neighbors if needed */
|
/* Create new page for neighbors if needed */
|
||||||
if (PageGetFreeSpace(page) < combinedSize)
|
if (PageGetFreeSpace(page) < combinedSize)
|
||||||
HnswInsertAppendPage(index, &nbuf, &npage, state, page, building);
|
HnswInsertAppendPage(index, &nbuf, &npage, state, page);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
nbuf = buf;
|
nbuf = buf;
|
||||||
@@ -297,14 +270,10 @@ WriteNewElementPages(Relation index, HnswElement e, int m, BlockNumber insertPag
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
MarkBufferDirty(buf);
|
||||||
{
|
if (nbuf != buf)
|
||||||
MarkBufferDirty(buf);
|
MarkBufferDirty(nbuf);
|
||||||
if (nbuf != buf)
|
GenericXLogFinish(state);
|
||||||
MarkBufferDirty(nbuf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
GenericXLogFinish(state);
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
if (nbuf != buf)
|
if (nbuf != buf)
|
||||||
UnlockReleaseBuffer(nbuf);
|
UnlockReleaseBuffer(nbuf);
|
||||||
@@ -338,12 +307,12 @@ ConnectionExists(HnswElement e, HnswNeighborTuple ntup, int startIdx, int lm)
|
|||||||
* Update neighbors
|
* Update neighbors
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting, bool building)
|
HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement e, int m, bool checkExisting)
|
||||||
{
|
{
|
||||||
for (int lc = e->level; lc >= 0; lc--)
|
for (int lc = e->level; lc >= 0; lc--)
|
||||||
{
|
{
|
||||||
int lm = HnswGetLayerM(m, lc);
|
int lm = HnswGetLayerM(m, lc);
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(e, lc);
|
HnswNeighborArray *neighbors = &e->neighbors[lc];
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
{
|
{
|
||||||
@@ -360,7 +329,7 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
|
|
||||||
/* Get latest neighbors since they may have changed */
|
/* Get latest neighbors since they may have changed */
|
||||||
/* Do not lock yet since selecting neighbors can take time */
|
/* Do not lock yet since selecting neighbors can take time */
|
||||||
HnswLoadNeighbors(hc->element, index, m);
|
HnswLoadNeighbors(hc->element, index);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Could improve performance for vacuuming by checking neighbors
|
* Could improve performance for vacuuming by checking neighbors
|
||||||
@@ -379,16 +348,8 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
/* Register page */
|
/* Register page */
|
||||||
buf = ReadBuffer(index, hc->element->neighborPage);
|
buf = ReadBuffer(index, hc->element->neighborPage);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
if (building)
|
state = GenericXLogStart(index);
|
||||||
{
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
state = NULL;
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state = GenericXLogStart(index);
|
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Get tuple */
|
/* Get tuple */
|
||||||
itemid = PageGetItemId(page, offno);
|
itemid = PageGetItemId(page, offno);
|
||||||
@@ -430,12 +391,10 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
MarkBufferDirty(buf);
|
||||||
MarkBufferDirty(buf);
|
GenericXLogFinish(state);
|
||||||
else
|
|
||||||
GenericXLogFinish(state);
|
|
||||||
}
|
}
|
||||||
else if (!building)
|
else
|
||||||
GenericXLogAbort(state);
|
GenericXLogAbort(state);
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
@@ -447,34 +406,23 @@ HnswUpdateNeighborPages(Relation index, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
* Add a heap TID to an existing element
|
* Add a heap TID to an existing element
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool building)
|
HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
ItemId itemid;
|
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(dup->vec->dim);
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
Size etupSize;
|
|
||||||
int i;
|
int i;
|
||||||
|
|
||||||
/* Read page */
|
/* Read page */
|
||||||
buf = ReadBuffer(index, dup->blkno);
|
buf = ReadBuffer(index, dup->blkno);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
if (building)
|
state = GenericXLogStart(index);
|
||||||
{
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
state = NULL;
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state = GenericXLogStart(index);
|
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Find space */
|
/* Find space */
|
||||||
itemid = PageGetItemId(page, dup->offno);
|
etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, dup->offno));
|
||||||
etup = (HnswElementTuple) PageGetItem(page, itemid);
|
|
||||||
etupSize = ItemIdGetLength(itemid);
|
|
||||||
for (i = 0; i < HNSW_HEAPTIDS; i++)
|
for (i = 0; i < HNSW_HEAPTIDS; i++)
|
||||||
{
|
{
|
||||||
if (!ItemPointerIsValid(&etup->heaptids[i]))
|
if (!ItemPointerIsValid(&etup->heaptids[i]))
|
||||||
@@ -484,93 +432,72 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup, bool buil
|
|||||||
/* Either being deleted or we lost our chance to another backend */
|
/* Either being deleted or we lost our chance to another backend */
|
||||||
if (i == 0 || i == HNSW_HEAPTIDS)
|
if (i == 0 || i == HNSW_HEAPTIDS)
|
||||||
{
|
{
|
||||||
if (!building)
|
GenericXLogAbort(state);
|
||||||
GenericXLogAbort(state);
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add heap TID */
|
/* Add heap TID */
|
||||||
etup->heaptids[i] = element->heaptids[0];
|
etup->heaptids[i] = *((ItemPointer) linitial(element->heaptids));
|
||||||
|
|
||||||
/* Overwrite tuple */
|
/* Overwrite tuple */
|
||||||
if (!PageIndexTupleOverwrite(page, dup->offno, (Item) etup, etupSize))
|
if (!PageIndexTupleOverwrite(page, dup->offno, (Item) etup, etupSize))
|
||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
if (building)
|
MarkBufferDirty(buf);
|
||||||
MarkBufferDirty(buf);
|
GenericXLogFinish(state);
|
||||||
else
|
|
||||||
GenericXLogFinish(state);
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Find duplicate element
|
|
||||||
*/
|
|
||||||
static bool
|
|
||||||
HnswFindDuplicate(Relation index, HnswElement element, bool building)
|
|
||||||
{
|
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(element, 0);
|
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
|
||||||
{
|
|
||||||
HnswCandidate *neighbor = &neighbors->items[i];
|
|
||||||
|
|
||||||
/* Exit early since ordered by distance */
|
|
||||||
if (!datumIsEqual(element->value, neighbor->element->value, false, -1))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
if (HnswAddDuplicate(index, element, neighbor->element, building))
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Write changes to disk
|
* Write changes to disk
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
WriteElement(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement entryPoint, bool building)
|
WriteElement(Relation index, FmgrInfo *procinfo, Oid collation, HnswElement element, int m, int efConstruction, HnswElement dup, HnswElement entryPoint)
|
||||||
{
|
{
|
||||||
BlockNumber newInsertPage = InvalidBlockNumber;
|
BlockNumber newInsertPage = InvalidBlockNumber;
|
||||||
|
|
||||||
/* Look for duplicate */
|
/* Try to add to existing page */
|
||||||
if (HnswFindDuplicate(index, element, building))
|
if (dup != NULL)
|
||||||
return;
|
{
|
||||||
|
if (HnswAddDuplicate(index, element, dup))
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
/* Write element and neighbor tuples */
|
/* Write element and neighbor tuples */
|
||||||
WriteNewElementPages(index, element, m, GetInsertPage(index), &newInsertPage, building);
|
WriteNewElementPages(index, element, m, GetInsertPage(index), &newInsertPage);
|
||||||
|
|
||||||
/* Update insert page if needed */
|
/* Update insert page if needed */
|
||||||
if (BlockNumberIsValid(newInsertPage))
|
if (BlockNumberIsValid(newInsertPage))
|
||||||
HnswUpdateMetaPage(index, 0, NULL, newInsertPage, MAIN_FORKNUM, building);
|
HnswUpdateMetaPage(index, 0, NULL, newInsertPage, MAIN_FORKNUM);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborPages(index, procinfo, collation, element, m, false, building);
|
HnswUpdateNeighborPages(index, procinfo, collation, element, m, false);
|
||||||
|
|
||||||
/* Update entry point if needed */
|
/* Update metapage if needed */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_GREATER, element, InvalidBlockNumber, MAIN_FORKNUM, building);
|
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_GREATER, element, InvalidBlockNumber, MAIN_FORKNUM);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Insert a tuple into the index
|
* Insert a tuple into the index
|
||||||
*/
|
*/
|
||||||
bool
|
bool
|
||||||
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel, bool building)
|
HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
||||||
{
|
{
|
||||||
Datum value;
|
Datum value;
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
HnswElement element;
|
HnswElement element;
|
||||||
int m;
|
int m = HnswGetM(index);
|
||||||
int efConstruction = HnswGetEfConstruction(index);
|
int efConstruction = HnswGetEfConstruction(index);
|
||||||
|
double ml = HnswGetMl(m);
|
||||||
FmgrInfo *procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
FmgrInfo *procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
||||||
Oid collation = index->rd_indcollation[0];
|
Oid collation = index->rd_indcollation[0];
|
||||||
|
HnswElement dup;
|
||||||
LOCKMODE lockmode = ShareLock;
|
LOCKMODE lockmode = ShareLock;
|
||||||
|
|
||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
@@ -584,6 +511,10 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Create an element */
|
||||||
|
element = HnswInitElement(heap_tid, m, ml, HnswGetMaxLevel(m));
|
||||||
|
element->vec = DatumGetVector(value);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get a shared lock. This allows vacuum to ensure no in-flight inserts
|
* Get a shared lock. This allows vacuum to ensure no in-flight inserts
|
||||||
* before repairing graph. Use a page lock so it does not interfere with
|
* before repairing graph. Use a page lock so it does not interfere with
|
||||||
@@ -591,12 +522,8 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
*/
|
*/
|
||||||
LockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
LockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||||
|
|
||||||
/* Get m and entry point */
|
/* Get entry point */
|
||||||
HnswGetMetaPageInfo(index, &m, &entryPoint);
|
entryPoint = HnswGetEntryPoint(index);
|
||||||
|
|
||||||
/* Create an element */
|
|
||||||
element = HnswInitElement(heap_tid, m, HnswGetMl(m), HnswGetMaxLevel(m));
|
|
||||||
element->value = value;
|
|
||||||
|
|
||||||
/* Prevent concurrent inserts when likely updating entry point */
|
/* Prevent concurrent inserts when likely updating entry point */
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
@@ -615,8 +542,11 @@ HnswInsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_ti
|
|||||||
/* Insert element in graph */
|
/* Insert element in graph */
|
||||||
HnswInsertElement(element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
HnswInsertElement(element, entryPoint, index, procinfo, collation, m, efConstruction, false);
|
||||||
|
|
||||||
|
/* Look for duplicate */
|
||||||
|
dup = HnswFindDuplicate(element);
|
||||||
|
|
||||||
/* Write to disk */
|
/* Write to disk */
|
||||||
WriteElement(index, procinfo, collation, element, m, efConstruction, entryPoint, building);
|
WriteElement(index, procinfo, collation, element, m, efConstruction, dup, entryPoint);
|
||||||
|
|
||||||
/* Release lock */
|
/* Release lock */
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||||
@@ -650,7 +580,7 @@ hnswinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid,
|
|||||||
oldCtx = MemoryContextSwitchTo(insertCtx);
|
oldCtx = MemoryContextSwitchTo(insertCtx);
|
||||||
|
|
||||||
/* Insert tuple */
|
/* Insert tuple */
|
||||||
HnswInsertTuple(index, values, isnull, heap_tid, heap, false);
|
HnswInsertTuple(index, values, isnull, heap_tid, heap);
|
||||||
|
|
||||||
/* Delete memory context */
|
/* Delete memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|||||||
@@ -19,11 +19,7 @@ GetScanItems(IndexScanDesc scan, Datum q)
|
|||||||
Oid collation = so->collation;
|
Oid collation = so->collation;
|
||||||
List *ep;
|
List *ep;
|
||||||
List *w;
|
List *w;
|
||||||
int m;
|
HnswElement entryPoint = HnswGetEntryPoint(index);
|
||||||
HnswElement entryPoint;
|
|
||||||
|
|
||||||
/* Get m and entry point */
|
|
||||||
HnswGetMetaPageInfo(index, &m, &entryPoint);
|
|
||||||
|
|
||||||
if (entryPoint == NULL)
|
if (entryPoint == NULL)
|
||||||
return NIL;
|
return NIL;
|
||||||
@@ -32,11 +28,11 @@ GetScanItems(IndexScanDesc scan, Datum q)
|
|||||||
|
|
||||||
for (int lc = entryPoint->level; lc >= 1; lc--)
|
for (int lc = entryPoint->level; lc >= 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(q, ep, 1, lc, index, procinfo, collation, m, false, NULL);
|
w = HnswSearchLayer(q, ep, 1, lc, index, procinfo, collation, false, NULL);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
return HnswSearchLayer(q, ep, hnsw_ef_search, 0, index, procinfo, collation, m, false, NULL);
|
return HnswSearchLayer(q, ep, hnsw_ef_search, 0, index, procinfo, collation, false, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -62,33 +58,6 @@ GetDimensions(Relation index)
|
|||||||
return dimensions;
|
return dimensions;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Get scan value
|
|
||||||
*/
|
|
||||||
static Datum
|
|
||||||
GetScanValue(IndexScanDesc scan)
|
|
||||||
{
|
|
||||||
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
|
||||||
Datum value;
|
|
||||||
|
|
||||||
if (scan->orderByData->sk_flags & SK_ISNULL)
|
|
||||||
value = PointerGetDatum(InitVector(GetDimensions(scan->indexRelation)));
|
|
||||||
else
|
|
||||||
{
|
|
||||||
value = scan->orderByData->sk_argument;
|
|
||||||
|
|
||||||
/* Value should not be compressed or toasted */
|
|
||||||
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
|
|
||||||
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
|
|
||||||
|
|
||||||
/* Fine if normalization fails */
|
|
||||||
if (so->normprocinfo != NULL)
|
|
||||||
HnswNormValue(so->normprocinfo, so->collation, &value, NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Prepare for an index scan
|
* Prepare for an index scan
|
||||||
*/
|
*/
|
||||||
@@ -101,6 +70,7 @@ hnswbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
scan = RelationGetIndexScan(index, nkeys, norderbys);
|
scan = RelationGetIndexScan(index, nkeys, norderbys);
|
||||||
|
|
||||||
so = (HnswScanOpaque) palloc(sizeof(HnswScanOpaqueData));
|
so = (HnswScanOpaque) palloc(sizeof(HnswScanOpaqueData));
|
||||||
|
so->buf = InvalidBuffer;
|
||||||
so->first = true;
|
so->first = true;
|
||||||
so->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
so->tmpCtx = AllocSetContextCreate(CurrentMemoryContext,
|
||||||
"Hnsw scan temporary context",
|
"Hnsw scan temporary context",
|
||||||
@@ -160,13 +130,20 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
if (scan->orderByData == NULL)
|
if (scan->orderByData == NULL)
|
||||||
elog(ERROR, "cannot scan hnsw index without order");
|
elog(ERROR, "cannot scan hnsw index without order");
|
||||||
|
|
||||||
/* Requires MVCC-compliant snapshot as not able to maintain a pin */
|
if (scan->orderByData->sk_flags & SK_ISNULL)
|
||||||
/* https://www.postgresql.org/docs/current/index-locking.html */
|
value = PointerGetDatum(InitVector(GetDimensions(scan->indexRelation)));
|
||||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
else
|
||||||
elog(ERROR, "non-MVCC snapshots are not supported with hnsw");
|
{
|
||||||
|
value = scan->orderByData->sk_argument;
|
||||||
|
|
||||||
/* Get scan value */
|
/* Value should not be compressed or toasted */
|
||||||
value = GetScanValue(scan);
|
Assert(!VARATT_IS_COMPRESSED(DatumGetPointer(value)));
|
||||||
|
Assert(!VARATT_IS_EXTENDED(DatumGetPointer(value)));
|
||||||
|
|
||||||
|
/* Fine if normalization fails */
|
||||||
|
if (so->normprocinfo != NULL)
|
||||||
|
HnswNormValue(so->normprocinfo, so->collation, &value, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
* Get a shared lock. This allows vacuum to ensure no in-flight scans
|
||||||
@@ -185,25 +162,41 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
while (list_length(so->w) > 0)
|
while (list_length(so->w) > 0)
|
||||||
{
|
{
|
||||||
HnswCandidate *hc = llast(so->w);
|
HnswCandidate *hc = llast(so->w);
|
||||||
ItemPointer heaptid;
|
ItemPointer tid;
|
||||||
|
BlockNumber indexblkno;
|
||||||
|
|
||||||
/* Move to next element if no valid heap TIDs */
|
/* Move to next element if no valid heap tids */
|
||||||
if (hc->element->heaptidsLength == 0)
|
if (list_length(hc->element->heaptids) == 0)
|
||||||
{
|
{
|
||||||
so->w = list_delete_last(so->w);
|
so->w = list_delete_last(so->w);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
heaptid = &hc->element->heaptids[--hc->element->heaptidsLength];
|
tid = llast(hc->element->heaptids);
|
||||||
|
indexblkno = hc->element->blkno;
|
||||||
|
|
||||||
|
hc->element->heaptids = list_delete_last(hc->element->heaptids);
|
||||||
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan->xs_heaptid = *heaptid;
|
scan->xs_heaptid = *tid;
|
||||||
#else
|
#else
|
||||||
scan->xs_ctup.t_self = *heaptid;
|
scan->xs_ctup.t_self = *tid;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/* Unpin buffer */
|
||||||
|
if (BufferIsValid(so->buf))
|
||||||
|
ReleaseBuffer(so->buf);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* An index scan must maintain a pin on the index page holding the
|
||||||
|
* item last returned by amgettuple
|
||||||
|
*
|
||||||
|
* https://www.postgresql.org/docs/current/index-locking.html
|
||||||
|
*/
|
||||||
|
so->buf = ReadBuffer(scan->indexRelation, indexblkno);
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -220,6 +213,10 @@ hnswendscan(IndexScanDesc scan)
|
|||||||
{
|
{
|
||||||
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
|
||||||
|
|
||||||
|
/* Release pin */
|
||||||
|
if (BufferIsValid(so->buf))
|
||||||
|
ReleaseBuffer(so->buf);
|
||||||
|
|
||||||
MemoryContextDelete(so->tmpCtx);
|
MemoryContextDelete(so->tmpCtx);
|
||||||
|
|
||||||
pfree(so);
|
pfree(so);
|
||||||
|
|||||||
455
src/hnswutils.c
455
src/hnswutils.c
@@ -4,92 +4,8 @@
|
|||||||
|
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "utils/datum.h"
|
|
||||||
#include "vector.h"
|
#include "vector.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
#include "common/hashfn.h"
|
|
||||||
#else
|
|
||||||
#include "utils/hashutils.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 170000
|
|
||||||
static inline uint64
|
|
||||||
murmurhash64(uint64 data)
|
|
||||||
{
|
|
||||||
uint64 h = data;
|
|
||||||
|
|
||||||
h ^= h >> 33;
|
|
||||||
h *= 0xff51afd7ed558ccd;
|
|
||||||
h ^= h >> 33;
|
|
||||||
h *= 0xc4ceb9fe1a85ec53;
|
|
||||||
h ^= h >> 33;
|
|
||||||
|
|
||||||
return h;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* TID hash table */
|
|
||||||
static uint32
|
|
||||||
hash_tid(ItemPointerData tid)
|
|
||||||
{
|
|
||||||
union
|
|
||||||
{
|
|
||||||
uint64 i;
|
|
||||||
ItemPointerData tid;
|
|
||||||
} x;
|
|
||||||
|
|
||||||
/* Initialize unused bytes */
|
|
||||||
x.i = 0;
|
|
||||||
x.tid = tid;
|
|
||||||
|
|
||||||
return murmurhash64(x.i);
|
|
||||||
}
|
|
||||||
|
|
||||||
#define SH_PREFIX tidhash
|
|
||||||
#define SH_ELEMENT_TYPE TidHashEntry
|
|
||||||
#define SH_KEY_TYPE ItemPointerData
|
|
||||||
#define SH_KEY tid
|
|
||||||
#define SH_HASH_KEY(tb, key) hash_tid(key)
|
|
||||||
#define SH_EQUAL(tb, a, b) ItemPointerEquals(&a, &b)
|
|
||||||
#define SH_SCOPE extern
|
|
||||||
#define SH_DEFINE
|
|
||||||
#include "lib/simplehash.h"
|
|
||||||
|
|
||||||
/* Needed to include simplehash.h twice */
|
|
||||||
#if PG_VERSION_NUM < 120000
|
|
||||||
#undef SH_EQUAL
|
|
||||||
#define sh_log2 pointerhash_sh_log2
|
|
||||||
#define sh_pow2 pointerhash_sh_pow2
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Pointer hash table */
|
|
||||||
static uint32
|
|
||||||
hash_pointer(uintptr_t ptr)
|
|
||||||
{
|
|
||||||
#if SIZEOF_VOID_P == 8
|
|
||||||
return murmurhash64((uint64) ptr);
|
|
||||||
#else
|
|
||||||
return murmurhash32((uint32) ptr);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#define SH_PREFIX pointerhash
|
|
||||||
#define SH_ELEMENT_TYPE PointerHashEntry
|
|
||||||
#define SH_KEY_TYPE uintptr_t
|
|
||||||
#define SH_KEY ptr
|
|
||||||
#define SH_HASH_KEY(tb, key) hash_pointer(key)
|
|
||||||
#define SH_EQUAL(tb, a, b) (a == b)
|
|
||||||
#define SH_SCOPE extern
|
|
||||||
#define SH_DEFINE
|
|
||||||
#include "lib/simplehash.h"
|
|
||||||
|
|
||||||
typedef union
|
|
||||||
{
|
|
||||||
pointerhash_hash *pointers;
|
|
||||||
tidhash_hash *tids;
|
|
||||||
} visited_hash;
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the max number of connections in an upper layer for each element in the index
|
* Get the max number of connections in an upper layer for each element in the index
|
||||||
*/
|
*/
|
||||||
@@ -122,12 +38,12 @@ HnswGetEfConstruction(Relation index)
|
|||||||
* Get proc
|
* Get proc
|
||||||
*/
|
*/
|
||||||
FmgrInfo *
|
FmgrInfo *
|
||||||
HnswOptionalProcInfo(Relation index, uint16 procnum)
|
HnswOptionalProcInfo(Relation rel, uint16 procnum)
|
||||||
{
|
{
|
||||||
if (!OidIsValid(index_getprocid(index, 1, procnum)))
|
if (!OidIsValid(index_getprocid(rel, 1, procnum)))
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
return index_getprocinfo(index, 1, procnum);
|
return index_getprocinfo(rel, 1, procnum);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -184,6 +100,28 @@ HnswInitPage(Buffer buf, Page page)
|
|||||||
HnswPageGetOpaque(page)->page_id = HNSW_PAGE_ID;
|
HnswPageGetOpaque(page)->page_id = HNSW_PAGE_ID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Init and register page
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
HnswInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state)
|
||||||
|
{
|
||||||
|
*state = GenericXLogStart(index);
|
||||||
|
*page = GenericXLogRegisterBuffer(*state, *buf, GENERIC_XLOG_FULL_IMAGE);
|
||||||
|
HnswInitPage(*buf, *page);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Commit buffer
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
HnswCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||||
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
|
GenericXLogFinish(state);
|
||||||
|
UnlockReleaseBuffer(buf);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Allocate neighbors
|
* Allocate neighbors
|
||||||
*/
|
*/
|
||||||
@@ -202,7 +140,6 @@ HnswInitNeighbors(HnswElement element, int m)
|
|||||||
a = &element->neighbors[lc];
|
a = &element->neighbors[lc];
|
||||||
a->length = 0;
|
a->length = 0;
|
||||||
a->items = palloc(sizeof(HnswCandidate) * lm);
|
a->items = palloc(sizeof(HnswCandidate) * lm);
|
||||||
a->closerSet = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,7 +157,7 @@ HnswInitElement(ItemPointer heaptid, int m, double ml, int maxLevel)
|
|||||||
if (level > maxLevel)
|
if (level > maxLevel)
|
||||||
level = maxLevel;
|
level = maxLevel;
|
||||||
|
|
||||||
element->heaptidsLength = 0;
|
element->heaptids = NIL;
|
||||||
HnswAddHeapTid(element, heaptid);
|
HnswAddHeapTid(element, heaptid);
|
||||||
|
|
||||||
element->level = level;
|
element->level = level;
|
||||||
@@ -228,18 +165,33 @@ HnswInitElement(ItemPointer heaptid, int m, double ml, int maxLevel)
|
|||||||
|
|
||||||
HnswInitNeighbors(element, m);
|
HnswInitNeighbors(element, m);
|
||||||
|
|
||||||
element->value = PointerGetDatum(NULL);
|
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Free an element
|
||||||
|
*/
|
||||||
|
void
|
||||||
|
HnswFreeElement(HnswElement element)
|
||||||
|
{
|
||||||
|
list_free_deep(element->heaptids);
|
||||||
|
for (int lc = 0; lc <= element->level; lc++)
|
||||||
|
pfree(element->neighbors[lc].items);
|
||||||
|
pfree(element->neighbors);
|
||||||
|
pfree(element->vec);
|
||||||
|
pfree(element);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add a heap TID to an element
|
* Add a heap TID to an element
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswAddHeapTid(HnswElement element, ItemPointer heaptid)
|
HnswAddHeapTid(HnswElement element, ItemPointer heaptid)
|
||||||
{
|
{
|
||||||
element->heaptids[element->heaptidsLength++] = *heaptid;
|
ItemPointer copy = palloc(sizeof(ItemPointerData));
|
||||||
|
|
||||||
|
ItemPointerCopy(heaptid, copy);
|
||||||
|
element->heaptids = lappend(element->heaptids, copy);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -253,48 +205,30 @@ HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno)
|
|||||||
element->blkno = blkno;
|
element->blkno = blkno;
|
||||||
element->offno = offno;
|
element->offno = offno;
|
||||||
element->neighbors = NULL;
|
element->neighbors = NULL;
|
||||||
element->value = PointerGetDatum(NULL);
|
element->vec = NULL;
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the metapage info
|
|
||||||
*/
|
|
||||||
void
|
|
||||||
HnswGetMetaPageInfo(Relation index, int *m, HnswElement * entryPoint)
|
|
||||||
{
|
|
||||||
Buffer buf;
|
|
||||||
Page page;
|
|
||||||
HnswMetaPage metap;
|
|
||||||
|
|
||||||
buf = ReadBuffer(index, HNSW_METAPAGE_BLKNO);
|
|
||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
metap = HnswPageGetMeta(page);
|
|
||||||
|
|
||||||
if (m != NULL)
|
|
||||||
*m = metap->m;
|
|
||||||
|
|
||||||
if (entryPoint != NULL)
|
|
||||||
{
|
|
||||||
if (BlockNumberIsValid(metap->entryBlkno))
|
|
||||||
*entryPoint = HnswInitElementFromBlock(metap->entryBlkno, metap->entryOffno);
|
|
||||||
else
|
|
||||||
*entryPoint = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the entry point
|
* Get the entry point
|
||||||
*/
|
*/
|
||||||
HnswElement
|
HnswElement
|
||||||
HnswGetEntryPoint(Relation index)
|
HnswGetEntryPoint(Relation index)
|
||||||
{
|
{
|
||||||
HnswElement entryPoint;
|
Buffer buf;
|
||||||
|
Page page;
|
||||||
|
HnswMetaPage metap;
|
||||||
|
HnswElement entryPoint = NULL;
|
||||||
|
|
||||||
HnswGetMetaPageInfo(index, NULL, &entryPoint);
|
buf = ReadBuffer(index, HNSW_METAPAGE_BLKNO);
|
||||||
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
|
page = BufferGetPage(buf);
|
||||||
|
metap = HnswPageGetMeta(page);
|
||||||
|
|
||||||
|
if (BlockNumberIsValid(metap->entryBlkno))
|
||||||
|
entryPoint = HnswInitElementFromBlock(metap->entryBlkno, metap->entryOffno);
|
||||||
|
|
||||||
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
return entryPoint;
|
return entryPoint;
|
||||||
}
|
}
|
||||||
@@ -331,7 +265,7 @@ HnswUpdateMetaPageInfo(Page page, int updateEntry, HnswElement entryPoint, Block
|
|||||||
* Update the metapage
|
* Update the metapage
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum, bool building)
|
HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, BlockNumber insertPage, ForkNumber forkNum)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -339,24 +273,12 @@ HnswUpdateMetaPage(Relation index, int updateEntry, HnswElement entryPoint, Bloc
|
|||||||
|
|
||||||
buf = ReadBufferExtended(index, forkNum, HNSW_METAPAGE_BLKNO, RBM_NORMAL, NULL);
|
buf = ReadBufferExtended(index, forkNum, HNSW_METAPAGE_BLKNO, RBM_NORMAL, NULL);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
if (building)
|
state = GenericXLogStart(index);
|
||||||
{
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
state = NULL;
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
state = GenericXLogStart(index);
|
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
HnswUpdateMetaPageInfo(page, updateEntry, entryPoint, insertPage);
|
HnswUpdateMetaPageInfo(page, updateEntry, entryPoint, insertPage);
|
||||||
|
|
||||||
if (building)
|
HnswCommitBuffer(buf, state);
|
||||||
MarkBufferDirty(buf);
|
|
||||||
else
|
|
||||||
GenericXLogFinish(state);
|
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -370,12 +292,12 @@ HnswSetElementTuple(HnswElementTuple etup, HnswElement element)
|
|||||||
etup->deleted = 0;
|
etup->deleted = 0;
|
||||||
for (int i = 0; i < HNSW_HEAPTIDS; i++)
|
for (int i = 0; i < HNSW_HEAPTIDS; i++)
|
||||||
{
|
{
|
||||||
if (i < element->heaptidsLength)
|
if (i < list_length(element->heaptids))
|
||||||
etup->heaptids[i] = element->heaptids[i];
|
etup->heaptids[i] = *((ItemPointer) list_nth(element->heaptids, i));
|
||||||
else
|
else
|
||||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||||
}
|
}
|
||||||
memcpy(&etup->data, DatumGetPointer(element->value), VARSIZE_ANY(DatumGetPointer(element->value)));
|
memcpy(&etup->vec, element->vec, VECTOR_SIZE(element->vec->dim));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -390,7 +312,7 @@ HnswSetNeighborTuple(HnswNeighborTuple ntup, HnswElement e, int m)
|
|||||||
|
|
||||||
for (int lc = e->level; lc >= 0; lc--)
|
for (int lc = e->level; lc >= 0; lc--)
|
||||||
{
|
{
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(e, lc);
|
HnswNeighborArray *neighbors = &e->neighbors[lc];
|
||||||
int lm = HnswGetLayerM(m, lc);
|
int lm = HnswGetLayerM(m, lc);
|
||||||
|
|
||||||
for (int i = 0; i < lm; i++)
|
for (int i = 0; i < lm; i++)
|
||||||
@@ -415,9 +337,10 @@ HnswSetNeighborTuple(HnswNeighborTuple ntup, HnswElement e, int m)
|
|||||||
* Load neighbors from page
|
* Load neighbors from page
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
LoadNeighborsFromPage(HnswElement element, Relation index, Page page, int m)
|
LoadNeighborsFromPage(HnswElement element, Relation index, Page page)
|
||||||
{
|
{
|
||||||
HnswNeighborTuple ntup = (HnswNeighborTuple) PageGetItem(page, PageGetItemId(page, element->neighborOffno));
|
HnswNeighborTuple ntup = (HnswNeighborTuple) PageGetItem(page, PageGetItemId(page, element->neighborOffno));
|
||||||
|
int m = HnswGetM(index);
|
||||||
int neighborCount = (element->level + 2) * m;
|
int neighborCount = (element->level + 2) * m;
|
||||||
|
|
||||||
Assert(HnswIsNeighborTuple(ntup));
|
Assert(HnswIsNeighborTuple(ntup));
|
||||||
@@ -448,7 +371,7 @@ LoadNeighborsFromPage(HnswElement element, Relation index, Page page, int m)
|
|||||||
if (level < 0)
|
if (level < 0)
|
||||||
level = 0;
|
level = 0;
|
||||||
|
|
||||||
neighbors = HnswGetNeighbors(element, level);
|
neighbors = &element->neighbors[level];
|
||||||
hc = &neighbors->items[neighbors->length++];
|
hc = &neighbors->items[neighbors->length++];
|
||||||
hc->element = e;
|
hc->element = e;
|
||||||
}
|
}
|
||||||
@@ -458,7 +381,7 @@ LoadNeighborsFromPage(HnswElement element, Relation index, Page page, int m)
|
|||||||
* Load neighbors
|
* Load neighbors
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswLoadNeighbors(HnswElement element, Relation index, int m)
|
HnswLoadNeighbors(HnswElement element, Relation index)
|
||||||
{
|
{
|
||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
@@ -467,7 +390,7 @@ HnswLoadNeighbors(HnswElement element, Relation index, int m)
|
|||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
page = BufferGetPage(buf);
|
page = BufferGetPage(buf);
|
||||||
|
|
||||||
LoadNeighborsFromPage(element, index, page, m);
|
LoadNeighborsFromPage(element, index, page);
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -482,7 +405,7 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
|||||||
element->deleted = etup->deleted;
|
element->deleted = etup->deleted;
|
||||||
element->neighborPage = ItemPointerGetBlockNumber(&etup->neighbortid);
|
element->neighborPage = ItemPointerGetBlockNumber(&etup->neighbortid);
|
||||||
element->neighborOffno = ItemPointerGetOffsetNumber(&etup->neighbortid);
|
element->neighborOffno = ItemPointerGetOffsetNumber(&etup->neighbortid);
|
||||||
element->heaptidsLength = 0;
|
element->heaptids = NIL;
|
||||||
|
|
||||||
if (loadHeaptids)
|
if (loadHeaptids)
|
||||||
{
|
{
|
||||||
@@ -497,7 +420,10 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (loadVec)
|
if (loadVec)
|
||||||
element->value = datumCopy(PointerGetDatum(&etup->data), false, -1);
|
{
|
||||||
|
element->vec = palloc(VECTOR_SIZE(etup->vec.dim));
|
||||||
|
memcpy(element->vec, &etup->vec, VECTOR_SIZE(etup->vec.dim));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -524,7 +450,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
|||||||
|
|
||||||
/* Calculate distance */
|
/* Calculate distance */
|
||||||
if (distance != NULL)
|
if (distance != NULL)
|
||||||
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->data)));
|
*distance = (float) DatumGetFloat8(FunctionCall2Coll(procinfo, collation, *q, PointerGetDatum(&etup->vec)));
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -535,7 +461,7 @@ HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation index,
|
|||||||
static float
|
static float
|
||||||
GetCandidateDistance(HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
GetCandidateDistance(HnswCandidate * hc, Datum q, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, hc->element->value));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, q, PointerGetDatum(hc->element->vec)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -600,22 +526,16 @@ CreatePairingHeapNode(HnswCandidate * c)
|
|||||||
* Add to visited
|
* Add to visited
|
||||||
*/
|
*/
|
||||||
static inline void
|
static inline void
|
||||||
AddToVisited(visited_hash v, HnswCandidate * hc, Relation index, bool *found)
|
AddToVisited(HTAB *v, HnswCandidate * hc, Relation index, bool *found)
|
||||||
{
|
{
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
{
|
hash_search(v, &hc->element, HASH_ENTER, found);
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
pointerhash_insert_hash(v.pointers, (uintptr_t) hc->element, hc->element->hash, found);
|
|
||||||
#else
|
|
||||||
pointerhash_insert(v.pointers, (uintptr_t) hc->element, found);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
ItemPointerData indextid;
|
ItemPointerData indextid;
|
||||||
|
|
||||||
ItemPointerSet(&indextid, hc->element->blkno, hc->element->offno);
|
ItemPointerSet(&indextid, hc->element->blkno, hc->element->offno);
|
||||||
tidhash_insert(v.tids, indextid, found);
|
hash_search(v, &indextid, HASH_ENTER, found);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -623,28 +543,38 @@ AddToVisited(visited_hash v, HnswCandidate * hc, Relation index, bool *found)
|
|||||||
* Algorithm 2 from paper
|
* Algorithm 2 from paper
|
||||||
*/
|
*/
|
||||||
List *
|
List *
|
||||||
HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, int m, bool inserting, HnswElement skipElement)
|
HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *procinfo, Oid collation, bool inserting, HnswElement skipElement)
|
||||||
{
|
{
|
||||||
|
ListCell *lc2;
|
||||||
|
|
||||||
List *w = NIL;
|
List *w = NIL;
|
||||||
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
pairingheap *C = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||||
pairingheap *W = pairingheap_allocate(CompareFurthestCandidates, NULL);
|
pairingheap *W = pairingheap_allocate(CompareFurthestCandidates, NULL);
|
||||||
int wlen = 0;
|
int wlen = 0;
|
||||||
visited_hash v;
|
HASHCTL hash_ctl;
|
||||||
ListCell *lc2;
|
HTAB *v;
|
||||||
|
|
||||||
/* Create hash table */
|
/* Create hash table */
|
||||||
if (index == NULL)
|
if (index == NULL)
|
||||||
v.pointers = pointerhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
{
|
||||||
|
hash_ctl.keysize = sizeof(HnswElement *);
|
||||||
|
hash_ctl.entrysize = sizeof(HnswElement *);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
v.tids = tidhash_create(CurrentMemoryContext, ef * m * 2, NULL);
|
{
|
||||||
|
hash_ctl.keysize = sizeof(ItemPointerData);
|
||||||
|
hash_ctl.entrysize = sizeof(ItemPointerData);
|
||||||
|
}
|
||||||
|
|
||||||
|
hash_ctl.hcxt = CurrentMemoryContext;
|
||||||
|
v = hash_create("hnsw visited", 256, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
|
||||||
|
|
||||||
/* Add entry points to v, C, and W */
|
/* Add entry points to v, C, and W */
|
||||||
foreach(lc2, ep)
|
foreach(lc2, ep)
|
||||||
{
|
{
|
||||||
HnswCandidate *hc = (HnswCandidate *) lfirst(lc2);
|
HnswCandidate *hc = (HnswCandidate *) lfirst(lc2);
|
||||||
bool found;
|
|
||||||
|
|
||||||
AddToVisited(v, hc, index, &found);
|
AddToVisited(v, hc, index, NULL);
|
||||||
|
|
||||||
pairingheap_add(C, &(CreatePairingHeapNode(hc)->ph_node));
|
pairingheap_add(C, &(CreatePairingHeapNode(hc)->ph_node));
|
||||||
pairingheap_add(W, &(CreatePairingHeapNode(hc)->ph_node));
|
pairingheap_add(W, &(CreatePairingHeapNode(hc)->ph_node));
|
||||||
@@ -654,7 +584,7 @@ HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *pro
|
|||||||
* would be ideal to do this for inserts as well, but this could
|
* would be ideal to do this for inserts as well, but this could
|
||||||
* affect insert performance.
|
* affect insert performance.
|
||||||
*/
|
*/
|
||||||
if (skipElement == NULL || hc->element->heaptidsLength != 0)
|
if (skipElement == NULL || list_length(hc->element->heaptids) != 0)
|
||||||
wlen++;
|
wlen++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -668,10 +598,10 @@ HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *pro
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
if (c->element->neighbors == NULL)
|
if (c->element->neighbors == NULL)
|
||||||
HnswLoadNeighbors(c->element, index, m);
|
HnswLoadNeighbors(c->element, index);
|
||||||
|
|
||||||
/* Get the neighborhood at layer lc */
|
/* Get the neighborhood at layer lc */
|
||||||
neighborhood = HnswGetNeighbors(c->element, lc);
|
neighborhood = &c->element->neighbors[lc];
|
||||||
|
|
||||||
for (int i = 0; i < neighborhood->length; i++)
|
for (int i = 0; i < neighborhood->length; i++)
|
||||||
{
|
{
|
||||||
@@ -713,7 +643,7 @@ HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *pro
|
|||||||
* vacuuming. It would be ideal to do this for inserts as
|
* vacuuming. It would be ideal to do this for inserts as
|
||||||
* well, but this could affect insert performance.
|
* well, but this could affect insert performance.
|
||||||
*/
|
*/
|
||||||
if (skipElement == NULL || e->element->heaptidsLength != 0)
|
if (skipElement == NULL || list_length(e->element->heaptids) != 0)
|
||||||
{
|
{
|
||||||
wlen++;
|
wlen++;
|
||||||
|
|
||||||
@@ -737,34 +667,6 @@ HnswSearchLayer(Datum q, List *ep, int ef, int lc, Relation index, FmgrInfo *pro
|
|||||||
return w;
|
return w;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Compare candidate distances
|
|
||||||
*/
|
|
||||||
static int
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
|
||||||
#else
|
|
||||||
CompareCandidateDistances(const void *a, const void *b)
|
|
||||||
#endif
|
|
||||||
{
|
|
||||||
HnswCandidate *hca = lfirst((ListCell *) a);
|
|
||||||
HnswCandidate *hcb = lfirst((ListCell *) b);
|
|
||||||
|
|
||||||
if (hca->distance < hcb->distance)
|
|
||||||
return 1;
|
|
||||||
|
|
||||||
if (hca->distance > hcb->distance)
|
|
||||||
return -1;
|
|
||||||
|
|
||||||
if (hca->element < hcb->element)
|
|
||||||
return 1;
|
|
||||||
|
|
||||||
if (hca->element > hcb->element)
|
|
||||||
return -1;
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Calculate the distance between elements
|
* Calculate the distance between elements
|
||||||
*/
|
*/
|
||||||
@@ -774,27 +676,27 @@ HnswGetDistance(HnswElement a, HnswElement b, int lc, FmgrInfo *procinfo, Oid co
|
|||||||
/* Look for cached distance */
|
/* Look for cached distance */
|
||||||
if (a->neighbors != NULL)
|
if (a->neighbors != NULL)
|
||||||
{
|
{
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(a, lc);
|
Assert(a->level >= lc);
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
for (int i = 0; i < a->neighbors[lc].length; i++)
|
||||||
{
|
{
|
||||||
if (neighbors->items[i].element == b)
|
if (a->neighbors[lc].items[i].element == b)
|
||||||
return neighbors->items[i].distance;
|
return a->neighbors[lc].items[i].distance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (b->neighbors != NULL)
|
if (b->neighbors != NULL)
|
||||||
{
|
{
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(b, lc);
|
Assert(b->level >= lc);
|
||||||
|
|
||||||
for (int i = 0; i < neighbors->length; i++)
|
for (int i = 0; i < b->neighbors[lc].length; i++)
|
||||||
{
|
{
|
||||||
if (neighbors->items[i].element == a)
|
if (b->neighbors[lc].items[i].element == a)
|
||||||
return neighbors->items[i].distance;
|
return b->neighbors[lc].items[i].distance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, a->value, b->value));
|
return DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(a->vec), PointerGetDatum(b->vec)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -821,78 +723,33 @@ CheckElementCloser(HnswCandidate * e, List *r, int lc, FmgrInfo *procinfo, Oid c
|
|||||||
* Algorithm 4 from paper
|
* Algorithm 4 from paper
|
||||||
*/
|
*/
|
||||||
static List *
|
static List *
|
||||||
SelectNeighbors(List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswElement e2, HnswCandidate * newCandidate, HnswCandidate * *pruned, bool sortCandidates)
|
SelectNeighbors(List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswCandidate * *pruned)
|
||||||
{
|
{
|
||||||
List *r = NIL;
|
List *r = NIL;
|
||||||
List *w = list_copy(c);
|
List *w = list_copy(c);
|
||||||
pairingheap *wd;
|
pairingheap *wd;
|
||||||
HnswNeighborArray *neighbors = HnswGetNeighbors(e2, lc);
|
|
||||||
bool mustCalculate = !neighbors->closerSet;
|
|
||||||
List *added = NIL;
|
|
||||||
bool removedAny = false;
|
|
||||||
|
|
||||||
if (list_length(w) <= m)
|
if (list_length(w) <= m)
|
||||||
return w;
|
return w;
|
||||||
|
|
||||||
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
wd = pairingheap_allocate(CompareNearestCandidates, NULL);
|
||||||
|
|
||||||
/* Ensure order of candidates is deterministic for closer caching */
|
|
||||||
if (sortCandidates)
|
|
||||||
list_sort(w, CompareCandidateDistances);
|
|
||||||
|
|
||||||
while (list_length(w) > 0 && list_length(r) < m)
|
while (list_length(w) > 0 && list_length(r) < m)
|
||||||
{
|
{
|
||||||
/* Assumes w is already ordered desc */
|
/* Assumes w is already ordered desc */
|
||||||
HnswCandidate *e = llast(w);
|
HnswCandidate *e = llast(w);
|
||||||
|
bool closer;
|
||||||
|
|
||||||
w = list_delete_last(w);
|
w = list_delete_last(w);
|
||||||
|
|
||||||
/* Use previous state of r and wd to skip work when possible */
|
closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
||||||
if (mustCalculate)
|
|
||||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
|
||||||
else if (list_length(added) > 0)
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
* If the current candidate was closer, we only need to compare it
|
|
||||||
* with the other candidates that we have added.
|
|
||||||
*/
|
|
||||||
if (e->closer)
|
|
||||||
{
|
|
||||||
e->closer = CheckElementCloser(e, added, lc, procinfo, collation);
|
|
||||||
|
|
||||||
if (!e->closer)
|
if (closer)
|
||||||
removedAny = true;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
/*
|
|
||||||
* If we have removed any candidates from closer, a candidate
|
|
||||||
* that was not closer earlier might now be.
|
|
||||||
*/
|
|
||||||
if (removedAny)
|
|
||||||
{
|
|
||||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
|
||||||
if (e->closer)
|
|
||||||
added = lappend(added, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (e == newCandidate)
|
|
||||||
{
|
|
||||||
e->closer = CheckElementCloser(e, r, lc, procinfo, collation);
|
|
||||||
if (e->closer)
|
|
||||||
added = lappend(added, e);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e->closer)
|
|
||||||
r = lappend(r, e);
|
r = lappend(r, e);
|
||||||
else
|
else
|
||||||
pairingheap_add(wd, &(CreatePairingHeapNode(e)->ph_node));
|
pairingheap_add(wd, &(CreatePairingHeapNode(e)->ph_node));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Cached value can only be used in future if sorted deterministically */
|
|
||||||
neighbors->closerSet = sortCandidates;
|
|
||||||
|
|
||||||
/* Keep pruned connections */
|
/* Keep pruned connections */
|
||||||
while (!pairingheap_is_empty(wd) && list_length(r) < m)
|
while (!pairingheap_is_empty(wd) && list_length(r) < m)
|
||||||
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
r = lappend(r, ((HnswPairingHeapNode *) pairingheap_remove_first(wd))->inner);
|
||||||
@@ -909,6 +766,30 @@ SelectNeighbors(List *c, int m, int lc, FmgrInfo *procinfo, Oid collation, HnswE
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Find duplicate element
|
||||||
|
*/
|
||||||
|
HnswElement
|
||||||
|
HnswFindDuplicate(HnswElement e)
|
||||||
|
{
|
||||||
|
HnswNeighborArray *neighbors = &e->neighbors[0];
|
||||||
|
|
||||||
|
for (int i = 0; i < neighbors->length; i++)
|
||||||
|
{
|
||||||
|
HnswCandidate *neighbor = &neighbors->items[i];
|
||||||
|
|
||||||
|
/* Exit early since ordered by distance */
|
||||||
|
if (vector_cmp_internal(e->vec, neighbor->element->vec) != 0)
|
||||||
|
break;
|
||||||
|
|
||||||
|
/* Check for space */
|
||||||
|
if (list_length(neighbor->element->heaptids) < HNSW_HEAPTIDS)
|
||||||
|
return neighbor->element;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add connections
|
* Add connections
|
||||||
*/
|
*/
|
||||||
@@ -916,19 +797,41 @@ static void
|
|||||||
AddConnections(HnswElement element, List *neighbors, int m, int lc)
|
AddConnections(HnswElement element, List *neighbors, int m, int lc)
|
||||||
{
|
{
|
||||||
ListCell *lc2;
|
ListCell *lc2;
|
||||||
HnswNeighborArray *a = HnswGetNeighbors(element, lc);
|
HnswNeighborArray *a = &element->neighbors[lc];
|
||||||
|
|
||||||
foreach(lc2, neighbors)
|
foreach(lc2, neighbors)
|
||||||
a->items[a->length++] = *((HnswCandidate *) lfirst(lc2));
|
a->items[a->length++] = *((HnswCandidate *) lfirst(lc2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Compare candidate distances
|
||||||
|
*/
|
||||||
|
static int
|
||||||
|
#if PG_VERSION_NUM >= 130000
|
||||||
|
CompareCandidateDistances(const ListCell *a, const ListCell *b)
|
||||||
|
#else
|
||||||
|
CompareCandidateDistances(const void *a, const void *b)
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
HnswCandidate *hca = lfirst((ListCell *) a);
|
||||||
|
HnswCandidate *hcb = lfirst((ListCell *) b);
|
||||||
|
|
||||||
|
if (hca->distance < hcb->distance)
|
||||||
|
return 1;
|
||||||
|
|
||||||
|
if (hca->distance > hcb->distance)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Update connections
|
* Update connections
|
||||||
*/
|
*/
|
||||||
void
|
void
|
||||||
HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation)
|
HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int *updateIdx, Relation index, FmgrInfo *procinfo, Oid collation)
|
||||||
{
|
{
|
||||||
HnswNeighborArray *currentNeighbors = HnswGetNeighbors(hc->element, lc);
|
HnswNeighborArray *currentNeighbors = &hc->element->neighbors[lc];
|
||||||
|
|
||||||
HnswCandidate hc2;
|
HnswCandidate hc2;
|
||||||
|
|
||||||
@@ -951,19 +854,19 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
|||||||
/* Load elements on insert */
|
/* Load elements on insert */
|
||||||
if (index != NULL)
|
if (index != NULL)
|
||||||
{
|
{
|
||||||
Datum q = hc->element->value;
|
Datum q = PointerGetDatum(hc->element->vec);
|
||||||
|
|
||||||
for (int i = 0; i < currentNeighbors->length; i++)
|
for (int i = 0; i < currentNeighbors->length; i++)
|
||||||
{
|
{
|
||||||
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
||||||
|
|
||||||
if (DatumGetPointer(hc3->element->value) == NULL)
|
if (hc3->element->vec == NULL)
|
||||||
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
||||||
else
|
else
|
||||||
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
||||||
|
|
||||||
/* Prune element if being deleted */
|
/* Prune element if being deleted */
|
||||||
if (hc3->element->heaptidsLength == 0)
|
if (list_length(hc3->element->heaptids) == 0)
|
||||||
{
|
{
|
||||||
pruned = ¤tNeighbors->items[i];
|
pruned = ¤tNeighbors->items[i];
|
||||||
break;
|
break;
|
||||||
@@ -975,12 +878,13 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
|||||||
{
|
{
|
||||||
List *c = NIL;
|
List *c = NIL;
|
||||||
|
|
||||||
/* Add candidates */
|
/* Add and sort candidates */
|
||||||
for (int i = 0; i < currentNeighbors->length; i++)
|
for (int i = 0; i < currentNeighbors->length; i++)
|
||||||
c = lappend(c, ¤tNeighbors->items[i]);
|
c = lappend(c, ¤tNeighbors->items[i]);
|
||||||
c = lappend(c, &hc2);
|
c = lappend(c, &hc2);
|
||||||
|
list_sort(c, CompareCandidateDistances);
|
||||||
|
|
||||||
SelectNeighbors(c, m, lc, procinfo, collation, hc->element, &hc2, &pruned, true);
|
SelectNeighbors(c, m, lc, procinfo, collation, &pruned);
|
||||||
|
|
||||||
/* Should not happen */
|
/* Should not happen */
|
||||||
if (pruned == NULL)
|
if (pruned == NULL)
|
||||||
@@ -1021,7 +925,7 @@ RemoveElements(List *w, HnswElement skipElement)
|
|||||||
if (skipElement != NULL && hc->element->blkno == skipElement->blkno && hc->element->offno == skipElement->offno)
|
if (skipElement != NULL && hc->element->blkno == skipElement->blkno && hc->element->offno == skipElement->offno)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (hc->element->heaptidsLength != 0)
|
if (list_length(hc->element->heaptids) != 0)
|
||||||
w2 = lappend(w2, hc);
|
w2 = lappend(w2, hc);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1038,15 +942,9 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
|||||||
List *w;
|
List *w;
|
||||||
int level = element->level;
|
int level = element->level;
|
||||||
int entryLevel;
|
int entryLevel;
|
||||||
Datum q = element->value;
|
Datum q = PointerGetDatum(element->vec);
|
||||||
HnswElement skipElement = existing ? element : NULL;
|
HnswElement skipElement = existing ? element : NULL;
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
/* Precompute hash */
|
|
||||||
if (index == NULL)
|
|
||||||
element->hash = hash_pointer((uintptr_t) element);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* No neighbors if no entry point */
|
/* No neighbors if no entry point */
|
||||||
if (entryPoint == NULL)
|
if (entryPoint == NULL)
|
||||||
return;
|
return;
|
||||||
@@ -1058,7 +956,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
|||||||
/* 1st phase: greedy search to insert level */
|
/* 1st phase: greedy search to insert level */
|
||||||
for (int lc = entryLevel; lc >= level + 1; lc--)
|
for (int lc = entryLevel; lc >= level + 1; lc--)
|
||||||
{
|
{
|
||||||
w = HnswSearchLayer(q, ep, 1, lc, index, procinfo, collation, m, true, skipElement);
|
w = HnswSearchLayer(q, ep, 1, lc, index, procinfo, collation, true, skipElement);
|
||||||
ep = w;
|
ep = w;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1076,7 +974,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
|||||||
List *neighbors;
|
List *neighbors;
|
||||||
List *lw;
|
List *lw;
|
||||||
|
|
||||||
w = HnswSearchLayer(q, ep, efConstruction, lc, index, procinfo, collation, m, true, skipElement);
|
w = HnswSearchLayer(q, ep, efConstruction, lc, index, procinfo, collation, true, skipElement);
|
||||||
|
|
||||||
/* Elements being deleted or skipped can help with search */
|
/* Elements being deleted or skipped can help with search */
|
||||||
/* but should be removed before selecting neighbors */
|
/* but should be removed before selecting neighbors */
|
||||||
@@ -1085,12 +983,7 @@ HnswInsertElement(HnswElement element, HnswElement entryPoint, Relation index, F
|
|||||||
else
|
else
|
||||||
lw = w;
|
lw = w;
|
||||||
|
|
||||||
/*
|
neighbors = SelectNeighbors(lw, lm, lc, procinfo, collation, NULL);
|
||||||
* Candidates are sorted, but not deterministically. Could set
|
|
||||||
* sortCandidates to true for in-memory builds to enable closer
|
|
||||||
* caching, but there does not seem to be a difference in performance.
|
|
||||||
*/
|
|
||||||
neighbors = SelectNeighbors(lw, lm, lc, procinfo, collation, element, NULL, NULL, false);
|
|
||||||
|
|
||||||
AddConnections(element, neighbors, lm, lc);
|
AddConnections(element, neighbors, lm, lc);
|
||||||
|
|
||||||
|
|||||||
@@ -12,9 +12,12 @@
|
|||||||
* Check if deleted list contains an index TID
|
* Check if deleted list contains an index TID
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
DeletedContains(tidhash_hash * deleted, ItemPointer indextid)
|
DeletedContains(HTAB *deleted, ItemPointer indextid)
|
||||||
{
|
{
|
||||||
return tidhash_lookup(deleted, *indextid) != NULL;
|
bool found;
|
||||||
|
|
||||||
|
hash_search(deleted, indextid, HASH_FIND, &found);
|
||||||
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -59,8 +62,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
/* Iterate over nodes */
|
/* Iterate over nodes */
|
||||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
ItemId itemid = PageGetItemId(page, offno);
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
|
||||||
int idx = 0;
|
int idx = 0;
|
||||||
bool itemUpdated = false;
|
bool itemUpdated = false;
|
||||||
|
|
||||||
@@ -91,7 +93,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
if (itemUpdated)
|
if (itemUpdated)
|
||||||
{
|
{
|
||||||
Size etupSize = ItemIdGetLength(itemid);
|
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
||||||
|
|
||||||
/* Mark rest as invalid */
|
/* Mark rest as invalid */
|
||||||
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
||||||
@@ -107,13 +109,11 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
if (!ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
{
|
{
|
||||||
ItemPointerData ip;
|
ItemPointerData ip;
|
||||||
bool found;
|
|
||||||
|
|
||||||
/* Add to deleted list */
|
/* Add to deleted list */
|
||||||
ItemPointerSet(&ip, blkno, offno);
|
ItemPointerSet(&ip, blkno, offno);
|
||||||
|
|
||||||
tidhash_insert(vacuumstate->deleted, ip, &found);
|
(void) hash_search(vacuumstate->deleted, &ip, HASH_ENTER, NULL);
|
||||||
Assert(!found);
|
|
||||||
}
|
}
|
||||||
else if (etup->level > highestLevel && !(entryPoint != NULL && blkno == entryPoint->blkno && offno == entryPoint->offno))
|
else if (etup->level > highestLevel && !(entryPoint != NULL && blkno == entryPoint->blkno && offno == entryPoint->offno))
|
||||||
{
|
{
|
||||||
@@ -128,7 +128,10 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
blkno = HnswPageGetOpaque(page)->nextblkno;
|
blkno = HnswPageGetOpaque(page)->nextblkno;
|
||||||
|
|
||||||
if (updated)
|
if (updated)
|
||||||
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
GenericXLogAbort(state);
|
GenericXLogAbort(state);
|
||||||
|
|
||||||
@@ -206,7 +209,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
|
|
||||||
/* Init fields */
|
/* Init fields */
|
||||||
HnswInitNeighbors(element, m);
|
HnswInitNeighbors(element, m);
|
||||||
element->heaptidsLength = 0;
|
element->heaptids = NIL;
|
||||||
|
|
||||||
/* Add element to graph, skipping itself */
|
/* Add element to graph, skipping itself */
|
||||||
HnswInsertElement(element, entryPoint, index, procinfo, collation, m, efConstruction, true);
|
HnswInsertElement(element, entryPoint, index, procinfo, collation, m, efConstruction, true);
|
||||||
@@ -226,11 +229,12 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
/* Update neighbors */
|
/* Update neighbors */
|
||||||
HnswUpdateNeighborPages(index, procinfo, collation, element, m, true, false);
|
HnswUpdateNeighborPages(index, procinfo, collation, element, m, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -286,7 +290,7 @@ RepairGraphEntryPoint(HnswVacuumState * vacuumstate)
|
|||||||
* point is outdated and empty, the entry point will be empty
|
* point is outdated and empty, the entry point will be empty
|
||||||
* until an element is repaired.
|
* until an element is repaired.
|
||||||
*/
|
*/
|
||||||
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_ALWAYS, highestPoint, InvalidBlockNumber, MAIN_FORKNUM, false);
|
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_ALWAYS, highestPoint, InvalidBlockNumber, MAIN_FORKNUM);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -326,10 +330,7 @@ RepairGraph(HnswVacuumState * vacuumstate)
|
|||||||
BufferAccessStrategy bas = vacuumstate->bas;
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
BlockNumber blkno = HNSW_HEAD_BLKNO;
|
BlockNumber blkno = HNSW_HEAD_BLKNO;
|
||||||
|
|
||||||
/*
|
/* Wait for inserts to complete */
|
||||||
* Wait for inserts to complete. Inserts before this point may have
|
|
||||||
* neighbors about to be deleted. Inserts after this point will not.
|
|
||||||
*/
|
|
||||||
LockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
LockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
UnlockPage(index, HNSW_UPDATE_LOCK, ExclusiveLock);
|
||||||
|
|
||||||
@@ -419,7 +420,7 @@ RepairGraph(HnswVacuumState * vacuumstate)
|
|||||||
* was replaced and highest point was outdated.
|
* was replaced and highest point was outdated.
|
||||||
*/
|
*/
|
||||||
if (entryPoint == NULL || element->level > entryPoint->level)
|
if (entryPoint == NULL || element->level > entryPoint->level)
|
||||||
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_GREATER, element, InvalidBlockNumber, MAIN_FORKNUM, false);
|
HnswUpdateMetaPage(index, HNSW_UPDATE_ENTRY_GREATER, element, InvalidBlockNumber, MAIN_FORKNUM);
|
||||||
|
|
||||||
/* Release lock */
|
/* Release lock */
|
||||||
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
UnlockPage(index, HNSW_UPDATE_LOCK, lockmode);
|
||||||
@@ -442,11 +443,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
Relation index = vacuumstate->index;
|
Relation index = vacuumstate->index;
|
||||||
BufferAccessStrategy bas = vacuumstate->bas;
|
BufferAccessStrategy bas = vacuumstate->bas;
|
||||||
|
|
||||||
/*
|
/* Wait for selects to complete */
|
||||||
* Wait for index scans to complete. Scans before this point may contain
|
|
||||||
* tuples about to be deleted. Scans after this point will not, since the
|
|
||||||
* graph has been repaired.
|
|
||||||
*/
|
|
||||||
LockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
LockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
||||||
UnlockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
UnlockPage(index, HNSW_SCAN_LOCK, ExclusiveLock);
|
||||||
|
|
||||||
@@ -477,8 +474,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
/* Update element and neighbors together */
|
/* Update element and neighbors together */
|
||||||
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
ItemId itemid = PageGetItemId(page, offno);
|
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||||
HnswElementTuple etup = (HnswElementTuple) PageGetItem(page, itemid);
|
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
Size etupSize;
|
Size etupSize;
|
||||||
Size ntupSize;
|
Size ntupSize;
|
||||||
@@ -506,7 +502,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = ItemIdGetLength(itemid);
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(etup->vec.dim);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
||||||
|
|
||||||
/* Get neighbor page */
|
/* Get neighbor page */
|
||||||
@@ -529,7 +525,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
/* Overwrite element */
|
/* Overwrite element */
|
||||||
etup->deleted = 1;
|
etup->deleted = 1;
|
||||||
MemSet(&etup->data, 0, VARSIZE_ANY(&etup->data));
|
MemSet(&etup->vec.x, 0, etup->vec.dim * sizeof(float));
|
||||||
|
|
||||||
/* Overwrite neighbors */
|
/* Overwrite neighbors */
|
||||||
for (int i = 0; i < ntup->count; i++)
|
for (int i = 0; i < ntup->count; i++)
|
||||||
@@ -544,6 +540,9 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(buf);
|
||||||
|
if (nbuf != buf)
|
||||||
|
MarkBufferDirty(nbuf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
if (nbuf != buf)
|
if (nbuf != buf)
|
||||||
UnlockReleaseBuffer(nbuf);
|
UnlockReleaseBuffer(nbuf);
|
||||||
@@ -564,7 +563,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Update insert page last, after everything has been marked as deleted */
|
/* Update insert page last, after everything has been marked as deleted */
|
||||||
HnswUpdateMetaPage(index, 0, NULL, insertPage, MAIN_FORKNUM, false);
|
HnswUpdateMetaPage(index, 0, NULL, insertPage, MAIN_FORKNUM);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -574,6 +573,7 @@ static void
|
|||||||
InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
|
InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
|
||||||
{
|
{
|
||||||
Relation index = info->index;
|
Relation index = info->index;
|
||||||
|
HASHCTL hash_ctl;
|
||||||
|
|
||||||
if (stats == NULL)
|
if (stats == NULL)
|
||||||
stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
|
stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
|
||||||
@@ -582,6 +582,7 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
vacuumstate->stats = stats;
|
vacuumstate->stats = stats;
|
||||||
vacuumstate->callback = callback;
|
vacuumstate->callback = callback;
|
||||||
vacuumstate->callback_state = callback_state;
|
vacuumstate->callback_state = callback_state;
|
||||||
|
vacuumstate->m = HnswGetM(index);
|
||||||
vacuumstate->efConstruction = HnswGetEfConstruction(index);
|
vacuumstate->efConstruction = HnswGetEfConstruction(index);
|
||||||
vacuumstate->bas = GetAccessStrategy(BAS_BULKREAD);
|
vacuumstate->bas = GetAccessStrategy(BAS_BULKREAD);
|
||||||
vacuumstate->procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
vacuumstate->procinfo = index_getprocinfo(index, 1, HNSW_DISTANCE_PROC);
|
||||||
@@ -591,11 +592,11 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
"Hnsw vacuum temporary context",
|
"Hnsw vacuum temporary context",
|
||||||
ALLOCSET_DEFAULT_SIZES);
|
ALLOCSET_DEFAULT_SIZES);
|
||||||
|
|
||||||
/* Get m from metapage */
|
|
||||||
HnswGetMetaPageInfo(index, &vacuumstate->m, NULL);
|
|
||||||
|
|
||||||
/* Create hash table */
|
/* Create hash table */
|
||||||
vacuumstate->deleted = tidhash_create(CurrentMemoryContext, 256, NULL);
|
hash_ctl.keysize = sizeof(ItemPointerData);
|
||||||
|
hash_ctl.entrysize = sizeof(ItemPointerData);
|
||||||
|
hash_ctl.hcxt = CurrentMemoryContext;
|
||||||
|
vacuumstate->deleted = hash_create("hnswbulkdelete indextids", 256, &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -604,7 +605,7 @@ InitVacuumState(HnswVacuumState * vacuumstate, IndexVacuumInfo *info, IndexBulkD
|
|||||||
static void
|
static void
|
||||||
FreeVacuumState(HnswVacuumState * vacuumstate)
|
FreeVacuumState(HnswVacuumState * vacuumstate)
|
||||||
{
|
{
|
||||||
tidhash_destroy(vacuumstate->deleted);
|
hash_destroy(vacuumstate->deleted);
|
||||||
FreeAccessStrategy(vacuumstate->bas);
|
FreeAccessStrategy(vacuumstate->bas);
|
||||||
pfree(vacuumstate->ntup);
|
pfree(vacuumstate->ntup);
|
||||||
MemoryContextDelete(vacuumstate->tmpCtx);
|
MemoryContextDelete(vacuumstate->tmpCtx);
|
||||||
|
|||||||
@@ -10,8 +10,8 @@
|
|||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
#include "tcop/tcopprot.h"
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
#if PG_VERSION_NUM >= 140000
|
||||||
#include "utils/backend_progress.h"
|
#include "utils/backend_progress.h"
|
||||||
@@ -506,30 +506,29 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
Buffer buf;
|
Buffer buf;
|
||||||
Page page;
|
Page page;
|
||||||
GenericXLogState *state;
|
GenericXLogState *state;
|
||||||
Size listSize;
|
OffsetNumber offno;
|
||||||
|
Size itemsz;
|
||||||
IvfflatList list;
|
IvfflatList list;
|
||||||
|
|
||||||
listSize = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
itemsz = MAXALIGN(IVFFLAT_LIST_SIZE(dimensions));
|
||||||
list = palloc(listSize);
|
list = palloc(itemsz);
|
||||||
|
|
||||||
buf = IvfflatNewBuffer(index, forkNum);
|
buf = IvfflatNewBuffer(index, forkNum);
|
||||||
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
IvfflatInitRegisterPage(index, &buf, &page, &state);
|
||||||
|
|
||||||
for (int i = 0; i < lists; i++)
|
for (int i = 0; i < lists; i++)
|
||||||
{
|
{
|
||||||
OffsetNumber offno;
|
|
||||||
|
|
||||||
/* Load list */
|
/* Load list */
|
||||||
list->startPage = InvalidBlockNumber;
|
list->startPage = InvalidBlockNumber;
|
||||||
list->insertPage = InvalidBlockNumber;
|
list->insertPage = InvalidBlockNumber;
|
||||||
memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
|
memcpy(&list->center, VectorArrayGet(centers, i), VECTOR_SIZE(dimensions));
|
||||||
|
|
||||||
/* Ensure free space */
|
/* Ensure free space */
|
||||||
if (PageGetFreeSpace(page) < listSize)
|
if (PageGetFreeSpace(page) < itemsz)
|
||||||
IvfflatAppendPage(index, &buf, &page, &state, forkNum);
|
IvfflatAppendPage(index, &buf, &page, &state, forkNum);
|
||||||
|
|
||||||
/* Add the item */
|
/* Add the item */
|
||||||
offno = PageAddItem(page, (Item) list, listSize, InvalidOffsetNumber, false, false);
|
offno = PageAddItem(page, (Item) list, itemsz, InvalidOffsetNumber, false, false);
|
||||||
if (offno == InvalidOffsetNumber)
|
if (offno == InvalidOffsetNumber)
|
||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
||||||
|
|
||||||
@@ -543,10 +542,10 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
|
|||||||
pfree(list);
|
pfree(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef IVFFLAT_KMEANS_DEBUG
|
|
||||||
/*
|
/*
|
||||||
* Print k-means metrics
|
* Print k-means metrics
|
||||||
*/
|
*/
|
||||||
|
#ifdef IVFFLAT_KMEANS_DEBUG
|
||||||
static void
|
static void
|
||||||
PrintKmeansMetrics(IvfflatBuildState * buildstate)
|
PrintKmeansMetrics(IvfflatBuildState * buildstate)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
int lists;
|
int lists;
|
||||||
double ratio;
|
double ratio;
|
||||||
double spc_seq_page_cost;
|
double spc_seq_page_cost;
|
||||||
Relation index;
|
Relation indexRel;
|
||||||
#if PG_VERSION_NUM < 120000
|
#if PG_VERSION_NUM < 120000
|
||||||
List *qinfos;
|
List *qinfos;
|
||||||
#endif
|
#endif
|
||||||
@@ -89,9 +89,9 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
|
|
||||||
MemSet(&costs, 0, sizeof(costs));
|
MemSet(&costs, 0, sizeof(costs));
|
||||||
|
|
||||||
index = index_open(path->indexinfo->indexoid, NoLock);
|
indexRel = index_open(path->indexinfo->indexoid, NoLock);
|
||||||
IvfflatGetMetaPageInfo(index, &lists, NULL);
|
lists = IvfflatGetLists(indexRel);
|
||||||
index_close(index, NoLock);
|
index_close(indexRel, NoLock);
|
||||||
|
|
||||||
/* Get the ratio of lists that we need to visit */
|
/* Get the ratio of lists that we need to visit */
|
||||||
ratio = ((double) ivfflat_probes) / lists;
|
ratio = ((double) ivfflat_probes) / lists;
|
||||||
@@ -105,20 +105,6 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count,
|
|||||||
*/
|
*/
|
||||||
costs.numIndexTuples = path->indexinfo->tuples * ratio;
|
costs.numIndexTuples = path->indexinfo->tuples * ratio;
|
||||||
|
|
||||||
/*
|
|
||||||
* Do not use index if no limit or limit + offset > expected tuples unless
|
|
||||||
* enable_seqscan = off
|
|
||||||
*/
|
|
||||||
if (root->limit_tuples < 0 || root->limit_tuples > costs.numIndexTuples)
|
|
||||||
{
|
|
||||||
*indexStartupCost = 1.0e10 - 1;
|
|
||||||
*indexTotalCost = 1.0e10 - 1;
|
|
||||||
*indexSelectivity = 0;
|
|
||||||
*indexCorrelation = 0;
|
|
||||||
*indexPages = 0;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
genericcostestimate(root, path, loop_count, &costs);
|
genericcostestimate(root, path, loop_count, &costs);
|
||||||
#else
|
#else
|
||||||
|
|||||||
@@ -244,8 +244,8 @@ typedef struct IvfflatScanList
|
|||||||
typedef struct IvfflatScanOpaqueData
|
typedef struct IvfflatScanOpaqueData
|
||||||
{
|
{
|
||||||
int probes;
|
int probes;
|
||||||
int dimensions;
|
|
||||||
bool first;
|
bool first;
|
||||||
|
Buffer buf;
|
||||||
|
|
||||||
/* Sorting */
|
/* Sorting */
|
||||||
Tuplesortstate *sortstate;
|
Tuplesortstate *sortstate;
|
||||||
@@ -275,10 +275,9 @@ VectorArray VectorArrayInit(int maxlen, int dimensions);
|
|||||||
void VectorArrayFree(VectorArray arr);
|
void VectorArrayFree(VectorArray arr);
|
||||||
void PrintVectorArray(char *msg, VectorArray arr);
|
void PrintVectorArray(char *msg, VectorArray arr);
|
||||||
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers);
|
||||||
FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
|
FmgrInfo *IvfflatOptionalProcInfo(Relation rel, uint16 procnum);
|
||||||
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
bool IvfflatNormValue(FmgrInfo *procinfo, Oid collation, Datum *value, Vector * result);
|
||||||
int IvfflatGetLists(Relation index);
|
int IvfflatGetLists(Relation index);
|
||||||
void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
|
|
||||||
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
|
||||||
void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
|
void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
|
||||||
void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
|
void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
|
||||||
|
|||||||
@@ -11,37 +11,36 @@
|
|||||||
* Find the list that minimizes the distance function
|
* Find the list that minimizes the distance function
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
FindInsertPage(Relation index, Datum *values, BlockNumber *insertPage, ListInfo * listInfo)
|
FindInsertPage(Relation rel, Datum *values, BlockNumber *insertPage, ListInfo * listInfo)
|
||||||
{
|
{
|
||||||
|
Buffer cbuf;
|
||||||
|
Page cpage;
|
||||||
|
IvfflatList list;
|
||||||
|
double distance;
|
||||||
double minDistance = DBL_MAX;
|
double minDistance = DBL_MAX;
|
||||||
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
||||||
FmgrInfo *procinfo;
|
FmgrInfo *procinfo;
|
||||||
Oid collation;
|
Oid collation;
|
||||||
|
OffsetNumber offno;
|
||||||
|
OffsetNumber maxoffno;
|
||||||
|
|
||||||
/* Avoid compiler warning */
|
/* Avoid compiler warning */
|
||||||
listInfo->blkno = nextblkno;
|
listInfo->blkno = nextblkno;
|
||||||
listInfo->offno = FirstOffsetNumber;
|
listInfo->offno = FirstOffsetNumber;
|
||||||
|
|
||||||
procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
|
procinfo = index_getprocinfo(rel, 1, IVFFLAT_DISTANCE_PROC);
|
||||||
collation = index->rd_indcollation[0];
|
collation = rel->rd_indcollation[0];
|
||||||
|
|
||||||
/* Search all list pages */
|
/* Search all list pages */
|
||||||
while (BlockNumberIsValid(nextblkno))
|
while (BlockNumberIsValid(nextblkno))
|
||||||
{
|
{
|
||||||
Buffer cbuf;
|
cbuf = ReadBuffer(rel, nextblkno);
|
||||||
Page cpage;
|
|
||||||
OffsetNumber maxoffno;
|
|
||||||
|
|
||||||
cbuf = ReadBuffer(index, nextblkno);
|
|
||||||
LockBuffer(cbuf, BUFFER_LOCK_SHARE);
|
LockBuffer(cbuf, BUFFER_LOCK_SHARE);
|
||||||
cpage = BufferGetPage(cbuf);
|
cpage = BufferGetPage(cbuf);
|
||||||
maxoffno = PageGetMaxOffsetNumber(cpage);
|
maxoffno = PageGetMaxOffsetNumber(cpage);
|
||||||
|
|
||||||
for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
IvfflatList list;
|
|
||||||
double distance;
|
|
||||||
|
|
||||||
list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
|
list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
|
||||||
distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum(&list->center)));
|
distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum(&list->center)));
|
||||||
|
|
||||||
@@ -64,7 +63,7 @@ FindInsertPage(Relation index, Datum *values, BlockNumber *insertPage, ListInfo
|
|||||||
* Insert a tuple into the index
|
* Insert a tuple into the index
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
InsertTuple(Relation rel, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heapRel)
|
||||||
{
|
{
|
||||||
IndexTuple itup;
|
IndexTuple itup;
|
||||||
Datum value;
|
Datum value;
|
||||||
@@ -81,33 +80,33 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
normprocinfo = IvfflatOptionalProcInfo(rel, IVFFLAT_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!IvfflatNormValue(normprocinfo, index->rd_indcollation[0], &value, NULL))
|
if (!IvfflatNormValue(normprocinfo, rel->rd_indcollation[0], &value, NULL))
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Find the insert page - sets the page and list info */
|
/* Find the insert page - sets the page and list info */
|
||||||
FindInsertPage(index, values, &insertPage, &listInfo);
|
FindInsertPage(rel, values, &insertPage, &listInfo);
|
||||||
Assert(BlockNumberIsValid(insertPage));
|
Assert(BlockNumberIsValid(insertPage));
|
||||||
originalInsertPage = insertPage;
|
originalInsertPage = insertPage;
|
||||||
|
|
||||||
/* Form tuple */
|
/* Form tuple */
|
||||||
itup = index_form_tuple(RelationGetDescr(index), &value, isnull);
|
itup = index_form_tuple(RelationGetDescr(rel), &value, isnull);
|
||||||
itup->t_tid = *heap_tid;
|
itup->t_tid = *heap_tid;
|
||||||
|
|
||||||
/* Get tuple size */
|
/* Get tuple size */
|
||||||
itemsz = MAXALIGN(IndexTupleSize(itup));
|
itemsz = MAXALIGN(IndexTupleSize(itup));
|
||||||
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)) - sizeof(ItemIdData));
|
Assert(itemsz <= BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(IvfflatPageOpaqueData)));
|
||||||
|
|
||||||
/* Find a page to insert the item */
|
/* Find a page to insert the item */
|
||||||
for (;;)
|
for (;;)
|
||||||
{
|
{
|
||||||
buf = ReadBuffer(index, insertPage);
|
buf = ReadBuffer(rel, insertPage);
|
||||||
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
|
||||||
|
|
||||||
state = GenericXLogStart(index);
|
state = GenericXLogStart(rel);
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
|
|
||||||
if (PageGetFreeSpace(page) >= itemsz)
|
if (PageGetFreeSpace(page) >= itemsz)
|
||||||
@@ -127,9 +126,9 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
Page newpage;
|
Page newpage;
|
||||||
|
|
||||||
/* Add a new page */
|
/* Add a new page */
|
||||||
LockRelationForExtension(index, ExclusiveLock);
|
LockRelationForExtension(rel, ExclusiveLock);
|
||||||
newbuf = IvfflatNewBuffer(index, MAIN_FORKNUM);
|
newbuf = IvfflatNewBuffer(rel, MAIN_FORKNUM);
|
||||||
UnlockRelationForExtension(index, ExclusiveLock);
|
UnlockRelationForExtension(rel, ExclusiveLock);
|
||||||
|
|
||||||
/* Init new page */
|
/* Init new page */
|
||||||
newpage = GenericXLogRegisterBuffer(state, newbuf, GENERIC_XLOG_FULL_IMAGE);
|
newpage = GenericXLogRegisterBuffer(state, newbuf, GENERIC_XLOG_FULL_IMAGE);
|
||||||
@@ -142,13 +141,15 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
|
IvfflatPageGetOpaque(page)->nextblkno = insertPage;
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(newbuf);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
|
|
||||||
/* Unlock previous buffer */
|
/* Unlock previous buffer */
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
/* Prepare new buffer */
|
/* Prepare new buffer */
|
||||||
state = GenericXLogStart(index);
|
state = GenericXLogStart(rel);
|
||||||
buf = newbuf;
|
buf = newbuf;
|
||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
page = GenericXLogRegisterBuffer(state, buf, 0);
|
||||||
break;
|
break;
|
||||||
@@ -157,13 +158,13 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
|
|||||||
|
|
||||||
/* Add to next offset */
|
/* Add to next offset */
|
||||||
if (PageAddItem(page, (Item) itup, itemsz, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
|
if (PageAddItem(page, (Item) itup, itemsz, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
|
||||||
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
|
elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(rel));
|
||||||
|
|
||||||
IvfflatCommitBuffer(buf, state);
|
IvfflatCommitBuffer(buf, state);
|
||||||
|
|
||||||
/* Update the insert page */
|
/* Update the insert page */
|
||||||
if (insertPage != originalInsertPage)
|
if (insertPage != originalInsertPage)
|
||||||
IvfflatUpdateList(index, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
IvfflatUpdateList(rel, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
@@ -6,10 +6,6 @@
|
|||||||
#include "ivfflat.h"
|
#include "ivfflat.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
|
|
||||||
#ifdef IVFFLAT_MEMORY
|
|
||||||
#include "utils/memutils.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Initialize with kmeans++
|
* Initialize with kmeans++
|
||||||
*
|
*
|
||||||
@@ -21,6 +17,10 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
|||||||
FmgrInfo *procinfo;
|
FmgrInfo *procinfo;
|
||||||
Oid collation;
|
Oid collation;
|
||||||
int64 j;
|
int64 j;
|
||||||
|
double distance;
|
||||||
|
double sum;
|
||||||
|
double choice;
|
||||||
|
Vector *vec;
|
||||||
float *weight = palloc(samples->length * sizeof(float));
|
float *weight = palloc(samples->length * sizeof(float));
|
||||||
int numCenters = centers->maxlen;
|
int numCenters = centers->maxlen;
|
||||||
int numSamples = samples->length;
|
int numSamples = samples->length;
|
||||||
@@ -33,21 +33,17 @@ InitCenters(Relation index, VectorArray samples, VectorArray centers, float *low
|
|||||||
centers->length++;
|
centers->length++;
|
||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
weight[j] = FLT_MAX;
|
weight[j] = DBL_MAX;
|
||||||
|
|
||||||
for (int i = 0; i < numCenters; i++)
|
for (int i = 0; i < numCenters; i++)
|
||||||
{
|
{
|
||||||
double sum;
|
|
||||||
double choice;
|
|
||||||
|
|
||||||
CHECK_FOR_INTERRUPTS();
|
CHECK_FOR_INTERRUPTS();
|
||||||
|
|
||||||
sum = 0.0;
|
sum = 0.0;
|
||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(samples, j);
|
vec = VectorArrayGet(samples, j);
|
||||||
double distance;
|
|
||||||
|
|
||||||
/* Only need to compute distance for new center */
|
/* Only need to compute distance for new center */
|
||||||
/* TODO Use triangle inequality to reduce distance calculations */
|
/* TODO Use triangle inequality to reduce distance calculations */
|
||||||
@@ -116,6 +112,7 @@ CompareVectors(const void *a, const void *b)
|
|||||||
static void
|
static void
|
||||||
QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
||||||
{
|
{
|
||||||
|
Vector *vec;
|
||||||
int dimensions = centers->dim;
|
int dimensions = centers->dim;
|
||||||
Oid collation = index->rd_indcollation[0];
|
Oid collation = index->rd_indcollation[0];
|
||||||
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
FmgrInfo *normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_KMEANS_NORM_PROC);
|
||||||
@@ -126,7 +123,7 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
qsort(samples->items, samples->length, VECTOR_SIZE(samples->dim), CompareVectors);
|
||||||
for (int i = 0; i < samples->length; i++)
|
for (int i = 0; i < samples->length; i++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(samples, i);
|
vec = VectorArrayGet(samples, i);
|
||||||
|
|
||||||
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
if (i == 0 || CompareVectors(vec, VectorArrayGet(samples, i - 1)) != 0)
|
||||||
{
|
{
|
||||||
@@ -139,7 +136,7 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* Fill remaining with random data */
|
/* Fill remaining with random data */
|
||||||
while (centers->length < centers->maxlen)
|
while (centers->length < centers->maxlen)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(centers, centers->length);
|
vec = VectorArrayGet(centers, centers->length);
|
||||||
|
|
||||||
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
|
||||||
vec->dim = dimensions;
|
vec->dim = dimensions;
|
||||||
@@ -155,23 +152,6 @@ QuickCenters(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef IVFFLAT_MEMORY
|
|
||||||
/*
|
|
||||||
* Show memory usage
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
ShowMemoryUsage(Size estimatedSize)
|
|
||||||
{
|
|
||||||
#if PG_VERSION_NUM >= 130000
|
|
||||||
elog(INFO, "total memory: %zu MB",
|
|
||||||
MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024));
|
|
||||||
#else
|
|
||||||
MemoryContextStats(CurrentMemoryContext);
|
|
||||||
#endif
|
|
||||||
elog(INFO, "estimated memory: %zu MB", estimatedSize / (1024 * 1024));
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Use Elkan for performance. This requires distance function to satisfy triangle inequality.
|
* Use Elkan for performance. This requires distance function to satisfy triangle inequality.
|
||||||
*
|
*
|
||||||
@@ -188,6 +168,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
Oid collation;
|
Oid collation;
|
||||||
Vector *vec;
|
Vector *vec;
|
||||||
Vector *newCenter;
|
Vector *newCenter;
|
||||||
|
int iteration;
|
||||||
int64 j;
|
int64 j;
|
||||||
int64 k;
|
int64 k;
|
||||||
int dimensions = centers->dim;
|
int dimensions = centers->dim;
|
||||||
@@ -201,6 +182,14 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
float *s;
|
float *s;
|
||||||
float *halfcdist;
|
float *halfcdist;
|
||||||
float *newcdist;
|
float *newcdist;
|
||||||
|
int changes;
|
||||||
|
double minDistance;
|
||||||
|
int closestCenter;
|
||||||
|
double distance;
|
||||||
|
bool rj;
|
||||||
|
bool rjreset;
|
||||||
|
double dxcx;
|
||||||
|
double dxc;
|
||||||
|
|
||||||
/* Calculate allocation sizes */
|
/* Calculate allocation sizes */
|
||||||
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
|
Size samplesSize = VECTOR_ARRAY_SIZE(samples->maxlen, samples->dim);
|
||||||
@@ -252,24 +241,20 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
vec->dim = dimensions;
|
vec->dim = dimensions;
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef IVFFLAT_MEMORY
|
|
||||||
ShowMemoryUsage(totalSize);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Pick initial centers */
|
/* Pick initial centers */
|
||||||
InitCenters(index, samples, centers, lowerBound);
|
InitCenters(index, samples, centers, lowerBound);
|
||||||
|
|
||||||
/* Assign each x to its closest initial center c(x) = argmin d(x,c) */
|
/* Assign each x to its closest initial center c(x) = argmin d(x,c) */
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
float minDistance = FLT_MAX;
|
minDistance = DBL_MAX;
|
||||||
int closestCenter = 0;
|
closestCenter = 0;
|
||||||
|
|
||||||
/* Find closest center */
|
/* Find closest center */
|
||||||
for (k = 0; k < numCenters; k++)
|
for (k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
/* TODO Use Lemma 1 in k-means++ initialization */
|
/* TODO Use Lemma 1 in k-means++ initialization */
|
||||||
float distance = lowerBound[j * numCenters + k];
|
distance = lowerBound[j * numCenters + k];
|
||||||
|
|
||||||
if (distance < minDistance)
|
if (distance < minDistance)
|
||||||
{
|
{
|
||||||
@@ -283,14 +268,13 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Give 500 iterations to converge */
|
/* Give 500 iterations to converge */
|
||||||
for (int iteration = 0; iteration < 500; iteration++)
|
for (iteration = 0; iteration < 500; iteration++)
|
||||||
{
|
{
|
||||||
int changes = 0;
|
|
||||||
bool rjreset;
|
|
||||||
|
|
||||||
/* Can take a while, so ensure we can interrupt */
|
/* Can take a while, so ensure we can interrupt */
|
||||||
CHECK_FOR_INTERRUPTS();
|
CHECK_FOR_INTERRUPTS();
|
||||||
|
|
||||||
|
changes = 0;
|
||||||
|
|
||||||
/* Step 1: For all centers, compute distance */
|
/* Step 1: For all centers, compute distance */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (j = 0; j < numCenters; j++)
|
||||||
{
|
{
|
||||||
@@ -298,8 +282,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
for (k = j + 1; k < numCenters; k++)
|
for (k = j + 1; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
distance = 0.5 * DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||||
|
|
||||||
halfcdist[j * numCenters + k] = distance;
|
halfcdist[j * numCenters + k] = distance;
|
||||||
halfcdist[k * numCenters + j] = distance;
|
halfcdist[k * numCenters + j] = distance;
|
||||||
}
|
}
|
||||||
@@ -308,12 +291,10 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* For all centers c, compute s(c) */
|
/* For all centers c, compute s(c) */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (j = 0; j < numCenters; j++)
|
||||||
{
|
{
|
||||||
float minDistance = FLT_MAX;
|
minDistance = DBL_MAX;
|
||||||
|
|
||||||
for (k = 0; k < numCenters; k++)
|
for (k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance;
|
|
||||||
|
|
||||||
if (j == k)
|
if (j == k)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
@@ -329,8 +310,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
bool rj;
|
|
||||||
|
|
||||||
/* Step 2: Identify all points x such that u(x) <= s(c(x)) */
|
/* Step 2: Identify all points x such that u(x) <= s(c(x)) */
|
||||||
if (upperBound[j] <= s[closestCenters[j]])
|
if (upperBound[j] <= s[closestCenters[j]])
|
||||||
continue;
|
continue;
|
||||||
@@ -339,8 +318,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
for (k = 0; k < numCenters; k++)
|
for (k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float dxcx;
|
|
||||||
|
|
||||||
/* Step 3: For all remaining points x and centers c */
|
/* Step 3: For all remaining points x and centers c */
|
||||||
if (k == closestCenters[j])
|
if (k == closestCenters[j])
|
||||||
continue;
|
continue;
|
||||||
@@ -370,7 +347,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
/* Step 3b */
|
/* Step 3b */
|
||||||
if (dxcx > lowerBound[j * numCenters + k] || dxcx > halfcdist[closestCenters[j] * numCenters + k])
|
if (dxcx > lowerBound[j * numCenters + k] || dxcx > halfcdist[closestCenters[j] * numCenters + k])
|
||||||
{
|
{
|
||||||
float dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
dxc = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, PointerGetDatum(vec), PointerGetDatum(VectorArrayGet(centers, k))));
|
||||||
|
|
||||||
/* d(x,c) calculated */
|
/* d(x,c) calculated */
|
||||||
lowerBound[j * numCenters + k] = dxc;
|
lowerBound[j * numCenters + k] = dxc;
|
||||||
@@ -384,6 +361,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
changes++;
|
changes++;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -400,8 +378,6 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
for (j = 0; j < numSamples; j++)
|
for (j = 0; j < numSamples; j++)
|
||||||
{
|
{
|
||||||
int closestCenter;
|
|
||||||
|
|
||||||
vec = VectorArrayGet(samples, j);
|
vec = VectorArrayGet(samples, j);
|
||||||
closestCenter = closestCenters[j];
|
closestCenter = closestCenters[j];
|
||||||
|
|
||||||
@@ -450,7 +426,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
{
|
{
|
||||||
for (k = 0; k < numCenters; k++)
|
for (k = 0; k < numCenters; k++)
|
||||||
{
|
{
|
||||||
float distance = lowerBound[j * numCenters + k] - newcdist[k];
|
distance = lowerBound[j * numCenters + k] - newcdist[k];
|
||||||
|
|
||||||
if (distance < 0)
|
if (distance < 0)
|
||||||
distance = 0;
|
distance = 0;
|
||||||
@@ -466,7 +442,7 @@ ElkanKmeans(Relation index, VectorArray samples, VectorArray centers)
|
|||||||
|
|
||||||
/* Step 7 */
|
/* Step 7 */
|
||||||
for (j = 0; j < numCenters; j++)
|
for (j = 0; j < numCenters; j++)
|
||||||
VectorArraySet(centers, j, VectorArrayGet(newCenters, j));
|
memcpy(VectorArrayGet(centers, j), VectorArrayGet(newCenters, j), VECTOR_SIZE(dimensions));
|
||||||
|
|
||||||
if (changes == 0 && iteration != 0)
|
if (changes == 0 && iteration != 0)
|
||||||
break;
|
break;
|
||||||
@@ -489,6 +465,9 @@ static void
|
|||||||
CheckCenters(Relation index, VectorArray centers)
|
CheckCenters(Relation index, VectorArray centers)
|
||||||
{
|
{
|
||||||
FmgrInfo *normprocinfo;
|
FmgrInfo *normprocinfo;
|
||||||
|
Oid collation;
|
||||||
|
Vector *vec;
|
||||||
|
double norm;
|
||||||
|
|
||||||
if (centers->length != centers->maxlen)
|
if (centers->length != centers->maxlen)
|
||||||
elog(ERROR, "Not enough centers. Please report a bug.");
|
elog(ERROR, "Not enough centers. Please report a bug.");
|
||||||
@@ -496,7 +475,7 @@ CheckCenters(Relation index, VectorArray centers)
|
|||||||
/* Ensure no NaN or infinite values */
|
/* Ensure no NaN or infinite values */
|
||||||
for (int i = 0; i < centers->length; i++)
|
for (int i = 0; i < centers->length; i++)
|
||||||
{
|
{
|
||||||
Vector *vec = VectorArrayGet(centers, i);
|
vec = VectorArrayGet(centers, i);
|
||||||
|
|
||||||
for (int j = 0; j < vec->dim; j++)
|
for (int j = 0; j < vec->dim; j++)
|
||||||
{
|
{
|
||||||
@@ -522,12 +501,11 @@ CheckCenters(Relation index, VectorArray centers)
|
|||||||
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
|
||||||
if (normprocinfo != NULL)
|
if (normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
Oid collation = index->rd_indcollation[0];
|
collation = index->rd_indcollation[0];
|
||||||
|
|
||||||
for (int i = 0; i < centers->length; i++)
|
for (int i = 0; i < centers->length; i++)
|
||||||
{
|
{
|
||||||
double norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, PointerGetDatum(VectorArrayGet(centers, i))));
|
norm = DatumGetFloat8(FunctionCall1Coll(normprocinfo, collation, PointerGetDatum(VectorArrayGet(centers, i))));
|
||||||
|
|
||||||
if (norm == 0)
|
if (norm == 0)
|
||||||
elog(ERROR, "Zero norm detected. Please report a bug.");
|
elog(ERROR, "Zero norm detected. Please report a bug.");
|
||||||
}
|
}
|
||||||
|
|||||||
114
src/ivfscan.c
114
src/ivfscan.c
@@ -31,36 +31,36 @@ CompareLists(const pairingheap_node *a, const pairingheap_node *b, void *arg)
|
|||||||
static void
|
static void
|
||||||
GetScanLists(IndexScanDesc scan, Datum value)
|
GetScanLists(IndexScanDesc scan, Datum value)
|
||||||
{
|
{
|
||||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
Buffer cbuf;
|
||||||
|
Page cpage;
|
||||||
|
IvfflatList list;
|
||||||
|
OffsetNumber offno;
|
||||||
|
OffsetNumber maxoffno;
|
||||||
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
|
||||||
int listCount = 0;
|
int listCount = 0;
|
||||||
|
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||||
|
double distance;
|
||||||
|
IvfflatScanList *scanlist;
|
||||||
double maxDistance = DBL_MAX;
|
double maxDistance = DBL_MAX;
|
||||||
|
|
||||||
/* Search all list pages */
|
/* Search all list pages */
|
||||||
while (BlockNumberIsValid(nextblkno))
|
while (BlockNumberIsValid(nextblkno))
|
||||||
{
|
{
|
||||||
Buffer cbuf;
|
|
||||||
Page cpage;
|
|
||||||
OffsetNumber maxoffno;
|
|
||||||
|
|
||||||
cbuf = ReadBuffer(scan->indexRelation, nextblkno);
|
cbuf = ReadBuffer(scan->indexRelation, nextblkno);
|
||||||
LockBuffer(cbuf, BUFFER_LOCK_SHARE);
|
LockBuffer(cbuf, BUFFER_LOCK_SHARE);
|
||||||
cpage = BufferGetPage(cbuf);
|
cpage = BufferGetPage(cbuf);
|
||||||
|
|
||||||
maxoffno = PageGetMaxOffsetNumber(cpage);
|
maxoffno = PageGetMaxOffsetNumber(cpage);
|
||||||
|
|
||||||
for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
|
list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
|
||||||
double distance;
|
|
||||||
|
|
||||||
/* Use procinfo from the index instead of scan key for performance */
|
/* Use procinfo from the index instead of scan key for performance */
|
||||||
distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
|
distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
|
||||||
|
|
||||||
if (listCount < so->probes)
|
if (listCount < so->probes)
|
||||||
{
|
{
|
||||||
IvfflatScanList *scanlist;
|
|
||||||
|
|
||||||
scanlist = &so->lists[listCount];
|
scanlist = &so->lists[listCount];
|
||||||
scanlist->startPage = list->startPage;
|
scanlist->startPage = list->startPage;
|
||||||
scanlist->distance = distance;
|
scanlist->distance = distance;
|
||||||
@@ -75,8 +75,6 @@ GetScanLists(IndexScanDesc scan, Datum value)
|
|||||||
}
|
}
|
||||||
else if (distance < maxDistance)
|
else if (distance < maxDistance)
|
||||||
{
|
{
|
||||||
IvfflatScanList *scanlist;
|
|
||||||
|
|
||||||
/* Remove */
|
/* Remove */
|
||||||
scanlist = (IvfflatScanList *) pairingheap_remove_first(so->listQueue);
|
scanlist = (IvfflatScanList *) pairingheap_remove_first(so->listQueue);
|
||||||
|
|
||||||
@@ -103,6 +101,14 @@ static void
|
|||||||
GetScanItems(IndexScanDesc scan, Datum value)
|
GetScanItems(IndexScanDesc scan, Datum value)
|
||||||
{
|
{
|
||||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||||
|
Buffer buf;
|
||||||
|
Page page;
|
||||||
|
IndexTuple itup;
|
||||||
|
BlockNumber searchPage;
|
||||||
|
OffsetNumber offno;
|
||||||
|
OffsetNumber maxoffno;
|
||||||
|
Datum datum;
|
||||||
|
bool isnull;
|
||||||
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
|
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
|
||||||
double tuples = 0;
|
double tuples = 0;
|
||||||
|
|
||||||
@@ -122,28 +128,19 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
/* Search closest probes lists */
|
/* Search closest probes lists */
|
||||||
while (!pairingheap_is_empty(so->listQueue))
|
while (!pairingheap_is_empty(so->listQueue))
|
||||||
{
|
{
|
||||||
BlockNumber searchPage = ((IvfflatScanList *) pairingheap_remove_first(so->listQueue))->startPage;
|
searchPage = ((IvfflatScanList *) pairingheap_remove_first(so->listQueue))->startPage;
|
||||||
|
|
||||||
/* Search all entry pages for list */
|
/* Search all entry pages for list */
|
||||||
while (BlockNumberIsValid(searchPage))
|
while (BlockNumberIsValid(searchPage))
|
||||||
{
|
{
|
||||||
Buffer buf;
|
|
||||||
Page page;
|
|
||||||
OffsetNumber maxoffno;
|
|
||||||
|
|
||||||
buf = ReadBufferExtended(scan->indexRelation, MAIN_FORKNUM, searchPage, RBM_NORMAL, bas);
|
buf = ReadBufferExtended(scan->indexRelation, MAIN_FORKNUM, searchPage, RBM_NORMAL, bas);
|
||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
page = BufferGetPage(buf);
|
page = BufferGetPage(buf);
|
||||||
maxoffno = PageGetMaxOffsetNumber(page);
|
maxoffno = PageGetMaxOffsetNumber(page);
|
||||||
|
|
||||||
for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
|
||||||
{
|
{
|
||||||
IndexTuple itup;
|
itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno));
|
||||||
Datum datum;
|
|
||||||
bool isnull;
|
|
||||||
ItemId itemid = PageGetItemId(page, offno);
|
|
||||||
|
|
||||||
itup = (IndexTuple) PageGetItem(page, itemid);
|
|
||||||
datum = index_getattr(itup, 1, tupdesc, &isnull);
|
datum = index_getattr(itup, 1, tupdesc, &isnull);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -157,6 +154,8 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
slot->tts_isnull[0] = false;
|
slot->tts_isnull[0] = false;
|
||||||
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
|
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
|
||||||
slot->tts_isnull[1] = false;
|
slot->tts_isnull[1] = false;
|
||||||
|
slot->tts_values[2] = Int32GetDatum((int) searchPage);
|
||||||
|
slot->tts_isnull[2] = false;
|
||||||
ExecStoreVirtualTuple(slot);
|
ExecStoreVirtualTuple(slot);
|
||||||
|
|
||||||
tuplesort_puttupleslot(so->sortstate, slot);
|
tuplesort_puttupleslot(so->sortstate, slot);
|
||||||
@@ -181,6 +180,29 @@ GetScanItems(IndexScanDesc scan, Datum value)
|
|||||||
tuplesort_performsort(so->sortstate);
|
tuplesort_performsort(so->sortstate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get dimensions from metapage
|
||||||
|
*/
|
||||||
|
static int
|
||||||
|
GetDimensions(Relation index)
|
||||||
|
{
|
||||||
|
Buffer buf;
|
||||||
|
Page page;
|
||||||
|
IvfflatMetaPage metap;
|
||||||
|
int dimensions;
|
||||||
|
|
||||||
|
buf = ReadBuffer(index, IVFFLAT_METAPAGE_BLKNO);
|
||||||
|
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
||||||
|
page = BufferGetPage(buf);
|
||||||
|
metap = IvfflatPageGetMeta(page);
|
||||||
|
|
||||||
|
dimensions = metap->dimensions;
|
||||||
|
|
||||||
|
UnlockReleaseBuffer(buf);
|
||||||
|
|
||||||
|
return dimensions;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Prepare for an index scan
|
* Prepare for an index scan
|
||||||
*/
|
*/
|
||||||
@@ -190,7 +212,6 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
IndexScanDesc scan;
|
IndexScanDesc scan;
|
||||||
IvfflatScanOpaque so;
|
IvfflatScanOpaque so;
|
||||||
int lists;
|
int lists;
|
||||||
int dimensions;
|
|
||||||
AttrNumber attNums[] = {1};
|
AttrNumber attNums[] = {1};
|
||||||
Oid sortOperators[] = {Float8LessOperator};
|
Oid sortOperators[] = {Float8LessOperator};
|
||||||
Oid sortCollations[] = {InvalidOid};
|
Oid sortCollations[] = {InvalidOid};
|
||||||
@@ -198,17 +219,15 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
int probes = ivfflat_probes;
|
int probes = ivfflat_probes;
|
||||||
|
|
||||||
scan = RelationGetIndexScan(index, nkeys, norderbys);
|
scan = RelationGetIndexScan(index, nkeys, norderbys);
|
||||||
|
lists = IvfflatGetLists(scan->indexRelation);
|
||||||
/* Get lists and dimensions from metapage */
|
|
||||||
IvfflatGetMetaPageInfo(index, &lists, &dimensions);
|
|
||||||
|
|
||||||
if (probes > lists)
|
if (probes > lists)
|
||||||
probes = lists;
|
probes = lists;
|
||||||
|
|
||||||
so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + probes * sizeof(IvfflatScanList));
|
so = (IvfflatScanOpaque) palloc(offsetof(IvfflatScanOpaqueData, lists) + probes * sizeof(IvfflatScanList));
|
||||||
|
so->buf = InvalidBuffer;
|
||||||
so->first = true;
|
so->first = true;
|
||||||
so->probes = probes;
|
so->probes = probes;
|
||||||
so->dimensions = dimensions;
|
|
||||||
|
|
||||||
/* Set support functions */
|
/* Set support functions */
|
||||||
so->procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
|
so->procinfo = index_getprocinfo(index, 1, IVFFLAT_DISTANCE_PROC);
|
||||||
@@ -217,12 +236,13 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
|
|||||||
|
|
||||||
/* Create tuple description for sorting */
|
/* Create tuple description for sorting */
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
so->tupdesc = CreateTemplateTupleDesc(2);
|
so->tupdesc = CreateTemplateTupleDesc(3);
|
||||||
#else
|
#else
|
||||||
so->tupdesc = CreateTemplateTupleDesc(2, false);
|
so->tupdesc = CreateTemplateTupleDesc(3, false);
|
||||||
#endif
|
#endif
|
||||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
|
||||||
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
|
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
|
||||||
|
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
|
||||||
|
|
||||||
/* Prep sort */
|
/* Prep sort */
|
||||||
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
|
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
|
||||||
@@ -288,13 +308,8 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
if (scan->orderByData == NULL)
|
if (scan->orderByData == NULL)
|
||||||
elog(ERROR, "cannot scan ivfflat index without order");
|
elog(ERROR, "cannot scan ivfflat index without order");
|
||||||
|
|
||||||
/* Requires MVCC-compliant snapshot as not able to pin during sorting */
|
|
||||||
/* https://www.postgresql.org/docs/current/index-locking.html */
|
|
||||||
if (!IsMVCCSnapshot(scan->xs_snapshot))
|
|
||||||
elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");
|
|
||||||
|
|
||||||
if (scan->orderByData->sk_flags & SK_ISNULL)
|
if (scan->orderByData->sk_flags & SK_ISNULL)
|
||||||
value = PointerGetDatum(InitVector(so->dimensions));
|
value = PointerGetDatum(InitVector(GetDimensions(scan->indexRelation)));
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
value = scan->orderByData->sk_argument;
|
value = scan->orderByData->sk_argument;
|
||||||
@@ -319,14 +334,27 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
|
|||||||
|
|
||||||
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL))
|
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL))
|
||||||
{
|
{
|
||||||
ItemPointer heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
|
ItemPointer tid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull));
|
||||||
|
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
#if PG_VERSION_NUM >= 120000
|
||||||
scan->xs_heaptid = *heaptid;
|
scan->xs_heaptid = *tid;
|
||||||
#else
|
#else
|
||||||
scan->xs_ctup.t_self = *heaptid;
|
scan->xs_ctup.t_self = *tid;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/* Unpin buffer */
|
||||||
|
if (BufferIsValid(so->buf))
|
||||||
|
ReleaseBuffer(so->buf);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* An index scan must maintain a pin on the index page holding the
|
||||||
|
* item last returned by amgettuple
|
||||||
|
*
|
||||||
|
* https://www.postgresql.org/docs/current/index-locking.html
|
||||||
|
*/
|
||||||
|
so->buf = ReadBuffer(scan->indexRelation, indexblkno);
|
||||||
|
|
||||||
scan->xs_recheckorderby = false;
|
scan->xs_recheckorderby = false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -342,6 +370,10 @@ ivfflatendscan(IndexScanDesc scan)
|
|||||||
{
|
{
|
||||||
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
|
||||||
|
|
||||||
|
/* Release pin */
|
||||||
|
if (BufferIsValid(so->buf))
|
||||||
|
ReleaseBuffer(so->buf);
|
||||||
|
|
||||||
pairingheap_free(so->listQueue);
|
pairingheap_free(so->listQueue);
|
||||||
tuplesort_end(so->sortstate);
|
tuplesort_end(so->sortstate);
|
||||||
|
|
||||||
|
|||||||
@@ -57,12 +57,12 @@ IvfflatGetLists(Relation index)
|
|||||||
* Get proc
|
* Get proc
|
||||||
*/
|
*/
|
||||||
FmgrInfo *
|
FmgrInfo *
|
||||||
IvfflatOptionalProcInfo(Relation index, uint16 procnum)
|
IvfflatOptionalProcInfo(Relation rel, uint16 procnum)
|
||||||
{
|
{
|
||||||
if (!OidIsValid(index_getprocid(index, 1, procnum)))
|
if (!OidIsValid(index_getprocid(rel, 1, procnum)))
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
return index_getprocinfo(index, 1, procnum);
|
return index_getprocinfo(rel, 1, procnum);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -136,6 +136,7 @@ IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogStat
|
|||||||
void
|
void
|
||||||
IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
|
IvfflatCommitBuffer(Buffer buf, GenericXLogState *state)
|
||||||
{
|
{
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -159,6 +160,8 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
|
|||||||
IvfflatInitPage(newbuf, newpage);
|
IvfflatInitPage(newbuf, newpage);
|
||||||
|
|
||||||
/* Commit */
|
/* Commit */
|
||||||
|
MarkBufferDirty(*buf);
|
||||||
|
MarkBufferDirty(newbuf);
|
||||||
GenericXLogFinish(*state);
|
GenericXLogFinish(*state);
|
||||||
|
|
||||||
/* Unlock */
|
/* Unlock */
|
||||||
@@ -169,29 +172,6 @@ IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **st
|
|||||||
*buf = newbuf;
|
*buf = newbuf;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the metapage info
|
|
||||||
*/
|
|
||||||
void
|
|
||||||
IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions)
|
|
||||||
{
|
|
||||||
Buffer buf;
|
|
||||||
Page page;
|
|
||||||
IvfflatMetaPage metap;
|
|
||||||
|
|
||||||
buf = ReadBuffer(index, IVFFLAT_METAPAGE_BLKNO);
|
|
||||||
LockBuffer(buf, BUFFER_LOCK_SHARE);
|
|
||||||
page = BufferGetPage(buf);
|
|
||||||
metap = IvfflatPageGetMeta(page);
|
|
||||||
|
|
||||||
*lists = metap->lists;
|
|
||||||
|
|
||||||
if (dimensions != NULL)
|
|
||||||
*dimensions = metap->dimensions;
|
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Update the start or insert page of a list
|
* Update the start or insert page of a list
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
|
|||||||
{
|
{
|
||||||
/* Delete tuples */
|
/* Delete tuples */
|
||||||
PageIndexMultiDelete(page, deletable, ndeletable);
|
PageIndexMultiDelete(page, deletable, ndeletable);
|
||||||
|
MarkBufferDirty(buf);
|
||||||
GenericXLogFinish(state);
|
GenericXLogFinish(state);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|||||||
59
src/vector.c
59
src/vector.c
@@ -89,7 +89,7 @@ CheckDim(int dim)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Ensure finite element
|
* Ensure finite elements
|
||||||
*/
|
*/
|
||||||
static inline void
|
static inline void
|
||||||
CheckElement(float value)
|
CheckElement(float value)
|
||||||
@@ -177,15 +177,14 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_in);
|
|||||||
Datum
|
Datum
|
||||||
vector_in(PG_FUNCTION_ARGS)
|
vector_in(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
char *lit = PG_GETARG_CSTRING(0);
|
char *str = PG_GETARG_CSTRING(0);
|
||||||
int32 typmod = PG_GETARG_INT32(2);
|
int32 typmod = PG_GETARG_INT32(2);
|
||||||
float x[VECTOR_MAX_DIM];
|
float x[VECTOR_MAX_DIM];
|
||||||
int dim = 0;
|
int dim = 0;
|
||||||
char *pt;
|
char *pt;
|
||||||
char *stringEnd;
|
char *stringEnd;
|
||||||
Vector *result;
|
Vector *result;
|
||||||
char *litcopy = pstrdup(lit);
|
char *lit = pstrdup(str);
|
||||||
char *str = litcopy;
|
|
||||||
|
|
||||||
while (vector_isspace(*str))
|
while (vector_isspace(*str))
|
||||||
str++;
|
str++;
|
||||||
@@ -269,7 +268,7 @@ vector_in(PG_FUNCTION_ARGS)
|
|||||||
(errcode(ERRCODE_DATA_EXCEPTION),
|
(errcode(ERRCODE_DATA_EXCEPTION),
|
||||||
errmsg("vector must have at least 1 dimension")));
|
errmsg("vector must have at least 1 dimension")));
|
||||||
|
|
||||||
pfree(litcopy);
|
pfree(lit);
|
||||||
|
|
||||||
CheckExpectedDim(typmod, dim);
|
CheckExpectedDim(typmod, dim);
|
||||||
|
|
||||||
@@ -438,18 +437,17 @@ vector_send(PG_FUNCTION_ARGS)
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
* Convert vector to vector
|
* Convert vector to vector
|
||||||
* This is needed to check the type modifier
|
|
||||||
*/
|
*/
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector);
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(vector);
|
||||||
Datum
|
Datum
|
||||||
vector(PG_FUNCTION_ARGS)
|
vector(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *vec = PG_GETARG_VECTOR_P(0);
|
Vector *arg = PG_GETARG_VECTOR_P(0);
|
||||||
int32 typmod = PG_GETARG_INT32(1);
|
int32 typmod = PG_GETARG_INT32(1);
|
||||||
|
|
||||||
CheckExpectedDim(typmod, vec->dim);
|
CheckExpectedDim(typmod, arg->dim);
|
||||||
|
|
||||||
PG_RETURN_POINTER(vec);
|
PG_RETURN_POINTER(arg);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -466,6 +464,7 @@ array_to_vector(PG_FUNCTION_ARGS)
|
|||||||
bool typbyval;
|
bool typbyval;
|
||||||
char typalign;
|
char typalign;
|
||||||
Datum *elemsp;
|
Datum *elemsp;
|
||||||
|
bool *nullsp;
|
||||||
int nelemsp;
|
int nelemsp;
|
||||||
|
|
||||||
if (ARR_NDIM(array) > 1)
|
if (ARR_NDIM(array) > 1)
|
||||||
@@ -479,7 +478,7 @@ array_to_vector(PG_FUNCTION_ARGS)
|
|||||||
errmsg("array must not contain nulls")));
|
errmsg("array must not contain nulls")));
|
||||||
|
|
||||||
get_typlenbyvalalign(ARR_ELEMTYPE(array), &typlen, &typbyval, &typalign);
|
get_typlenbyvalalign(ARR_ELEMTYPE(array), &typlen, &typbyval, &typalign);
|
||||||
deconstruct_array(array, ARR_ELEMTYPE(array), typlen, typbyval, typalign, &elemsp, NULL, &nelemsp);
|
deconstruct_array(array, ARR_ELEMTYPE(array), typlen, typbyval, typalign, &elemsp, &nullsp, &nelemsp);
|
||||||
|
|
||||||
CheckDim(nelemsp);
|
CheckDim(nelemsp);
|
||||||
CheckExpectedDim(typmod, nelemsp);
|
CheckExpectedDim(typmod, nelemsp);
|
||||||
@@ -513,12 +512,6 @@ array_to_vector(PG_FUNCTION_ARGS)
|
|||||||
errmsg("unsupported array type")));
|
errmsg("unsupported array type")));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Free allocation from deconstruct_array. Do not free individual elements
|
|
||||||
* when pass-by-reference since they point to original array.
|
|
||||||
*/
|
|
||||||
pfree(elemsp);
|
|
||||||
|
|
||||||
/* Check elements */
|
/* Check elements */
|
||||||
for (int i = 0; i < result->dim; i++)
|
for (int i = 0; i < result->dim; i++)
|
||||||
CheckElement(result->x[i]);
|
CheckElement(result->x[i]);
|
||||||
@@ -702,8 +695,6 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
|
|||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = PG_GETARG_VECTOR_P(1);
|
||||||
float *ax = a->x;
|
|
||||||
float *bx = b->x;
|
|
||||||
float dp = 0.0;
|
float dp = 0.0;
|
||||||
double distance;
|
double distance;
|
||||||
|
|
||||||
@@ -711,7 +702,7 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
|
|||||||
|
|
||||||
/* Auto-vectorized */
|
/* Auto-vectorized */
|
||||||
for (int i = 0; i < a->dim; i++)
|
for (int i = 0; i < a->dim; i++)
|
||||||
dp += ax[i] * bx[i];
|
dp += a->x[i] * b->x[i];
|
||||||
|
|
||||||
distance = (double) dp;
|
distance = (double) dp;
|
||||||
|
|
||||||
@@ -725,7 +716,7 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Get the L1 distance between two vectors
|
* Get the L1 distance between vectors
|
||||||
*/
|
*/
|
||||||
PGDLLEXPORT PG_FUNCTION_INFO_V1(l1_distance);
|
PGDLLEXPORT PG_FUNCTION_INFO_V1(l1_distance);
|
||||||
Datum
|
Datum
|
||||||
@@ -904,8 +895,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_lt);
|
|||||||
Datum
|
Datum
|
||||||
vector_lt(PG_FUNCTION_ARGS)
|
vector_lt(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) < 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) < 0);
|
||||||
}
|
}
|
||||||
@@ -917,8 +908,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_le);
|
|||||||
Datum
|
Datum
|
||||||
vector_le(PG_FUNCTION_ARGS)
|
vector_le(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) <= 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) <= 0);
|
||||||
}
|
}
|
||||||
@@ -930,8 +921,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_eq);
|
|||||||
Datum
|
Datum
|
||||||
vector_eq(PG_FUNCTION_ARGS)
|
vector_eq(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) == 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) == 0);
|
||||||
}
|
}
|
||||||
@@ -943,8 +934,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_ne);
|
|||||||
Datum
|
Datum
|
||||||
vector_ne(PG_FUNCTION_ARGS)
|
vector_ne(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) != 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) != 0);
|
||||||
}
|
}
|
||||||
@@ -956,8 +947,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_ge);
|
|||||||
Datum
|
Datum
|
||||||
vector_ge(PG_FUNCTION_ARGS)
|
vector_ge(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) >= 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) >= 0);
|
||||||
}
|
}
|
||||||
@@ -969,8 +960,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_gt);
|
|||||||
Datum
|
Datum
|
||||||
vector_gt(PG_FUNCTION_ARGS)
|
vector_gt(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_BOOL(vector_cmp_internal(a, b) > 0);
|
PG_RETURN_BOOL(vector_cmp_internal(a, b) > 0);
|
||||||
}
|
}
|
||||||
@@ -982,8 +973,8 @@ PGDLLEXPORT PG_FUNCTION_INFO_V1(vector_cmp);
|
|||||||
Datum
|
Datum
|
||||||
vector_cmp(PG_FUNCTION_ARGS)
|
vector_cmp(PG_FUNCTION_ARGS)
|
||||||
{
|
{
|
||||||
Vector *a = PG_GETARG_VECTOR_P(0);
|
Vector *a = (Vector *) PG_GETARG_VECTOR_P(0);
|
||||||
Vector *b = PG_GETARG_VECTOR_P(1);
|
Vector *b = (Vector *) PG_GETARG_VECTOR_P(1);
|
||||||
|
|
||||||
PG_RETURN_INT32(vector_cmp_internal(a, b));
|
PG_RETURN_INT32(vector_cmp_internal(a, b));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -106,12 +106,6 @@ SELECT cosine_distance('[1,1]', '[1,1]');
|
|||||||
0
|
0
|
||||||
(1 row)
|
(1 row)
|
||||||
|
|
||||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
|
||||||
cosine_distance
|
|
||||||
-----------------
|
|
||||||
1
|
|
||||||
(1 row)
|
|
||||||
|
|
||||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||||
cosine_distance
|
cosine_distance
|
||||||
-----------------
|
-----------------
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ SELECT inner_product('[3e38]', '[3e38]');
|
|||||||
SELECT cosine_distance('[1,2]', '[2,4]');
|
SELECT cosine_distance('[1,2]', '[2,4]');
|
||||||
SELECT cosine_distance('[1,2]', '[0,0]');
|
SELECT cosine_distance('[1,2]', '[0,0]');
|
||||||
SELECT cosine_distance('[1,1]', '[1,1]');
|
SELECT cosine_distance('[1,1]', '[1,1]');
|
||||||
SELECT cosine_distance('[1,0]', '[0,2]');
|
|
||||||
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
SELECT cosine_distance('[1,1]', '[-1,-1]');
|
||||||
SELECT cosine_distance('[1,2]', '[3]');
|
SELECT cosine_distance('[1,2]', '[3]');
|
||||||
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
SELECT cosine_distance('[1,1]', '[1.1,1.1]');
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ sub test_index_replay
|
|||||||
|
|
||||||
# Wait for replica to catch up
|
# Wait for replica to catch up
|
||||||
my $applname = $node_replica->name;
|
my $applname = $node_replica->name;
|
||||||
|
|
||||||
|
my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
|
||||||
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
|
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
|
||||||
$node_primary->poll_query_until('postgres', $caughtup_query)
|
$node_primary->poll_query_until('postgres', $caughtup_query)
|
||||||
or die "Timed out while waiting for replica 1 to catch up";
|
or die "Timed out while waiting for replica 1 to catch up";
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ for my $i (0 .. $#operators)
|
|||||||
# Test approximate results
|
# Test approximate results
|
||||||
if ($operator ne "<#>")
|
if ($operator ne "<#>")
|
||||||
{
|
{
|
||||||
# TODO Fix test (uniform random vectors all have similar inner product)
|
# TODO fix test
|
||||||
test_recall(1, 0.71, $operator);
|
test_recall(1, 0.71, $operator);
|
||||||
test_recall(10, 0.95, $operator);
|
test_recall(10, 0.95, $operator);
|
||||||
}
|
}
|
||||||
@@ -115,7 +115,7 @@ for my $i (0 .. $#operators)
|
|||||||
# Test approximate results
|
# Test approximate results
|
||||||
if ($operator ne "<#>")
|
if ($operator ne "<#>")
|
||||||
{
|
{
|
||||||
# TODO Fix test (uniform random vectors all have similar inner product)
|
# TODO fix test
|
||||||
test_recall(1, 0.71, $operator);
|
test_recall(1, 0.71, $operator);
|
||||||
test_recall(10, 0.95, $operator);
|
test_recall(10, 0.95, $operator);
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,8 @@ sub test_index_replay
|
|||||||
|
|
||||||
# Wait for replica to catch up
|
# Wait for replica to catch up
|
||||||
my $applname = $node_replica->name;
|
my $applname = $node_replica->name;
|
||||||
|
|
||||||
|
my $server_version_num = $node_primary->safe_psql("postgres", "SHOW server_version_num");
|
||||||
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
|
my $caughtup_query = "SELECT pg_current_wal_lsn() <= replay_lsn FROM pg_stat_replication WHERE application_name = '$applname';";
|
||||||
$node_primary->poll_query_until('postgres', $caughtup_query)
|
$node_primary->poll_query_until('postgres', $caughtup_query)
|
||||||
or die "Timed out while waiting for replica 1 to catch up";
|
or die "Timed out while waiting for replica 1 to catch up";
|
||||||
|
|||||||
@@ -99,7 +99,6 @@ for my $i (0 .. $#operators)
|
|||||||
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
||||||
SET client_min_messages = DEBUG;
|
SET client_min_messages = DEBUG;
|
||||||
SET min_parallel_table_scan_size = 1;
|
SET min_parallel_table_scan_size = 1;
|
||||||
SET hnsw.enable_parallel_build = on;
|
|
||||||
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
||||||
));
|
));
|
||||||
is($ret, 0, $stderr);
|
is($ret, 0, $stderr);
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ foreach (@queries)
|
|||||||
test_recall(0.20, $limit, "before vacuum");
|
test_recall(0.20, $limit, "before vacuum");
|
||||||
test_recall(0.95, 100, "before vacuum");
|
test_recall(0.95, 100, "before vacuum");
|
||||||
|
|
||||||
# TODO Test concurrent inserts with vacuum
|
# TODO test concurrent inserts with vacuum
|
||||||
$node->safe_psql("postgres", "VACUUM tst;");
|
$node->safe_psql("postgres", "VACUUM tst;");
|
||||||
|
|
||||||
test_recall(0.95, $limit, "after vacuum");
|
test_recall(0.95, $limit, "after vacuum");
|
||||||
|
|||||||
@@ -1,117 +0,0 @@
|
|||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use PostgresNode;
|
|
||||||
use TestLib;
|
|
||||||
use Test::More;
|
|
||||||
|
|
||||||
my $node;
|
|
||||||
my @queries = ();
|
|
||||||
my @expected;
|
|
||||||
my $limit = 20;
|
|
||||||
|
|
||||||
sub test_recall
|
|
||||||
{
|
|
||||||
my ($probes, $min, $operator) = @_;
|
|
||||||
my $correct = 0;
|
|
||||||
my $total = 0;
|
|
||||||
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
|
||||||
SET enable_seqscan = off;
|
|
||||||
SET ivfflat.probes = $probes;
|
|
||||||
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan using idx on tst/);
|
|
||||||
|
|
||||||
for my $i (0 .. $#queries)
|
|
||||||
{
|
|
||||||
my $actual = $node->safe_psql("postgres", qq(
|
|
||||||
SET enable_seqscan = off;
|
|
||||||
SET ivfflat.probes = $probes;
|
|
||||||
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
|
||||||
));
|
|
||||||
my @actual_ids = split("\n", $actual);
|
|
||||||
my %actual_set = map { $_ => 1 } @actual_ids;
|
|
||||||
|
|
||||||
my @expected_ids = split("\n", $expected[$i]);
|
|
||||||
|
|
||||||
foreach (@expected_ids)
|
|
||||||
{
|
|
||||||
if (exists($actual_set{$_}))
|
|
||||||
{
|
|
||||||
$correct++;
|
|
||||||
}
|
|
||||||
$total++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp_ok($correct / $total, ">=", $min, $operator);
|
|
||||||
}
|
|
||||||
|
|
||||||
# Initialize node
|
|
||||||
$node = get_new_node('node');
|
|
||||||
$node->init;
|
|
||||||
$node->start;
|
|
||||||
|
|
||||||
# Create table
|
|
||||||
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
|
||||||
$node->safe_psql("postgres", "CREATE TABLE tst (i serial, v vector(3));");
|
|
||||||
|
|
||||||
# Generate queries
|
|
||||||
for (1 .. 20)
|
|
||||||
{
|
|
||||||
my $r1 = rand();
|
|
||||||
my $r2 = rand();
|
|
||||||
my $r3 = rand();
|
|
||||||
push(@queries, "[$r1,$r2,$r3]");
|
|
||||||
}
|
|
||||||
|
|
||||||
# Check each index type
|
|
||||||
my @operators = ("<->", "<#>", "<=>");
|
|
||||||
my @opclasses = ("vector_l2_ops", "vector_ip_ops", "vector_cosine_ops");
|
|
||||||
|
|
||||||
for my $i (0 .. $#operators)
|
|
||||||
{
|
|
||||||
my $operator = $operators[$i];
|
|
||||||
my $opclass = $opclasses[$i];
|
|
||||||
|
|
||||||
# Add index
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING ivfflat (v $opclass);");
|
|
||||||
|
|
||||||
# Use concurrent inserts
|
|
||||||
$node->pgbench(
|
|
||||||
"--no-vacuum --client=10 --transactions=1000",
|
|
||||||
0,
|
|
||||||
[qr{actually processed}],
|
|
||||||
[qr{^$}],
|
|
||||||
"concurrent INSERTs",
|
|
||||||
{
|
|
||||||
"017_ivfflat_insert_recall_$opclass" => "INSERT INTO tst (v) SELECT ARRAY[random(), random(), random()] FROM generate_series(1, 10) i;"
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
# Get exact results
|
|
||||||
@expected = ();
|
|
||||||
foreach (@queries)
|
|
||||||
{
|
|
||||||
my $res = $node->safe_psql("postgres", qq(
|
|
||||||
SET enable_indexscan = off;
|
|
||||||
SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;
|
|
||||||
));
|
|
||||||
push(@expected, $res);
|
|
||||||
}
|
|
||||||
|
|
||||||
# Test approximate results
|
|
||||||
if ($operator ne "<#>")
|
|
||||||
{
|
|
||||||
# TODO Fix test (uniform random vectors all have similar inner product)
|
|
||||||
test_recall(1, 0.71, $operator);
|
|
||||||
test_recall(10, 0.95, $operator);
|
|
||||||
}
|
|
||||||
# Account for equal distances
|
|
||||||
test_recall(100, 0.9925, $operator);
|
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
|
||||||
$node->safe_psql("postgres", "TRUNCATE tst;");
|
|
||||||
}
|
|
||||||
|
|
||||||
done_testing();
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use PostgresNode;
|
|
||||||
use TestLib;
|
|
||||||
use Test::More;
|
|
||||||
|
|
||||||
# Initialize node
|
|
||||||
my $node = get_new_node('node');
|
|
||||||
$node->init;
|
|
||||||
$node->start;
|
|
||||||
|
|
||||||
# Create table and index
|
|
||||||
$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;"
|
|
||||||
);
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v vector_l2_ops) WITH (lists = 10);");
|
|
||||||
|
|
||||||
# Test limit
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 100;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit with probes
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
SET ivfflat.probes = 2;
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 200;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit + offset
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 90 OFFSET 10;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit > expected tuples
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 101;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test limit > expected tuples with probes
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
SET ivfflat.probes = 2;
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 201;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test limit + offset > expected tuples
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 91 OFFSET 10;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test no limit
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]';
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
done_testing();
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
use strict;
|
|
||||||
use warnings;
|
|
||||||
use PostgresNode;
|
|
||||||
use TestLib;
|
|
||||||
use Test::More;
|
|
||||||
|
|
||||||
# Initialize node
|
|
||||||
my $node = get_new_node('node');
|
|
||||||
$node->init;
|
|
||||||
$node->start;
|
|
||||||
|
|
||||||
# Create table and index
|
|
||||||
$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;"
|
|
||||||
);
|
|
||||||
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v vector_l2_ops);");
|
|
||||||
|
|
||||||
# Test limit
|
|
||||||
my $explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 40;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit with CTE
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE WITH cte AS (SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 40) SELECT * FROM cte;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit + offset
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 30 OFFSET 10;
|
|
||||||
));
|
|
||||||
like($explain, qr/Index Scan/);
|
|
||||||
|
|
||||||
# Test limit > ef_search
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 41;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test limit > ef_search with CTE
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE WITH cte AS (SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 41) SELECT * FROM cte;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test limit + offset > ef_search
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]' LIMIT 31 OFFSET 10;
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
# Test no limit
|
|
||||||
$explain = $node->safe_psql("postgres", qq(
|
|
||||||
EXPLAIN ANALYZE SELECT * FROM tst ORDER BY v <-> '[1,2,3]';
|
|
||||||
));
|
|
||||||
like($explain, qr/Seq Scan/);
|
|
||||||
|
|
||||||
done_testing();
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
comment = 'vector data type and ivfflat and hnsw access methods'
|
comment = 'vector data type and ivfflat access method'
|
||||||
default_version = '0.5.1'
|
default_version = '0.5.0'
|
||||||
module_pathname = '$libdir/vector'
|
module_pathname = '$libdir/vector'
|
||||||
relocatable = true
|
relocatable = true
|
||||||
|
|||||||
Reference in New Issue
Block a user