mirror of
https://github.com/pgvector/pgvector.git
synced 2026-07-22 20:15:46 +08:00
Compare commits
1 Commits
external
...
hnsw-datum
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f858705293 |
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
|
||||||
|
|||||||
@@ -1,7 +1,3 @@
|
|||||||
## 0.5.2 (unreleased)
|
|
||||||
|
|
||||||
- Added support for on-disk parallel index builds for HNSW
|
|
||||||
|
|
||||||
## 0.5.1 (2023-10-10)
|
## 0.5.1 (2023-10-10)
|
||||||
|
|
||||||
- Improved performance of HNSW index builds
|
- Improved performance of HNSW index builds
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
105
README.md
105
README.md
@@ -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
|
||||||
|
|
||||||
@@ -215,23 +215,6 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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 * tuples_done / nullif(tuples_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;
|
|
||||||
```
|
|
||||||
|
|
||||||
The phases for IVFFlat are:
|
|
||||||
|
|
||||||
1. `initializing`
|
|
||||||
2. `performing k-means`
|
|
||||||
3. `assigning tuples`
|
|
||||||
4. `loading tuples`
|
|
||||||
|
|
||||||
Note: `%` is only populated during the `loading tuples` phase
|
|
||||||
|
|
||||||
## HNSW
|
## HNSW
|
||||||
|
|
||||||
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.
|
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.
|
||||||
@@ -288,18 +271,22 @@ SELECT ...
|
|||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Indexing Progress
|
## 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 * blocks_done / nullif(blocks_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 HNSW are:
|
The phases are:
|
||||||
|
|
||||||
1. `initializing`
|
1. `initializing`
|
||||||
2. `loading tuples`
|
2. `performing k-means` - IVFFlat only
|
||||||
|
3. `assigning tuples` - IVFFlat only
|
||||||
|
4. `loading tuples`
|
||||||
|
|
||||||
|
Note: `tuples_done` and `tuples_total` are only populated during the `loading tuples` phase
|
||||||
|
|
||||||
## Filtering
|
## Filtering
|
||||||
|
|
||||||
@@ -330,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.
|
||||||
@@ -375,7 +360,6 @@ 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# | [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)
|
||||||
@@ -383,11 +367,10 @@ 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)
|
||||||
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)
|
||||||
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)
|
||||||
@@ -395,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
|
||||||
|
|
||||||
@@ -411,55 +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;
|
|
||||||
```
|
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
#### Why isn’t a query using an index?
|
#### Why isn’t a query using an index?
|
||||||
@@ -473,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:
|
||||||
@@ -664,7 +595,7 @@ 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. Then in each database you want to upgrade, run:
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
ALTER EXTENSION vector UPDATE;
|
ALTER EXTENSION vector UPDATE;
|
||||||
@@ -678,16 +609,6 @@ SELECT extversion FROM pg_extension WHERE extname = 'vector';
|
|||||||
|
|
||||||
## Upgrade Notes
|
## Upgrade Notes
|
||||||
|
|
||||||
### 0.6.0
|
|
||||||
|
|
||||||
If upgrading with Postgres < 13, remove this line from `sql/vector--0.5.1--0.6.0.sql`:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
ALTER TYPE vector SET (STORAGE = external);
|
|
||||||
```
|
|
||||||
|
|
||||||
Then run `make install` and `ALTER EXTENSION vector UPDATE;`.
|
|
||||||
|
|
||||||
### 0.4.0
|
### 0.4.0
|
||||||
|
|
||||||
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
|
If upgrading with Postgres < 13, remove this line from `sql/vector--0.3.2--0.4.0.sql`:
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
-- complain if script is sourced in psql, rather than via CREATE EXTENSION
|
|
||||||
\echo Use "ALTER EXTENSION vector UPDATE TO '0.6.0'" to load this file. \quit
|
|
||||||
|
|
||||||
-- remove this single line for Postgres < 13
|
|
||||||
ALTER TYPE vector SET (STORAGE = external);
|
|
||||||
@@ -26,7 +26,7 @@ CREATE TYPE vector (
|
|||||||
TYPMOD_IN = vector_typmod_in,
|
TYPMOD_IN = vector_typmod_in,
|
||||||
RECEIVE = vector_recv,
|
RECEIVE = vector_recv,
|
||||||
SEND = vector_send,
|
SEND = vector_send,
|
||||||
STORAGE = external
|
STORAGE = extended
|
||||||
);
|
);
|
||||||
|
|
||||||
-- functions
|
-- functions
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
61
src/hnsw.h
61
src/hnsw.h
@@ -4,7 +4,6 @@
|
|||||||
#include "postgres.h"
|
#include "postgres.h"
|
||||||
|
|
||||||
#include "access/generic_xlog.h"
|
#include "access/generic_xlog.h"
|
||||||
#include "access/parallel.h"
|
|
||||||
#include "access/reloptions.h"
|
#include "access/reloptions.h"
|
||||||
#include "nodes/execnodes.h"
|
#include "nodes/execnodes.h"
|
||||||
#include "port.h" /* for random() */
|
#include "port.h" /* for random() */
|
||||||
@@ -15,10 +14,6 @@
|
|||||||
#error "Requires PostgreSQL 11+"
|
#error "Requires PostgreSQL 11+"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 120000
|
|
||||||
#include "access/relscan.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define HNSW_MAX_DIM 2000
|
#define HNSW_MAX_DIM 2000
|
||||||
|
|
||||||
/* Support functions */
|
/* Support functions */
|
||||||
@@ -64,7 +59,7 @@
|
|||||||
|
|
||||||
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
#define HNSW_MAX_SIZE (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - MAXALIGN(sizeof(HnswPageOpaqueData)) - sizeof(ItemIdData))
|
||||||
|
|
||||||
#define HNSW_ELEMENT_TUPLE_SIZE(size) MAXALIGN(offsetof(HnswElementTupleData, data) + (size))
|
#define HNSW_ELEMENT_TUPLE_SIZE(_datum) MAXALIGN(offsetof(HnswElementTupleData, value) + VARSIZE_ANY(_datum))
|
||||||
#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))
|
||||||
@@ -95,7 +90,6 @@
|
|||||||
|
|
||||||
/* Variables */
|
/* Variables */
|
||||||
extern int hnsw_ef_search;
|
extern int hnsw_ef_search;
|
||||||
extern bool hnsw_enable_parallel_build;
|
|
||||||
|
|
||||||
typedef struct HnswNeighborArray HnswNeighborArray;
|
typedef struct HnswNeighborArray HnswNeighborArray;
|
||||||
|
|
||||||
@@ -104,6 +98,7 @@ typedef struct HnswElementData
|
|||||||
List *heaptids;
|
List *heaptids;
|
||||||
uint8 level;
|
uint8 level;
|
||||||
uint8 deleted;
|
uint8 deleted;
|
||||||
|
bool loaded;
|
||||||
HnswNeighborArray *neighbors;
|
HnswNeighborArray *neighbors;
|
||||||
BlockNumber blkno;
|
BlockNumber blkno;
|
||||||
OffsetNumber offno;
|
OffsetNumber offno;
|
||||||
@@ -142,49 +137,6 @@ typedef struct HnswOptions
|
|||||||
int efConstruction; /* size of dynamic candidate list */
|
int efConstruction; /* size of dynamic candidate list */
|
||||||
} HnswOptions;
|
} HnswOptions;
|
||||||
|
|
||||||
typedef struct HnswSpool
|
|
||||||
{
|
|
||||||
Relation heap;
|
|
||||||
Relation index;
|
|
||||||
} HnswSpool;
|
|
||||||
|
|
||||||
typedef struct HnswShared
|
|
||||||
{
|
|
||||||
/* Immutable state */
|
|
||||||
Oid heaprelid;
|
|
||||||
Oid indexrelid;
|
|
||||||
bool isconcurrent;
|
|
||||||
int scantuplesortstates;
|
|
||||||
|
|
||||||
/* Worker progress */
|
|
||||||
ConditionVariable workersdonecv;
|
|
||||||
|
|
||||||
/* Mutex for mutable state */
|
|
||||||
slock_t mutex;
|
|
||||||
|
|
||||||
/* Mutable state */
|
|
||||||
int nparticipantsdone;
|
|
||||||
double reltuples;
|
|
||||||
double indtuples;
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM < 120000
|
|
||||||
ParallelHeapScanDescData heapdesc; /* must come last */
|
|
||||||
#endif
|
|
||||||
} HnswShared;
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
#define ParallelTableScanFromHnswShared(shared) \
|
|
||||||
(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(HnswShared)))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
typedef struct HnswLeader
|
|
||||||
{
|
|
||||||
ParallelContext *pcxt;
|
|
||||||
int nparticipanttuplesorts;
|
|
||||||
HnswShared *hnswshared;
|
|
||||||
Snapshot snapshot;
|
|
||||||
} HnswLeader;
|
|
||||||
|
|
||||||
typedef struct HnswBuildState
|
typedef struct HnswBuildState
|
||||||
{
|
{
|
||||||
/* Info */
|
/* Info */
|
||||||
@@ -212,16 +164,12 @@ typedef struct HnswBuildState
|
|||||||
HnswElement entryPoint;
|
HnswElement entryPoint;
|
||||||
double ml;
|
double ml;
|
||||||
int maxLevel;
|
int maxLevel;
|
||||||
long memoryLeft;
|
double maxInMemoryElements;
|
||||||
bool flushed;
|
bool flushed;
|
||||||
Vector *normvec;
|
Vector *normvec;
|
||||||
|
|
||||||
/* Memory */
|
/* Memory */
|
||||||
MemoryContext tmpCtx;
|
MemoryContext tmpCtx;
|
||||||
|
|
||||||
/* Parallel builds */
|
|
||||||
HnswLeader *hnswleader;
|
|
||||||
HnswShared *hnswshared;
|
|
||||||
} HnswBuildState;
|
} HnswBuildState;
|
||||||
|
|
||||||
typedef struct HnswMetaPageData
|
typedef struct HnswMetaPageData
|
||||||
@@ -257,7 +205,7 @@ typedef struct HnswElementTupleData
|
|||||||
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
ItemPointerData heaptids[HNSW_HEAPTIDS];
|
||||||
ItemPointerData neighbortid;
|
ItemPointerData neighbortid;
|
||||||
uint16 unused2;
|
uint16 unused2;
|
||||||
Vector data;
|
char value[FLEXIBLE_ARRAY_MEMBER];
|
||||||
} HnswElementTupleData;
|
} HnswElementTupleData;
|
||||||
|
|
||||||
typedef HnswElementTupleData * HnswElementTuple;
|
typedef HnswElementTupleData * HnswElementTuple;
|
||||||
@@ -342,7 +290,6 @@ void HnswLoadElement(HnswElement element, float *distance, Datum *q, Relation i
|
|||||||
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, int m);
|
||||||
PGDLLEXPORT void HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc);
|
|
||||||
|
|
||||||
/* Index access methods */
|
/* Index access methods */
|
||||||
IndexBuildResult *hnswbuild(Relation heap, Relation index, IndexInfo *indexInfo);
|
IndexBuildResult *hnswbuild(Relation heap, Relation index, IndexInfo *indexInfo);
|
||||||
|
|||||||
479
src/hnswbuild.c
479
src/hnswbuild.c
@@ -2,15 +2,12 @@
|
|||||||
|
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
#include "access/parallel.h"
|
|
||||||
#include "access/xact.h"
|
|
||||||
#include "catalog/index.h"
|
#include "catalog/index.h"
|
||||||
#include "hnsw.h"
|
#include "hnsw.h"
|
||||||
#include "miscadmin.h"
|
#include "miscadmin.h"
|
||||||
#include "lib/pairingheap.h"
|
#include "lib/pairingheap.h"
|
||||||
#include "nodes/pg_list.h"
|
#include "nodes/pg_list.h"
|
||||||
#include "storage/bufmgr.h"
|
#include "storage/bufmgr.h"
|
||||||
#include "tcop/tcopprot.h"
|
|
||||||
#include "utils/datum.h"
|
#include "utils/datum.h"
|
||||||
#include "utils/memutils.h"
|
#include "utils/memutils.h"
|
||||||
|
|
||||||
@@ -39,23 +36,6 @@
|
|||||||
#define UpdateProgress(index, val) ((void)val)
|
#define UpdateProgress(index, val) ((void)val)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 140000
|
|
||||||
#include "utils/backend_status.h"
|
|
||||||
#include "utils/wait_event.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
#include "access/table.h"
|
|
||||||
#include "optimizer/optimizer.h"
|
|
||||||
#else
|
|
||||||
#include "access/heapam.h"
|
|
||||||
#include "optimizer/planner.h"
|
|
||||||
#include "pgstat.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define PARALLEL_KEY_HNSW_SHARED UINT64CONST(0xA000000000000001)
|
|
||||||
#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000002)
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Create the metapage
|
* Create the metapage
|
||||||
*/
|
*/
|
||||||
@@ -126,7 +106,6 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
{
|
{
|
||||||
Relation index = buildstate->index;
|
Relation index = buildstate->index;
|
||||||
ForkNumber forkNum = buildstate->forkNum;
|
ForkNumber forkNum = buildstate->forkNum;
|
||||||
Size etupAllocSize;
|
|
||||||
Size maxSize;
|
Size maxSize;
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
HnswNeighborTuple ntup;
|
HnswNeighborTuple ntup;
|
||||||
@@ -137,11 +116,10 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
ListCell *lc;
|
ListCell *lc;
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupAllocSize = BLCKSZ;
|
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = HNSW_MAX_SIZE;
|
||||||
|
|
||||||
/* Allocate once */
|
/* Allocate once */
|
||||||
etup = palloc0(etupAllocSize);
|
etup = palloc0(BLCKSZ);
|
||||||
ntup = palloc0(BLCKSZ);
|
ntup = palloc0(BLCKSZ);
|
||||||
|
|
||||||
/* Prepare first page */
|
/* Prepare first page */
|
||||||
@@ -157,20 +135,13 @@ CreateElementPages(HnswBuildState * buildstate)
|
|||||||
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)));
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(element->value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(element->level, buildstate->m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
|
|
||||||
/* 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, &state, forkNum);
|
HnswBuildAppendPage(index, &buf, &page, &state, forkNum);
|
||||||
@@ -293,30 +264,24 @@ FlushPages(HnswBuildState * buildstate)
|
|||||||
* Insert tuple
|
* Insert tuple
|
||||||
*/
|
*/
|
||||||
static bool
|
static bool
|
||||||
InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState * buildstate, HnswElement * dup, MemoryContext outerCtx)
|
InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState * buildstate, HnswElement * dup)
|
||||||
{
|
{
|
||||||
FmgrInfo *procinfo = buildstate->procinfo;
|
FmgrInfo *procinfo = buildstate->procinfo;
|
||||||
Oid collation = buildstate->collation;
|
Oid collation = buildstate->collation;
|
||||||
HnswElement entryPoint = buildstate->entryPoint;
|
HnswElement entryPoint = buildstate->entryPoint;
|
||||||
int efConstruction = buildstate->efConstruction;
|
int efConstruction = buildstate->efConstruction;
|
||||||
int m = buildstate->m;
|
int m = buildstate->m;
|
||||||
MemoryContext oldCtx;
|
|
||||||
|
|
||||||
/* Detoast once for all calls */
|
/* Detoast once for all calls */
|
||||||
Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
element->value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
|
||||||
|
|
||||||
/* Normalize if needed */
|
/* Normalize if needed */
|
||||||
if (buildstate->normprocinfo != NULL)
|
if (buildstate->normprocinfo != NULL)
|
||||||
{
|
{
|
||||||
if (!HnswNormValue(buildstate->normprocinfo, collation, &value, buildstate->normvec))
|
if (!HnswNormValue(buildstate->normprocinfo, collation, &element->value, buildstate->normvec))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Copy value to element so accessible outside of memory context */
|
|
||||||
oldCtx = MemoryContextSwitchTo(outerCtx);
|
|
||||||
element->value = datumCopy(value, false, -1);
|
|
||||||
MemoryContextSwitchTo(oldCtx);
|
|
||||||
|
|
||||||
/* 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);
|
||||||
|
|
||||||
@@ -345,21 +310,6 @@ InsertTuple(Relation index, Datum *values, HnswElement element, HnswBuildState *
|
|||||||
return *dup == NULL;
|
return *dup == NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Get the memory used by an element
|
|
||||||
*/
|
|
||||||
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 += sizeof(ItemPointerData);
|
|
||||||
elementSize += VARSIZE_ANY(DatumGetPointer(e->value));
|
|
||||||
return elementSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Callback for table_index_build_scan
|
* Callback for table_index_build_scan
|
||||||
*/
|
*/
|
||||||
@@ -381,7 +331,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
if (isnull[0])
|
if (isnull[0])
|
||||||
return;
|
return;
|
||||||
|
|
||||||
if (buildstate->memoryLeft <= 0)
|
if (buildstate->indtuples >= buildstate->maxInMemoryElements)
|
||||||
{
|
{
|
||||||
if (!buildstate->flushed)
|
if (!buildstate->flushed)
|
||||||
{
|
{
|
||||||
@@ -396,18 +346,7 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
|
|
||||||
if (HnswInsertTuple(buildstate->index, values, isnull, tid, buildstate->heap))
|
if (HnswInsertTuple(buildstate->index, values, isnull, tid, buildstate->heap))
|
||||||
{
|
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
||||||
if (buildstate->hnswshared)
|
|
||||||
{
|
|
||||||
HnswShared *hnswshared = buildstate->hnswshared;
|
|
||||||
|
|
||||||
SpinLockAcquire(&hnswshared->mutex);
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++hnswshared->indtuples);
|
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_TUPLES_DONE, ++buildstate->indtuples);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Reset memory context */
|
/* Reset memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
@@ -423,27 +362,44 @@ BuildCallback(Relation index, CALLBACK_ITEM_POINTER, Datum *values,
|
|||||||
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx);
|
||||||
|
|
||||||
/* Insert tuple */
|
/* Insert tuple */
|
||||||
inserted = InsertTuple(index, values, element, buildstate, &dup, oldCtx);
|
inserted = InsertTuple(index, values, element, buildstate, &dup);
|
||||||
|
|
||||||
/* Reset memory context */
|
/* Switch memory context */
|
||||||
MemoryContextSwitchTo(oldCtx);
|
MemoryContextSwitchTo(oldCtx);
|
||||||
MemoryContextReset(buildstate->tmpCtx);
|
|
||||||
|
|
||||||
/* Add outside memory context */
|
/* Add outside memory context */
|
||||||
if (dup != NULL)
|
if (dup != NULL)
|
||||||
{
|
|
||||||
HnswAddHeapTid(dup, tid);
|
HnswAddHeapTid(dup, tid);
|
||||||
buildstate->memoryLeft -= sizeof(ItemPointerData);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Add to buildstate or free */
|
/* Add to buildstate or free */
|
||||||
if (inserted)
|
if (inserted)
|
||||||
{
|
{
|
||||||
|
element->value = datumCopy(element->value, false, -1);
|
||||||
|
element->loaded = true;
|
||||||
buildstate->elements = lappend(buildstate->elements, element);
|
buildstate->elements = lappend(buildstate->elements, element);
|
||||||
buildstate->memoryLeft -= HnswElementMemory(element, buildstate->m);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
HnswFreeElement(element);
|
HnswFreeElement(element);
|
||||||
|
|
||||||
|
/* Reset memory context */
|
||||||
|
MemoryContextReset(buildstate->tmpCtx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Get the max number of elements that fit into maintenance_work_mem
|
||||||
|
*/
|
||||||
|
static double
|
||||||
|
HnswGetMaxInMemoryElements(int m, double ml, int dimensions)
|
||||||
|
{
|
||||||
|
Size elementSize = sizeof(HnswElementData);
|
||||||
|
double avgLevel = -log(0.5) * ml;
|
||||||
|
|
||||||
|
elementSize += sizeof(HnswNeighborArray) * (avgLevel + 1);
|
||||||
|
elementSize += sizeof(HnswCandidate) * (m * (avgLevel + 2));
|
||||||
|
elementSize += sizeof(ItemPointerData);
|
||||||
|
/* TODO Handle non-vector types */
|
||||||
|
elementSize += VECTOR_SIZE(dimensions);
|
||||||
|
return (maintenance_work_mem * 1024L) / elementSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -461,10 +417,6 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
buildstate->efConstruction = HnswGetEfConstruction(index);
|
buildstate->efConstruction = HnswGetEfConstruction(index);
|
||||||
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
buildstate->dimensions = TupleDescAttr(index->rd_att, 0)->atttypmod;
|
||||||
|
|
||||||
/* Require column to have dimensions to be indexed */
|
|
||||||
if (buildstate->dimensions < 0)
|
|
||||||
elog(ERROR, "column does not have dimensions");
|
|
||||||
|
|
||||||
if (buildstate->dimensions > HNSW_MAX_DIM)
|
if (buildstate->dimensions > HNSW_MAX_DIM)
|
||||||
elog(ERROR, "column cannot have more than %d dimensions for hnsw index", HNSW_MAX_DIM);
|
elog(ERROR, "column cannot have more than %d dimensions for hnsw index", HNSW_MAX_DIM);
|
||||||
|
|
||||||
@@ -483,18 +435,16 @@ InitBuildState(HnswBuildState * buildstate, Relation heap, Relation index, Index
|
|||||||
buildstate->entryPoint = NULL;
|
buildstate->entryPoint = NULL;
|
||||||
buildstate->ml = HnswGetMl(buildstate->m);
|
buildstate->ml = HnswGetMl(buildstate->m);
|
||||||
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
buildstate->maxLevel = HnswGetMaxLevel(buildstate->m);
|
||||||
buildstate->memoryLeft = maintenance_work_mem * 1024L;
|
buildstate->maxInMemoryElements = HnswGetMaxInMemoryElements(buildstate->m, buildstate->ml, buildstate->dimensions);
|
||||||
buildstate->flushed = false;
|
buildstate->flushed = false;
|
||||||
|
|
||||||
/* Reuse for each tuple */
|
/* Reuse for each tuple */
|
||||||
|
/* TODO Fix / replace with support function */
|
||||||
buildstate->normvec = InitVector(buildstate->dimensions);
|
buildstate->normvec = InitVector(buildstate->dimensions);
|
||||||
|
|
||||||
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->hnswshared = NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -507,374 +457,21 @@ FreeBuildState(HnswBuildState * buildstate)
|
|||||||
MemoryContextDelete(buildstate->tmpCtx);
|
MemoryContextDelete(buildstate->tmpCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
|
||||||
* Within leader, wait for end of heap scan
|
|
||||||
*/
|
|
||||||
static double
|
|
||||||
ParallelHeapScan(HnswBuildState * buildstate)
|
|
||||||
{
|
|
||||||
HnswShared *hnswshared = buildstate->hnswleader->hnswshared;
|
|
||||||
int nparticipanttuplesorts;
|
|
||||||
double reltuples;
|
|
||||||
|
|
||||||
nparticipanttuplesorts = buildstate->hnswleader->nparticipanttuplesorts;
|
|
||||||
for (;;)
|
|
||||||
{
|
|
||||||
SpinLockAcquire(&hnswshared->mutex);
|
|
||||||
if (hnswshared->nparticipantsdone == nparticipanttuplesorts)
|
|
||||||
{
|
|
||||||
buildstate->indtuples = hnswshared->indtuples;
|
|
||||||
reltuples = hnswshared->reltuples;
|
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
|
||||||
|
|
||||||
ConditionVariableSleep(&hnswshared->workersdonecv,
|
|
||||||
WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN);
|
|
||||||
}
|
|
||||||
|
|
||||||
ConditionVariableCancelSleep();
|
|
||||||
|
|
||||||
return reltuples;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Perform a worker's portion of a parallel insert
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
HnswParallelScanAndInsert(HnswSpool * hnswspool, HnswShared * hnswshared, bool progress)
|
|
||||||
{
|
|
||||||
HnswBuildState buildstate;
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
TableScanDesc scan;
|
|
||||||
#else
|
|
||||||
HeapScanDesc scan;
|
|
||||||
#endif
|
|
||||||
double reltuples;
|
|
||||||
IndexInfo *indexInfo;
|
|
||||||
|
|
||||||
/* Join parallel scan */
|
|
||||||
indexInfo = BuildIndexInfo(hnswspool->index);
|
|
||||||
indexInfo->ii_Concurrent = hnswshared->isconcurrent;
|
|
||||||
InitBuildState(&buildstate, hnswspool->heap, hnswspool->index, indexInfo, MAIN_FORKNUM);
|
|
||||||
/* TODO Support in-memory builds */
|
|
||||||
buildstate.memoryLeft = 0;
|
|
||||||
buildstate.flushed = true;
|
|
||||||
buildstate.hnswshared = hnswshared;
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
scan = table_beginscan_parallel(hnswspool->heap,
|
|
||||||
ParallelTableScanFromHnswShared(hnswshared));
|
|
||||||
reltuples = table_index_build_scan(hnswspool->heap, hnswspool->index, indexInfo,
|
|
||||||
true, progress, BuildCallback,
|
|
||||||
(void *) &buildstate, scan);
|
|
||||||
#else
|
|
||||||
scan = heap_beginscan_parallel(hnswspool->heap, &hnswshared->heapdesc);
|
|
||||||
reltuples = IndexBuildHeapScan(hnswspool->heap, hnswspool->index, indexInfo,
|
|
||||||
true, BuildCallback,
|
|
||||||
(void *) &buildstate, scan);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Record statistics */
|
|
||||||
SpinLockAcquire(&hnswshared->mutex);
|
|
||||||
hnswshared->nparticipantsdone++;
|
|
||||||
hnswshared->reltuples += reltuples;
|
|
||||||
SpinLockRelease(&hnswshared->mutex);
|
|
||||||
|
|
||||||
/* Log statistics */
|
|
||||||
if (progress)
|
|
||||||
ereport(DEBUG1, (errmsg("leader processed " INT64_FORMAT " tuples", (int64) reltuples)));
|
|
||||||
else
|
|
||||||
ereport(DEBUG1, (errmsg("worker processed " INT64_FORMAT " tuples", (int64) reltuples)));
|
|
||||||
|
|
||||||
/* Notify leader */
|
|
||||||
ConditionVariableSignal(&hnswshared->workersdonecv);
|
|
||||||
|
|
||||||
FreeBuildState(&buildstate);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Perform work within a launched parallel process
|
|
||||||
*/
|
|
||||||
void
|
|
||||||
HnswParallelBuildMain(dsm_segment *seg, shm_toc *toc)
|
|
||||||
{
|
|
||||||
char *sharedquery;
|
|
||||||
HnswSpool *hnswspool;
|
|
||||||
HnswShared *hnswshared;
|
|
||||||
Relation heapRel;
|
|
||||||
Relation indexRel;
|
|
||||||
LOCKMODE heapLockmode;
|
|
||||||
LOCKMODE indexLockmode;
|
|
||||||
|
|
||||||
/* Set debug_query_string for individual workers first */
|
|
||||||
sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
|
|
||||||
debug_query_string = sharedquery;
|
|
||||||
|
|
||||||
/* Report the query string from leader */
|
|
||||||
pgstat_report_activity(STATE_RUNNING, debug_query_string);
|
|
||||||
|
|
||||||
/* Look up shared state */
|
|
||||||
hnswshared = shm_toc_lookup(toc, PARALLEL_KEY_HNSW_SHARED, false);
|
|
||||||
|
|
||||||
/* Open relations using lock modes known to be obtained by index.c */
|
|
||||||
if (!hnswshared->isconcurrent)
|
|
||||||
{
|
|
||||||
heapLockmode = ShareLock;
|
|
||||||
indexLockmode = AccessExclusiveLock;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
heapLockmode = ShareUpdateExclusiveLock;
|
|
||||||
indexLockmode = RowExclusiveLock;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Open relations within worker */
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
heapRel = table_open(hnswshared->heaprelid, heapLockmode);
|
|
||||||
#else
|
|
||||||
heapRel = heap_open(hnswshared->heaprelid, heapLockmode);
|
|
||||||
#endif
|
|
||||||
indexRel = index_open(hnswshared->indexrelid, indexLockmode);
|
|
||||||
|
|
||||||
/* Initialize worker's own spool */
|
|
||||||
hnswspool = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
|
||||||
hnswspool->heap = heapRel;
|
|
||||||
hnswspool->index = indexRel;
|
|
||||||
|
|
||||||
/* Perform inserts */
|
|
||||||
HnswParallelScanAndInsert(hnswspool, hnswshared, false);
|
|
||||||
|
|
||||||
/* Close relations within worker */
|
|
||||||
index_close(indexRel, indexLockmode);
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
table_close(heapRel, heapLockmode);
|
|
||||||
#else
|
|
||||||
heap_close(heapRel, heapLockmode);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* End parallel build
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
HnswEndParallel(HnswLeader * hnswleader)
|
|
||||||
{
|
|
||||||
/* Shutdown worker processes */
|
|
||||||
WaitForParallelWorkersToFinish(hnswleader->pcxt);
|
|
||||||
|
|
||||||
/* Free last reference to MVCC snapshot, if one was used */
|
|
||||||
if (IsMVCCSnapshot(hnswleader->snapshot))
|
|
||||||
UnregisterSnapshot(hnswleader->snapshot);
|
|
||||||
DestroyParallelContext(hnswleader->pcxt);
|
|
||||||
ExitParallelMode();
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Return size of shared memory required for parallel index build
|
|
||||||
*/
|
|
||||||
static Size
|
|
||||||
ParallelEstimateShared(Relation heap, Snapshot snapshot)
|
|
||||||
{
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
return add_size(BUFFERALIGN(sizeof(HnswShared)), table_parallelscan_estimate(heap, snapshot));
|
|
||||||
#else
|
|
||||||
if (!IsMVCCSnapshot(snapshot))
|
|
||||||
{
|
|
||||||
Assert(snapshot == SnapshotAny);
|
|
||||||
return sizeof(HnswShared);
|
|
||||||
}
|
|
||||||
|
|
||||||
return add_size(offsetof(HnswShared, heapdesc) +
|
|
||||||
offsetof(ParallelHeapScanDescData, phs_snapshot_data),
|
|
||||||
EstimateSnapshotSpace(snapshot));
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Within leader, participate as a parallel worker
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
HnswLeaderParticipateAsWorker(HnswBuildState * buildstate)
|
|
||||||
{
|
|
||||||
HnswLeader *hnswleader = buildstate->hnswleader;
|
|
||||||
HnswSpool *leaderworker;
|
|
||||||
|
|
||||||
/* Allocate memory and initialize private spool */
|
|
||||||
leaderworker = (HnswSpool *) palloc0(sizeof(HnswSpool));
|
|
||||||
leaderworker->heap = buildstate->heap;
|
|
||||||
leaderworker->index = buildstate->index;
|
|
||||||
|
|
||||||
/* Perform work common to all participants */
|
|
||||||
HnswParallelScanAndInsert(leaderworker, hnswleader->hnswshared, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Begin parallel build
|
|
||||||
*/
|
|
||||||
static void
|
|
||||||
HnswBeginParallel(HnswBuildState * buildstate, bool isconcurrent, int request)
|
|
||||||
{
|
|
||||||
ParallelContext *pcxt;
|
|
||||||
int scantuplesortstates;
|
|
||||||
Snapshot snapshot;
|
|
||||||
Size esthnswshared;
|
|
||||||
HnswShared *hnswshared;
|
|
||||||
HnswLeader *hnswleader = (HnswLeader *) palloc0(sizeof(HnswLeader));
|
|
||||||
bool leaderparticipates = true;
|
|
||||||
int querylen;
|
|
||||||
|
|
||||||
#ifdef DISABLE_LEADER_PARTICIPATION
|
|
||||||
leaderparticipates = false;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Enter parallel mode and create context */
|
|
||||||
EnterParallelMode();
|
|
||||||
Assert(request > 0);
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request);
|
|
||||||
#else
|
|
||||||
pcxt = CreateParallelContext("vector", "HnswParallelBuildMain", request, true);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
scantuplesortstates = leaderparticipates ? request + 1 : request;
|
|
||||||
|
|
||||||
/* Get snapshot for table scan */
|
|
||||||
if (!isconcurrent)
|
|
||||||
snapshot = SnapshotAny;
|
|
||||||
else
|
|
||||||
snapshot = RegisterSnapshot(GetTransactionSnapshot());
|
|
||||||
|
|
||||||
/* Estimate size of workspaces */
|
|
||||||
esthnswshared = ParallelEstimateShared(buildstate->heap, snapshot);
|
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, esthnswshared);
|
|
||||||
shm_toc_estimate_keys(&pcxt->estimator, 1);
|
|
||||||
|
|
||||||
/* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
|
|
||||||
if (debug_query_string)
|
|
||||||
{
|
|
||||||
querylen = strlen(debug_query_string);
|
|
||||||
shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
|
|
||||||
shm_toc_estimate_keys(&pcxt->estimator, 1);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
querylen = 0; /* keep compiler quiet */
|
|
||||||
|
|
||||||
/* Everyone's had a chance to ask for space, so now create the DSM */
|
|
||||||
InitializeParallelDSM(pcxt);
|
|
||||||
|
|
||||||
/* If no DSM segment was available, back out (do serial build) */
|
|
||||||
if (pcxt->seg == NULL)
|
|
||||||
{
|
|
||||||
if (IsMVCCSnapshot(snapshot))
|
|
||||||
UnregisterSnapshot(snapshot);
|
|
||||||
DestroyParallelContext(pcxt);
|
|
||||||
ExitParallelMode();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Store shared build state, for which we reserved space */
|
|
||||||
hnswshared = (HnswShared *) shm_toc_allocate(pcxt->toc, esthnswshared);
|
|
||||||
/* Initialize immutable state */
|
|
||||||
hnswshared->heaprelid = RelationGetRelid(buildstate->heap);
|
|
||||||
hnswshared->indexrelid = RelationGetRelid(buildstate->index);
|
|
||||||
hnswshared->isconcurrent = isconcurrent;
|
|
||||||
hnswshared->scantuplesortstates = scantuplesortstates;
|
|
||||||
ConditionVariableInit(&hnswshared->workersdonecv);
|
|
||||||
SpinLockInit(&hnswshared->mutex);
|
|
||||||
/* Initialize mutable state */
|
|
||||||
hnswshared->nparticipantsdone = 0;
|
|
||||||
hnswshared->reltuples = 0;
|
|
||||||
hnswshared->indtuples = 0;
|
|
||||||
#if PG_VERSION_NUM >= 120000
|
|
||||||
table_parallelscan_initialize(buildstate->heap,
|
|
||||||
ParallelTableScanFromHnswShared(hnswshared),
|
|
||||||
snapshot);
|
|
||||||
#else
|
|
||||||
heap_parallelscan_initialize(&hnswshared->heapdesc, buildstate->heap, snapshot);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_HNSW_SHARED, hnswshared);
|
|
||||||
|
|
||||||
/* Store query string for workers */
|
|
||||||
if (debug_query_string)
|
|
||||||
{
|
|
||||||
char *sharedquery;
|
|
||||||
|
|
||||||
sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
|
|
||||||
memcpy(sharedquery, debug_query_string, querylen + 1);
|
|
||||||
shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Launch workers, saving status for leader/caller */
|
|
||||||
LaunchParallelWorkers(pcxt);
|
|
||||||
hnswleader->pcxt = pcxt;
|
|
||||||
hnswleader->nparticipanttuplesorts = pcxt->nworkers_launched;
|
|
||||||
if (leaderparticipates)
|
|
||||||
hnswleader->nparticipanttuplesorts++;
|
|
||||||
hnswleader->hnswshared = hnswshared;
|
|
||||||
hnswleader->snapshot = snapshot;
|
|
||||||
|
|
||||||
/* If no workers were successfully launched, back out (do serial build) */
|
|
||||||
if (pcxt->nworkers_launched == 0)
|
|
||||||
{
|
|
||||||
HnswEndParallel(hnswleader);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Log participants */
|
|
||||||
ereport(DEBUG1, (errmsg("using %d parallel workers", pcxt->nworkers_launched)));
|
|
||||||
|
|
||||||
/* Save leader state now that it's clear build will be parallel */
|
|
||||||
buildstate->hnswleader = hnswleader;
|
|
||||||
|
|
||||||
/* Join heap scan ourselves */
|
|
||||||
if (leaderparticipates)
|
|
||||||
HnswLeaderParticipateAsWorker(buildstate);
|
|
||||||
|
|
||||||
/* Wait for all launched workers */
|
|
||||||
WaitForParallelWorkersToAttach(pcxt);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Build graph
|
* Build graph
|
||||||
*/
|
*/
|
||||||
static void
|
static void
|
||||||
BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
BuildGraph(HnswBuildState * buildstate, ForkNumber forkNum)
|
||||||
{
|
{
|
||||||
int parallel_workers = 0;
|
|
||||||
|
|
||||||
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
UpdateProgress(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_HNSW_PHASE_LOAD);
|
||||||
|
|
||||||
/* Calculate parallel workers */
|
|
||||||
if (hnsw_enable_parallel_build)
|
|
||||||
parallel_workers = plan_create_index_workers(RelationGetRelid(buildstate->heap), RelationGetRelid(buildstate->index));
|
|
||||||
|
|
||||||
/* Attempt to launch parallel worker scan when required */
|
|
||||||
if (parallel_workers > 0)
|
|
||||||
{
|
|
||||||
/* TODO Support in-memory builds */
|
|
||||||
FlushPages(buildstate);
|
|
||||||
HnswBeginParallel(buildstate, buildstate->indexInfo->ii_Concurrent, parallel_workers);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Add tuples to sort */
|
|
||||||
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
|
||||||
}
|
|
||||||
|
|
||||||
/* End parallel build */
|
|
||||||
if (buildstate->hnswleader)
|
|
||||||
HnswEndParallel(buildstate->hnswleader);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ 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(e->value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(e->level, m);
|
||||||
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
combinedSize = etupSize + ntupSize + sizeof(ItemIdData);
|
||||||
maxSize = HNSW_MAX_SIZE;
|
maxSize = HNSW_MAX_SIZE;
|
||||||
@@ -404,9 +404,8 @@ 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->value);
|
||||||
HnswElementTuple etup;
|
HnswElementTuple etup;
|
||||||
Size etupSize;
|
|
||||||
int i;
|
int i;
|
||||||
|
|
||||||
/* Read page */
|
/* Read page */
|
||||||
@@ -416,9 +415,7 @@ HnswAddDuplicate(Relation index, HnswElement element, HnswElement dup)
|
|||||||
page = GenericXLogRegisterBuffer(state, buf, 0);
|
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]))
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ HnswFreeElement(HnswElement element)
|
|||||||
{
|
{
|
||||||
HnswFreeNeighbors(element);
|
HnswFreeNeighbors(element);
|
||||||
list_free_deep(element->heaptids);
|
list_free_deep(element->heaptids);
|
||||||
if (DatumGetPointer(element->value))
|
if (element->loaded)
|
||||||
pfree(DatumGetPointer(element->value));
|
pfree(DatumGetPointer(element->value));
|
||||||
pfree(element);
|
pfree(element);
|
||||||
}
|
}
|
||||||
@@ -216,7 +216,7 @@ HnswInitElementFromBlock(BlockNumber blkno, OffsetNumber offno)
|
|||||||
element->blkno = blkno;
|
element->blkno = blkno;
|
||||||
element->offno = offno;
|
element->offno = offno;
|
||||||
element->neighbors = NULL;
|
element->neighbors = NULL;
|
||||||
element->value = PointerGetDatum(NULL);
|
element->loaded = false;
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,7 +326,7 @@ HnswSetElementTuple(HnswElementTuple etup, HnswElement element)
|
|||||||
else
|
else
|
||||||
ItemPointerSetInvalid(&etup->heaptids[i]);
|
ItemPointerSetInvalid(&etup->heaptids[i]);
|
||||||
}
|
}
|
||||||
memcpy(&etup->data, DatumGetPointer(element->value), VARSIZE_ANY(DatumGetPointer(element->value)));
|
memcpy(&etup->value, DatumGetPointer(element->value), VARSIZE_ANY(element->value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -448,7 +448,12 @@ HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHe
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (loadVec)
|
if (loadVec)
|
||||||
element->value = datumCopy(PointerGetDatum(&etup->data), false, -1);
|
{
|
||||||
|
Datum value = PointerGetDatum(&etup->value);
|
||||||
|
|
||||||
|
element->value = datumCopy(value, false, -1);
|
||||||
|
element->loaded = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -475,7 +480,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->value)));
|
||||||
|
|
||||||
UnlockReleaseBuffer(buf);
|
UnlockReleaseBuffer(buf);
|
||||||
}
|
}
|
||||||
@@ -935,7 +940,7 @@ HnswUpdateConnection(HnswElement element, HnswCandidate * hc, int m, int lc, int
|
|||||||
{
|
{
|
||||||
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
HnswCandidate *hc3 = ¤tNeighbors->items[i];
|
||||||
|
|
||||||
if (DatumGetPointer(hc3->element->value) == NULL)
|
if (!hc3->element->loaded)
|
||||||
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
HnswLoadElement(hc3->element, &hc3->distance, &q, index, procinfo, collation, true);
|
||||||
else
|
else
|
||||||
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
hc3->distance = GetCandidateDistance(hc3, q, procinfo, collation);
|
||||||
|
|||||||
@@ -62,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;
|
||||||
|
|
||||||
@@ -94,7 +93,7 @@ RemoveHeapTids(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
if (itemUpdated)
|
if (itemUpdated)
|
||||||
{
|
{
|
||||||
Size etupSize = ItemIdGetLength(itemid);
|
Size etupSize = HNSW_ELEMENT_TUPLE_SIZE(PointerGetDatum(&etup->value));
|
||||||
|
|
||||||
/* Mark rest as invalid */
|
/* Mark rest as invalid */
|
||||||
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
for (int i = idx; i < HNSW_HEAPTIDS; i++)
|
||||||
@@ -478,11 +477,11 @@ 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;
|
||||||
|
Datum value;
|
||||||
Buffer nbuf;
|
Buffer nbuf;
|
||||||
Page npage;
|
Page npage;
|
||||||
BlockNumber neighborPage;
|
BlockNumber neighborPage;
|
||||||
@@ -506,8 +505,11 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
if (ItemPointerIsValid(&etup->heaptids[0]))
|
if (ItemPointerIsValid(&etup->heaptids[0]))
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
/* Get datum */
|
||||||
|
value = PointerGetDatum(&etup->value);
|
||||||
|
|
||||||
/* Calculate sizes */
|
/* Calculate sizes */
|
||||||
etupSize = ItemIdGetLength(itemid);
|
etupSize = HNSW_ELEMENT_TUPLE_SIZE(value);
|
||||||
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
ntupSize = HNSW_NEIGHBOR_TUPLE_SIZE(etup->level, vacuumstate->m);
|
||||||
|
|
||||||
/* Get neighbor page */
|
/* Get neighbor page */
|
||||||
@@ -530,7 +532,7 @@ MarkDeleted(HnswVacuumState * vacuumstate)
|
|||||||
|
|
||||||
/* Overwrite element */
|
/* Overwrite element */
|
||||||
etup->deleted = 1;
|
etup->deleted = 1;
|
||||||
MemSet(&etup->data, 0, VARSIZE_ANY(&etup->data));
|
MemSet(&etup->value, 0, VARSIZE_ANY(value));
|
||||||
|
|
||||||
/* Overwrite neighbors */
|
/* Overwrite neighbors */
|
||||||
for (int i = 0; i < ntup->count; i++)
|
for (int i = 0; i < ntup->count; i++)
|
||||||
|
|||||||
18
src/vector.c
18
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)
|
||||||
@@ -437,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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -465,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)
|
||||||
@@ -478,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);
|
||||||
@@ -512,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]);
|
||||||
|
|||||||
@@ -83,32 +83,11 @@ for my $i (0 .. $#operators)
|
|||||||
push(@expected, $res);
|
push(@expected, $res);
|
||||||
}
|
}
|
||||||
|
|
||||||
# Build index serially
|
# Add index
|
||||||
$node->safe_psql("postgres", qq(
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v $opclass);");
|
||||||
SET max_parallel_maintenance_workers = 0;
|
|
||||||
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
|
||||||
));
|
|
||||||
|
|
||||||
# Test approximate results
|
|
||||||
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
test_recall($min, $operator);
|
test_recall($min, $operator);
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
|
||||||
|
|
||||||
# Build index in parallel
|
|
||||||
my ($ret, $stdout, $stderr) = $node->psql("postgres", qq(
|
|
||||||
SET client_min_messages = DEBUG;
|
|
||||||
SET min_parallel_table_scan_size = 1;
|
|
||||||
SET hnsw.enable_parallel_build = on;
|
|
||||||
CREATE INDEX idx ON tst USING hnsw (v $opclass);
|
|
||||||
));
|
|
||||||
is($ret, 0, $stderr);
|
|
||||||
like($stderr, qr/using \d+ parallel workers/);
|
|
||||||
|
|
||||||
# Test approximate results
|
|
||||||
test_recall($min, $operator);
|
|
||||||
|
|
||||||
$node->safe_psql("postgres", "DROP INDEX idx;");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
done_testing();
|
done_testing();
|
||||||
|
|||||||
113
test/t/019_hnsw_array.pl
Normal file
113
test/t/019_hnsw_array.pl
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
use PostgresNode;
|
||||||
|
use TestLib;
|
||||||
|
use Test::More;
|
||||||
|
|
||||||
|
my $node;
|
||||||
|
my @queries = ();
|
||||||
|
my @expected;
|
||||||
|
my $limit = 20;
|
||||||
|
|
||||||
|
sub test_recall
|
||||||
|
{
|
||||||
|
my ($min, $operator) = @_;
|
||||||
|
my $correct = 0;
|
||||||
|
my $total = 0;
|
||||||
|
|
||||||
|
my $explain = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
EXPLAIN ANALYZE SELECT i FROM tst ORDER BY v $operator '$queries[0]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
like($explain, qr/Index Scan/);
|
||||||
|
|
||||||
|
for my $i (0 .. $#queries)
|
||||||
|
{
|
||||||
|
my $actual = $node->safe_psql("postgres", qq(
|
||||||
|
SET enable_seqscan = off;
|
||||||
|
SELECT i FROM tst ORDER BY v $operator '$queries[$i]' LIMIT $limit;
|
||||||
|
));
|
||||||
|
my @actual_ids = split("\n", $actual);
|
||||||
|
my %actual_set = map { $_ => 1 } @actual_ids;
|
||||||
|
|
||||||
|
my @expected_ids = split("\n", $expected[$i]);
|
||||||
|
|
||||||
|
foreach (@expected_ids)
|
||||||
|
{
|
||||||
|
if (exists($actual_set{$_}))
|
||||||
|
{
|
||||||
|
$correct++;
|
||||||
|
}
|
||||||
|
$total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmp_ok($correct / $total, ">=", $min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize node
|
||||||
|
$node = get_new_node('node');
|
||||||
|
$node->init;
|
||||||
|
$node->start;
|
||||||
|
|
||||||
|
# Create table
|
||||||
|
$node->safe_psql("postgres", "CREATE EXTENSION vector;");
|
||||||
|
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v float4[3]);");
|
||||||
|
$node->safe_psql("postgres",
|
||||||
|
"INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 10000) i;"
|
||||||
|
);
|
||||||
|
|
||||||
|
$node->safe_psql("postgres", qq(
|
||||||
|
CREATE FUNCTION float4_l2_distance(float4[], float4[]) RETURNS float8
|
||||||
|
AS 'BEGIN RETURN l2_distance(\$1::vector, \$2::vector); END;'
|
||||||
|
LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE FUNCTION float4_l2_squared_distance(float4[], float4[]) RETURNS float8
|
||||||
|
AS 'BEGIN RETURN vector_l2_squared_distance(\$1::vector, \$2::vector); END;'
|
||||||
|
LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE;
|
||||||
|
|
||||||
|
CREATE OPERATOR <-> (
|
||||||
|
LEFTARG = float4[], RIGHTARG = float4[], PROCEDURE = float4_l2_distance,
|
||||||
|
COMMUTATOR = '<->'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE OPERATOR CLASS float4_l2_ops
|
||||||
|
FOR TYPE float4[] USING hnsw AS
|
||||||
|
OPERATOR 1 <-> (float4[], float4[]) FOR ORDER BY float_ops,
|
||||||
|
FUNCTION 1 float4_l2_squared_distance(float4[], float4[]);
|
||||||
|
));
|
||||||
|
|
||||||
|
# Generate queries
|
||||||
|
for (1 .. 20)
|
||||||
|
{
|
||||||
|
my $r1 = rand();
|
||||||
|
my $r2 = rand();
|
||||||
|
my $r3 = rand();
|
||||||
|
push(@queries, "{$r1,$r2,$r3}");
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check each index type
|
||||||
|
my @operators = ("<->");
|
||||||
|
my @opclasses = ("float4_l2_ops");
|
||||||
|
|
||||||
|
for my $i (0 .. $#operators)
|
||||||
|
{
|
||||||
|
my $operator = $operators[$i];
|
||||||
|
my $opclass = $opclasses[$i];
|
||||||
|
|
||||||
|
# Get exact results
|
||||||
|
@expected = ();
|
||||||
|
foreach (@queries)
|
||||||
|
{
|
||||||
|
my $res = $node->safe_psql("postgres", "SELECT i FROM tst ORDER BY v $operator '$_' LIMIT $limit;");
|
||||||
|
push(@expected, $res);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add index
|
||||||
|
$node->safe_psql("postgres", "CREATE INDEX ON tst USING hnsw (v $opclass);");
|
||||||
|
|
||||||
|
my $min = $operator eq "<#>" ? 0.80 : 0.99;
|
||||||
|
test_recall($min, $operator);
|
||||||
|
}
|
||||||
|
|
||||||
|
done_testing();
|
||||||
Reference in New Issue
Block a user