Compare commits

..

106 Commits

Author SHA1 Message Date
Andrew Kane
581ec6bfed Use maxItems 10 [skip ci] 2023-04-29 12:20:04 -07:00
Andrew Kane
a3c1eab27a Use pairing heap [skip ci] 2023-04-29 12:02:54 -07:00
Andrew Kane
a445355a48 Added Heroku Postgres link [skip ci] 2023-04-26 12:48:55 -07:00
Andrew Kane
d5b17a3624 Fixed installation error with Postgres 12.0-12.2 - fixes #101 2023-04-25 09:36:21 -07:00
Andrew Kane
6383078029 Updated readme [skip ci] 2023-04-22 17:07:10 -07:00
Andrew Kane
5146c7cc57 Added guidance for probes to readme [skip ci] 2023-04-20 12:32:49 -07:00
Andrew Kane
ac63f9858b Updated readme [skip ci] 2023-04-14 12:35:59 -07:00
Andrew Kane
76a4166857 Added link to pgvector-crystal [skip ci] 2023-04-13 21:10:18 -07:00
Andrew Kane
31fb6963a3 Now available on Render [skip ci] 2023-04-13 13:20:06 -07:00
Andrew Kane
18c06cb9b1 Added link to pgvector-swift [skip ci] 2023-04-11 21:11:46 -07:00
Andrew Kane
f858796c64 Added link to pgvector-haskell [skip ci] 2023-04-11 12:53:00 -07:00
Andrew Kane
f32f695844 Improved notice [skip ci] 2023-04-10 21:31:33 -07:00
Andrew Kane
1b013a94f7 Added notice when index created with little data [skip ci] 2023-04-10 21:28:24 -07:00
Andrew Kane
00148dfa1f Improved indexing docs [skip ci] 2023-04-10 21:12:25 -07:00
Andrew Kane
67fc791d95 Improved indexing docs [skip ci] 2023-04-10 21:04:46 -07:00
Andrew Kane
8bf360ed84 Updated header [skip ci] 2023-04-02 11:24:46 -07:00
Andrew Kane
f79d28347b Updated installation notes [skip ci] 2023-04-02 11:21:57 -07:00
Andrew Kane
20cf63de0a Updated readme [skip ci] 2023-04-02 10:56:37 -07:00
Andrew Kane
587cbcf15b Updated readme [skip ci] 2023-04-02 10:46:44 -07:00
Andrew Kane
c09edb5b8f Moved instructions [skip ci] 2023-04-02 10:39:41 -07:00
Will Laurance
c63501cca4 Update readme to show example usage of PG_CONFIG (#79) 2023-04-02 10:34:02 -07:00
Andrew Kane
58f0c922d2 Updated readme [skip ci] 2023-04-02 10:24:21 -07:00
Andrew Kane
36e73d2818 Updated readme [skip ci] 2023-04-01 20:06:18 -07:00
Andrew Kane
dd92d0ece3 Updated readme [skip ci] 2023-04-01 20:04:47 -07:00
Andrew Kane
6ede7681a5 Updated readme [skip ci] 2023-04-01 19:47:13 -07:00
Andrew Kane
8733729149 Updated readme [skip ci] 2023-04-01 19:45:13 -07:00
Andrew Kane
03a5789132 Updated readme [skip ci] 2023-04-01 19:44:23 -07:00
Andrew Kane
e5b612a856 Updated readme [skip ci] 2023-04-01 19:34:21 -07:00
Andrew Kane
9a7d3532f5 Updated readme [skip ci] 2023-04-01 19:32:26 -07:00
Andrew Kane
91315dfeff Added additional instructions for Ubuntu, Debian, and Windows [skip ci] 2023-04-01 17:42:44 -07:00
Andrew Kane
6e3101d527 Updated Dockerfile [skip ci] 2023-04-01 13:31:52 -07:00
Andrew Kane
96ae1a6a72 Added PG_MAJOR arg to Dockerfile [skip ci] 2023-04-01 13:15:00 -07:00
Andrew Kane
55aeba8bd6 Added lists to example [skip ci] 2023-03-31 22:12:35 -07:00
Andrew Kane
aebe1bae02 Updated readme [skip ci] 2023-03-31 21:55:24 -07:00
Andrew Kane
14355b9312 Updated readme [skip ci] 2023-03-31 21:46:38 -07:00
Andrew Kane
b5c66d0416 Updated readme [skip ci] 2023-03-31 21:36:25 -07:00
Andrew Kane
f534d9878a Updated readme [skip ci] 2023-03-31 21:31:38 -07:00
Andrew Kane
f3df137db6 Improved indexing instructions [skip ci] 2023-03-31 21:28:45 -07:00
Andrew Kane
489cdb5068 Added delete example [skip ci] 2023-03-31 20:02:22 -07:00
Andrew Kane
161f48793e Updated readme [skip ci] 2023-03-31 19:59:53 -07:00
Andrew Kane
f0f7ffca41 Updated readme [skip ci] 2023-03-31 19:34:39 -07:00
Andrew Kane
138d9be616 Added storage examples [skip ci] 2023-03-31 19:17:26 -07:00
Andrew Kane
fb98e73255 Updated readme [skip ci] 2023-03-31 18:55:51 -07:00
Andrew Kane
4754cac40c Updated readme [skip ci] 2023-03-31 18:47:15 -07:00
Andrew Kane
8432efb7d8 Added cosine similarity example [skip ci] 2023-03-31 18:34:36 -07:00
Andrew Kane
c38410259c Updated header [skip ci] 2023-03-31 16:59:21 -07:00
Andrew Kane
609d9fbf0a Updated header [skip ci] 2023-03-31 16:54:14 -07:00
Andrew Kane
7946424639 Updated header [skip ci] 2023-03-31 16:49:40 -07:00
Andrew Kane
d51310dfa0 Updated readme [skip ci] 2023-03-31 16:38:09 -07:00
Andrew Kane
30f2893aeb Updated readme [skip ci] 2023-03-31 16:30:42 -07:00
Andrew Kane
5d0f88529e Updated readme [skip ci] 2023-03-31 16:28:27 -07:00
Andrew Kane
1d020abdd1 Added auto-vectorized comments [skip ci] 2023-03-31 16:20:10 -07:00
Andrew Kane
d0fdd42652 Added comment [skip ci] 2023-03-31 13:37:33 -07:00
Andrew Kane
8473468925 Added instructions for Yum - #76 2023-03-30 15:39:27 -07:00
Andrew Kane
9c01524466 Updated readme [skip ci] 2023-03-26 23:39:09 -07:00
Andrew Kane
121baa411e Added debug message for index scan 2023-03-26 12:45:44 -07:00
Andrew Kane
50005d7326 Updated CI [skip ci] 2023-03-26 09:46:21 -07:00
Andrew Kane
ec12d79cbc Added link to pgvector-perl [skip ci] 2023-03-23 21:42:43 -07:00
Andrew Kane
d3eb56df07 Improved tests 2023-03-22 16:35:56 -07:00
Andrew Kane
13f7aa50c3 Added Render link [skip ci] 2023-03-22 16:29:06 -07:00
Andrew Kane
81e9e72fbc Updated guidance on lists [skip ci] 2023-03-22 14:00:47 -07:00
Andrew Kane
8d95510302 Updated readme [skip ci] 2023-03-22 13:32:25 -07:00
Andrew Kane
53bb2ed0cd Updated Homebrew instructions [skip ci] 2023-03-21 13:20:57 -07:00
Andrew Kane
fac8b9c8d9 Version bump to 0.4.1 [skip ci] 2023-03-21 12:39:59 -07:00
Andrew Kane
4e68f4f800 Updated comment [skip ci] 2023-03-21 11:55:26 -07:00
Andrew Kane
b69ac51ad7 Added comment [skip ci] 2023-03-21 11:43:30 -07:00
Andrew Kane
29c7af5d18 Improved test 2023-03-21 11:32:16 -07:00
Andrew Kane
bc9e2a37ec Improved performance of cosine distance 2023-03-21 11:25:25 -07:00
Andrew Kane
18eb04e278 Updated readme [skip ci] 2023-03-12 14:09:36 -07:00
Andrew Kane
42da2b334b Restored previous behavior and added comment 2023-03-12 13:57:40 -07:00
Andrew Kane
dbfc6a35d9 Improved vacuumcleanup stats 2023-03-12 13:34:26 -07:00
Andrew Kane
bbae64b784 Removed unneeded query from test 2023-03-12 13:26:23 -07:00
Andrew Kane
a6e8f36415 Updated readme [skip ci] 2023-03-12 13:15:47 -07:00
Andrew Kane
44985abbc6 Updated comment [skip ci] 2023-03-12 13:15:31 -07:00
Andrew Kane
9897ba7f64 Fixed CI 2023-03-12 13:13:04 -07:00
Andrew Kane
bb75ce2cf2 Fixed index scan count 2023-03-12 12:24:20 -07:00
Andrew Kane
385b2437a9 Updated readme [skip ci] 2023-03-05 18:18:03 -08:00
Andrew Kane
6c1536ee78 Moved section [skip ci] 2023-03-05 18:16:43 -08:00
Andrew Kane
4d8eae1c3e Updated readme [skip ci] 2023-03-05 18:13:32 -08:00
Andrew Kane
68378066a8 Added example of AVG [skip ci] 2023-03-05 17:54:02 -08:00
Andrew Kane
4f8620fe9e Added EXPLAIN ANALYZE to readme [skip ci] 2023-03-05 17:48:01 -08:00
Andrew Kane
a1ab0a453c Moved section [skip ci] 2023-03-05 17:44:53 -08:00
Andrew Kane
f1983ce672 Added section on querying - #64 [skip ci] 2023-03-05 17:34:49 -08:00
Andrew Kane
0a3615b82f Updated readme [skip ci] 2023-03-05 14:17:39 -08:00
Andrew Kane
e8a67dcf1c Added link to pgvector-lua [skip ci] 2023-03-05 13:44:52 -08:00
Andrew Kane
e83121eee4 Added link to pgvector-dotnet [skip ci] 2023-03-05 11:45:40 -08:00
Andrew Kane
77154f8cbb Updated readme [skip ci] 2023-03-03 16:33:44 -08:00
Andrew Kane
051c42a05a Updated readme [skip ci] 2023-03-03 16:28:23 -08:00
Andrew Kane
9077d85407 Reordered libraries [skip ci] 2023-03-03 16:18:55 -08:00
Andrew Kane
d74c82ff97 Updated pgvector-java link [skip ci] 2023-03-03 16:08:01 -08:00
Andrew Kane
cb6b7a3893 Added link to pgvector-scala [skip ci] 2023-03-03 11:50:03 -08:00
Andrew Kane
cb7d787d7c Added link to pgvector-julia [skip ci] 2023-03-02 22:16:23 -08:00
Andrew Kane
fc09ee200d Updated readme [skip ci] 2023-03-02 19:33:21 -08:00
Andrew Kane
eedcd64e08 Updated readme [skip ci] 2023-03-02 19:27:09 -08:00
Andrew Kane
c1671a4982 Updated readme [skip ci] 2023-03-02 19:22:00 -08:00
Andrew Kane
010055b288 Updated readme [skip ci] 2023-03-02 16:57:01 -08:00
Andrew Kane
8b759b695b Added link to pgvector-r [skip ci] 2023-03-02 16:48:14 -08:00
Andrew Kane
e1e53860d4 Added log to .gitignore [skip ci] 2023-02-26 09:57:31 -08:00
Andrew Kane
a85250c7bc Added platform to Docker task [skip ci] 2023-02-25 16:11:28 -08:00
Andrew Kane
4984411906 Added dylib to .gitignore [skip ci] 2023-02-25 15:28:00 -08:00
Andrew Kane
e4b0d41d30 Fixed warning 2023-02-23 14:17:31 -08:00
Andrew Kane
1b16a28906 Added test for casting from numeric[] 2023-02-23 14:15:50 -08:00
Andrew Kane
0b3dc0887f Fixed compilation with Postgres 16 - fixes #61 2023-02-23 14:08:27 -08:00
Andrew Kane
bb71b22e2e Updated readme [skip ci] 2023-02-22 19:42:40 -08:00
Andrew Kane
3b9df1c145 Moved to thread [skip ci] 2023-01-28 13:56:44 -08:00
Andrew Kane
11f66e6010 Added Supabase to readme [skip ci] 2023-01-28 11:13:47 -08:00
27 changed files with 487 additions and 200 deletions

View File

@@ -17,7 +17,7 @@ jobs:
- postgres: 12 - postgres: 12
os: ubuntu-20.04 os: ubuntu-20.04
- postgres: 11 - postgres: 11
os: ubuntu-18.04 os: ubuntu-20.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: ankane/setup-postgres@v1 - uses: ankane/setup-postgres@v1

2
.gitignore vendored
View File

@@ -1,4 +1,5 @@
/dist/ /dist/
/log/
/results/ /results/
/tmp_check/ /tmp_check/
/sql/vector--?.?.?.sql /sql/vector--?.?.?.sql
@@ -7,6 +8,7 @@ regression.*
*.so *.so
*.bc *.bc
*.dll *.dll
*.dylib
*.obj *.obj
*.lib *.lib
*.exp *.exp

View File

@@ -1,6 +1,12 @@
## 0.4.1 (unreleased) ## 0.4.2 (unreleased)
- Added `random_vector` function - Added notice when index created with little data
- Fixed installation error with Postgres 12.0-12.2
## 0.4.1 (2023-03-21)
- Improved performance of cosine distance
- Fixed index scan count
## 0.4.0 (2023-01-11) ## 0.4.0 (2023-01-11)

View File

@@ -1,9 +1,11 @@
FROM postgres:15 ARG PG_MAJOR=15
FROM postgres:$PG_MAJOR
ARG PG_MAJOR
COPY . /tmp/pgvector COPY . /tmp/pgvector
RUN apt-get update && \ RUN apt-get update && \
apt-get install -y --no-install-recommends build-essential postgresql-server-dev-15 && \ apt-get install -y --no-install-recommends build-essential postgresql-server-dev-$PG_MAJOR && \
cd /tmp/pgvector && \ cd /tmp/pgvector && \
make clean && \ make clean && \
make OPTFLAGS="" && \ make OPTFLAGS="" && \
@@ -11,6 +13,6 @@ RUN apt-get update && \
mkdir /usr/share/doc/pgvector && \ mkdir /usr/share/doc/pgvector && \
cp LICENSE README.md /usr/share/doc/pgvector && \ cp LICENSE README.md /usr/share/doc/pgvector && \
rm -r /tmp/pgvector && \ rm -r /tmp/pgvector && \
apt-get remove -y build-essential postgresql-server-dev-15 && \ apt-get remove -y build-essential postgresql-server-dev-$PG_MAJOR && \
apt-get autoremove -y && \ apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*

View File

@@ -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.4.0", "version": "0.4.1",
"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.4.0", "version": "0.4.1",
"abstract": "Open-source vector similarity search for Postgres" "abstract": "Open-source vector similarity search for Postgres"
} }
}, },

View File

@@ -1,5 +1,5 @@
EXTENSION = vector EXTENSION = vector
EXTVERSION = 0.4.0 EXTVERSION = 0.4.1
MODULE_big = vector MODULE_big = vector
DATA = $(wildcard sql/*--*.sql) DATA = $(wildcard sql/*--*.sql)
@@ -14,6 +14,7 @@ OPTFLAGS = -march=native
# Mac ARM doesn't support -march=native # Mac ARM doesn't support -march=native
ifeq ($(shell uname -s), Darwin) ifeq ($(shell uname -s), Darwin)
ifeq ($(shell uname -p), arm) ifeq ($(shell uname -p), arm)
# no difference with -march=armv8.5-a
OPTFLAGS = OPTFLAGS =
endif endif
endif endif
@@ -61,4 +62,4 @@ dist:
.PHONY: docker .PHONY: docker
docker: docker:
docker build --pull --no-cache -t ankane/pgvector:latest . docker build --pull --no-cache --platform linux/amd64 -t ankane/pgvector:latest .

View File

@@ -1,5 +1,5 @@
EXTENSION = vector EXTENSION = vector
EXTVERSION = 0.4.0 EXTVERSION = 0.4.1
OBJS = 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\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\vector.obj

311
README.md
View File

@@ -2,13 +2,11 @@
Open-source vector similarity search for Postgres Open-source vector similarity search for Postgres
```sql Supports
CREATE TABLE items (embedding vector(3));
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops);
SELECT * FROM items ORDER BY embedding <-> '[1,2,3]' LIMIT 5;
```
Supports L2 distance, inner product, and cosine distance - exact and approximate nearest neighbor search
- L2 distance, inner product, and cosine distance
- any [language](#languages) with a Postgres client
[![Build Status](https://github.com/pgvector/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/pgvector/pgvector/actions) [![Build Status](https://github.com/pgvector/pgvector/workflows/build/badge.svg?branch=master)](https://github.com/pgvector/pgvector/actions)
@@ -17,7 +15,8 @@ Supports L2 distance, inner product, and cosine distance
Compile and install the extension (supports Postgres 11+) Compile and install the extension (supports Postgres 11+)
```sh ```sh
git clone --branch v0.4.0 https://github.com/pgvector/pgvector.git cd /tmp
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector cd pgvector
make make
make install # may need sudo make install # may need sudo
@@ -29,81 +28,178 @@ Then load it in databases where you want to use it
CREATE EXTENSION vector; CREATE EXTENSION vector;
``` ```
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), or [conda-forge](#conda-forge) See the [installation notes](#installation-notes) if you run into issues
You can also install it with [Docker](#docker), [Homebrew](#homebrew), [PGXN](#pgxn), [Yum](#yum), or [conda-forge](#conda-forge)
## Getting Started ## Getting Started
Create a vector column with 3 dimensions Create a vector column with 3 dimensions
```sql ```sql
CREATE TABLE items (embedding vector(3)); CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
``` ```
Insert values Insert vectors
```sql ```sql
INSERT INTO items VALUES ('[1,2,3]'), ('[4,5,6]'); INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
``` ```
Get the nearest neighbor by L2 distance Get the nearest neighbors by L2 distance
```sql ```sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 1; SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
``` ```
Also supports inner product (`<#>`) and cosine distance (`<=>`) Also supports inner product (`<#>`) and cosine distance (`<=>`)
Note: `<#>` returns the negative inner product since Postgres only supports `ASC` order index scans on operators Note: `<#>` returns the negative inner product since Postgres only supports `ASC` order index scans on operators
## Storing
Create a new table with a vector column
```sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
```
Or add a vector column to an existing table
```sql
ALTER TABLE items ADD COLUMN embedding vector(3);
```
Insert vectors
```sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
```
Upsert vectors
```sql
INSERT INTO items (id, embedding) VALUES (1, '[1,2,3]'), (2, '[4,5,6]')
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
```
Update vectors
```sql
UPDATE items SET embedding = '[1,2,3]' WHERE id = 1;
```
Delete vectors
```sql
DELETE FROM items WHERE id = 1;
```
## Querying
Get the nearest neighbors to a vector
```sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
Get the nearest neighbors to a row
```sql
SELECT * FROM items WHERE id != 1 ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1) LIMIT 5;
```
Get rows within a certain distance
```sql
SELECT * FROM items WHERE embedding <-> '[3,1,2]' < 5;
```
Note: Combine with `ORDER BY` and `LIMIT` to use an index
#### Distances
Get the distance
```sql
SELECT embedding <-> '[3,1,2]' AS distance FROM items;
```
For inner product, multiply by -1 (since `<#>` returns the negative inner product)
```sql
SELECT (embedding <#> '[3,1,2]') * -1 AS inner_product FROM items;
```
For cosine similarity, use 1 - cosine distance
```sql
SELECT 1 - (embedding <=> '[3,1,2]') AS cosine_similarity FROM items;
```
#### Aggregates
Average vectors
```sql
SELECT AVG(embedding) FROM items;
```
Average groups of vectors
```sql
SELECT category_id, AVG(embedding) FROM items GROUP BY category_id;
```
## Indexing ## Indexing
Speed up queries with an approximate index. Add an index for each distance function you want to use. By default, pgvector performs exact nearest neighbor search, which provides perfect recall.
You can add an index to use approximate nearest neighbor search, which trades some recall for performance. Unlike typical indexes, you will see different results for queries after adding an approximate index.
Three keys to achieving good recall are:
1. Create the index *after* the table has some data
2. Choose an appropriate number of lists - a good place to start is `rows / 1000` for up to 1M rows and `sqrt(rows)` for over 1M rows
3. When querying, specify an appropriate number of [probes](#query-options) (higher is better for recall, lower is better for speed) - a good place to start is `lists / 10` for up to 1M rows and `sqrt(lists)` for over 1M rows
Add an index for each distance function you want to use.
L2 distance L2 distance
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops);
```
Inner product
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops);
```
Cosine distance
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops);
```
Indexes should be created after the table has some data for optimal clustering. Also, unlike typical indexes which only affect performance, you may see different results for queries after adding an approximate index. Vectors with up to 2,000 dimensions can be indexed.
### Index Options
Specify the number of inverted lists (100 by default)
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100); CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
``` ```
A [good place to start](https://github.com/facebookresearch/faiss/issues/112) is `4 * sqrt(rows)` Inner product
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100);
```
Cosine distance
```sql
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
```
Vectors with up to 2,000 dimensions can be indexed.
### Query Options ### Query Options
Specify the number of probes (1 by default) Specify the number of probes (1 by default)
```sql ```sql
SET ivfflat.probes = 1; SET ivfflat.probes = 10;
``` ```
A higher value improves recall at the cost of speed. A higher value provides better recall at the cost of speed, and it can be set to the number of lists for exact nearest neighbor search (at which point the planner wont use the index)
Use `SET LOCAL` inside a transaction to set it for a single query Use `SET LOCAL` inside a transaction to set it for a single query
```sql ```sql
BEGIN; BEGIN;
SET LOCAL ivfflat.probes = 1; SET LOCAL ivfflat.probes = 10;
SELECT ... SELECT ...
COMMIT; COMMIT;
``` ```
@@ -136,7 +232,7 @@ SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIM
can be indexed with: can be indexed with:
```sql ```sql
CREATE INDEX ON items USING ivfflat (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);
``` ```
To index many different values of `category_id`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `category_id`. To index many different values of `category_id`, consider [partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) on `category_id`.
@@ -147,18 +243,75 @@ CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(cate
## Performance ## Performance
Use `EXPLAIN ANALYZE` to debug performance.
```sql
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
```
### Exact Search
To speed up queries without an index, increase `max_parallel_workers_per_gather`. To speed up queries without an index, increase `max_parallel_workers_per_gather`.
```sql ```sql
SET max_parallel_workers_per_gather = 4; SET max_parallel_workers_per_gather = 4;
``` ```
If vectors are normalized to length 1 (like [OpenAI embeddings](https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use)), use inner product for best performance.
```sql
SELECT * FROM items ORDER BY embedding <#> '[3,1,2]' LIMIT 5;
```
### Approximate Search
To speed up queries with an index, increase the number of inverted lists (at the expense of recall). To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
```sql ```sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000); CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
``` ```
## Languages
Use pgvector from any language with a Postgres client. You can even generate and store vectors in one language and query them in another.
Language | Libraries / Examples
--- | ---
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
C# | [pgvector-dotnet](https://github.com/pgvector/pgvector-dotnet)
Crystal | [pgvector-crystal](https://github.com/pgvector/pgvector-crystal)
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
Haskell | [pgvector-haskell](https://github.com/pgvector/pgvector-haskell)
Java, Scala | [pgvector-java](https://github.com/pgvector/pgvector-java)
Julia | [pgvector-julia](https://github.com/pgvector/pgvector-julia)
Lua | [pgvector-lua](https://github.com/pgvector/pgvector-lua)
Node.js | [pgvector-node](https://github.com/pgvector/pgvector-node)
Perl | [pgvector-perl](https://github.com/pgvector/pgvector-perl)
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
R | [pgvector-r](https://github.com/pgvector/pgvector-r)
Ruby | [pgvector-ruby](https://github.com/pgvector/pgvector-ruby), [Neighbor](https://github.com/ankane/neighbor)
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
Swift | [pgvector-swift](https://github.com/pgvector/pgvector-swift)
## Frequently Asked Questions
#### How many vectors can be stored in a single table?
A non-partitioned table has a limit of 32 TB by default in Postgres. A partitioned table can have thousands of partitions of that size.
#### Is replication supported?
Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
#### What if I want to index vectors with more than 2,000 dimensions?
Two things you can try are:
1. use dimensionality reduction
2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/ivfflat.h`
## Reference ## Reference
### Vector Type ### Vector Type
@@ -184,7 +337,6 @@ inner_product(vector, vector) → double precision | inner product
l2_distance(vector, vector) → double precision | Euclidean distance l2_distance(vector, vector) → double precision | Euclidean distance
vector_dims(vector) → integer | number of dimensions vector_dims(vector) → integer | number of dimensions
vector_norm(vector) → double precision | Euclidean norm vector_norm(vector) → double precision | Euclidean norm
random_vector(integer) → vector | random vector [unreleased]
### Aggregate Functions ### Aggregate Functions
@@ -192,35 +344,41 @@ Function | Description
--- | --- --- | ---
avg(vector) → vector | arithmetic mean avg(vector) → vector | arithmetic mean
## Libraries ## Installation Notes
Language | Libraries ### Postgres Location
--- | ---
Python | [pgvector-python](https://github.com/pgvector/pgvector-python)
Ruby | [Neighbor](https://github.com/ankane/neighbor), [pgvector-ruby](https://github.com/pgvector/pgvector-ruby)
Node | [pgvector-node](https://github.com/pgvector/pgvector-node)
Go | [pgvector-go](https://github.com/pgvector/pgvector-go)
PHP | [pgvector-php](https://github.com/pgvector/pgvector-php)
Rust | [pgvector-rust](https://github.com/pgvector/pgvector-rust)
C++ | [pgvector-cpp](https://github.com/pgvector/pgvector-cpp)
Elixir | [pgvector-elixir](https://github.com/pgvector/pgvector-elixir)
## Frequently Asked Questions If your machine has multiple Postgres installations, specify the path to [pg_config](https://www.postgresql.org/docs/current/app-pgconfig.html) with:
#### How many vectors can be stored in a single table? ```sh
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
```
A non-partitioned table has a limit of 32 TB by default in Postgres. A partitioned table can have thousands of partitions of that size. Then re-run the installation instructions (run `make clean` before `make` if needed)
#### Is replication supported? ### Missing Header
Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery. If compilation fails with `fatal error: postgres.h: No such file or directory`, make sure Postgres development files are installed on the server.
#### What if I want to index vectors with more than 2,000 dimensions? For Ubuntu and Debian, use:
Two things you can try are: ```sh
sudo apt-get install postgresql-server-dev-15
```
1. use dimensionality reduction Note: Replace `15` with your Postgres server version
2. compile Postgres with a larger block size (`./configure --with-blocksize=32`) and edit the limit in `src/ivfflat.h`
### Windows
Support for Windows is currently experimental. Use `nmake` to build:
```cmd
set "PGROOT=C:\Program Files\PostgreSQL\15"
git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector
nmake /F Makefile.win
nmake /F Makefile.win install
```
## Additional Installation Methods ## Additional Installation Methods
@@ -232,12 +390,12 @@ Get the [Docker image](https://hub.docker.com/r/ankane/pgvector) with:
docker pull ankane/pgvector docker pull ankane/pgvector
``` ```
This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres). This adds pgvector to the [Postgres image](https://hub.docker.com/_/postgres) (run it the same way).
You can also build the image manually You can also build the image manually:
```sh ```sh
git clone --branch v0.4.0 https://github.com/pgvector/pgvector.git git clone --branch v0.4.1 https://github.com/pgvector/pgvector.git
cd pgvector cd pgvector
docker build -t pgvector . docker build -t pgvector .
``` ```
@@ -247,7 +405,7 @@ docker build -t pgvector .
With Homebrew Postgres, you can use: With Homebrew Postgres, you can use:
```sh ```sh
brew install pgvector/brew/pgvector brew install pgvector
``` ```
### PGXN ### PGXN
@@ -258,9 +416,21 @@ Install from the [PostgreSQL Extension Network](https://pgxn.org/dist/vector) wi
pgxn install vector pgxn install vector
``` ```
### 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:
```sh
sudo yum install pgvector_15
# or
sudo dnf install pgvector_15
```
Note: Replace `15` with your Postgres server version
### conda-forge ### conda-forge
Install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with: With Conda Postgres, install from [conda-forge](https://anaconda.org/conda-forge/pgvector) with:
```sh ```sh
conda install -c conda-forge pgvector conda install -c conda-forge pgvector
@@ -270,12 +440,15 @@ This method is [community-maintained](https://github.com/conda-forge/pgvector-fe
## Hosted Postgres ## Hosted Postgres
Some Postgres providers only support specific extensions. To request a new extension: pgvector is available on [these providers](https://github.com/pgvector/pgvector/issues/54).
To request a new extension on other providers:
- Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/) - Amazon RDS - follow the instructions on [this page](https://aws.amazon.com/rds/postgresql/faqs/)
- Google Cloud SQL - vote or comment on [this page](https://issuetracker.google.com/issues/265172065) - Google Cloud SQL - vote or comment on [this page](https://issuetracker.google.com/issues/265172065)
- Azure Database - vote or comment on [this page](https://feedback.azure.com/d365community/idea/7b423322-6189-ed11-a81b-000d3ae49307)
- DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql) - DigitalOcean Managed Databases - vote or comment on [this page](https://ideas.digitalocean.com/app-framework-services/p/pgvector-extension-for-postgresql)
- Azure Database for PostgreSQL - vote or comment on [this page](https://feedback.azure.com/d365community/idea/7b423322-6189-ed11-a81b-000d3ae49307) - Heroku Postgres - vote or comment on [this page](https://github.com/heroku/roadmap/issues/156)
## Upgrading ## Upgrading

View File

@@ -1,5 +1,2 @@
-- complain if script is sourced in psql, rather than via CREATE EXTENSION -- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION vector UPDATE TO '0.4.1'" to load this file. \quit \echo Use "ALTER EXTENSION vector UPDATE TO '0.4.1'" to load this file. \quit
CREATE FUNCTION random_vector(integer) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C VOLATILE STRICT PARALLEL SAFE;

View File

@@ -52,9 +52,6 @@ CREATE FUNCTION vector_add(vector, vector) RETURNS vector
CREATE FUNCTION vector_sub(vector, vector) RETURNS vector CREATE FUNCTION vector_sub(vector, vector) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
CREATE FUNCTION random_vector(integer) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C VOLATILE STRICT PARALLEL SAFE;
-- private functions -- private functions
CREATE FUNCTION vector_lt(vector, vector) RETURNS bool CREATE FUNCTION vector_lt(vector, vector) RETURNS bool

View File

@@ -431,8 +431,18 @@ ComputeCenters(IvfflatBuildState * buildstate)
/* TODO Ensure within maintenance_work_mem */ /* TODO Ensure within maintenance_work_mem */
buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions); buildstate->samples = VectorArrayInit(numSamples, buildstate->dimensions);
if (buildstate->heap != NULL) if (buildstate->heap != NULL)
{
SampleRows(buildstate); SampleRows(buildstate);
if (buildstate->samples->length < buildstate->lists)
{
ereport(NOTICE,
(errmsg("ivfflat index created with little data"),
errdetail("this will cause poor recall"),
errhint("drop the index until the table has more data")));
}
}
/* Calculate centers */ /* Calculate centers */
IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers)); IvfflatBench("k-means", IvfflatKmeans(buildstate->index, buildstate->samples, buildstate->centers));

View File

@@ -10,10 +10,15 @@
#include "access/generic_xlog.h" #include "access/generic_xlog.h"
#include "access/reloptions.h" #include "access/reloptions.h"
#include "nodes/execnodes.h" #include "nodes/execnodes.h"
#include "port.h" /* for strtof() and random() */
#include "utils/sampling.h" #include "utils/sampling.h"
#include "utils/tuplesort.h" #include "utils/tuplesort.h"
#include "vector.h" #include "vector.h"
#if PG_VERSION_NUM >= 150000
#include "common/pg_prng.h"
#endif
#ifdef IVFFLAT_BENCH #ifdef IVFFLAT_BENCH
#include "portability/instr_time.h" #include "portability/instr_time.h"
#endif #endif
@@ -63,6 +68,14 @@
#define IvfflatBench(name, code) (code) #define IvfflatBench(name, code) (code)
#endif #endif
#if PG_VERSION_NUM >= 150000
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
#define RandomInt() pg_prng_uint32(&pg_global_prng_state)
#else
#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
#define RandomInt() random()
#endif
/* Variables */ /* Variables */
extern int ivfflat_probes; extern int ivfflat_probes;
@@ -174,6 +187,14 @@ typedef struct IvfflatScanList
double distance; double distance;
} IvfflatScanList; } IvfflatScanList;
typedef struct IvfflatScanItem
{
pairingheap_node ph_node;
BlockNumber searchPage;
double distance;
ItemPointerData tid;
} IvfflatScanItem;
typedef struct IvfflatScanOpaqueData typedef struct IvfflatScanOpaqueData
{ {
int probes; int probes;
@@ -191,6 +212,13 @@ typedef struct IvfflatScanOpaqueData
FmgrInfo *normprocinfo; FmgrInfo *normprocinfo;
Oid collation; Oid collation;
/* Items */
int maxItems;
int itemCount;
pairingheap *itemQueue;
IvfflatScanItem *items;
IvfflatScanItem **sortedItems;
/* Lists */ /* Lists */
pairingheap *listQueue; pairingheap *listQueue;
IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER]; /* must come last */ IvfflatScanList lists[FLEXIBLE_ARRAY_MEMBER]; /* must come last */

View File

@@ -5,6 +5,7 @@
#include "access/relscan.h" #include "access/relscan.h"
#include "ivfflat.h" #include "ivfflat.h"
#include "miscadmin.h" #include "miscadmin.h"
#include "pgstat.h"
#include "storage/bufmgr.h" #include "storage/bufmgr.h"
#include "catalog/pg_operator_d.h" #include "catalog/pg_operator_d.h"
@@ -25,6 +26,21 @@ CompareLists(const pairingheap_node *a, const pairingheap_node *b, void *arg)
return 0; return 0;
} }
/*
* Compare item distances
*/
static int
CompareItems(const pairingheap_node *a, const pairingheap_node *b, void *arg)
{
if (((const IvfflatScanItem *) a)->distance > ((const IvfflatScanItem *) b)->distance)
return 1;
if (((const IvfflatScanItem *) a)->distance < ((const IvfflatScanItem *) b)->distance)
return -1;
return 0;
}
/* /*
* Get lists and sort by distance * Get lists and sort by distance
*/ */
@@ -110,12 +126,10 @@ GetScanItems(IndexScanDesc scan, Datum value)
Datum datum; Datum datum;
bool isnull; bool isnull;
TupleDesc tupdesc = RelationGetDescr(scan->indexRelation); TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
int i;
#if PG_VERSION_NUM >= 120000 double distance;
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsVirtual); IvfflatScanItem *scanitem;
#else double maxDistance = DBL_MAX;
TupleTableSlot *slot = MakeSingleTupleTableSlot(so->tupdesc);
#endif
/* /*
* Reuse same set of shared buffers for scan * Reuse same set of shared buffers for scan
@@ -141,23 +155,40 @@ GetScanItems(IndexScanDesc scan, Datum value)
{ {
itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno)); itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno));
datum = index_getattr(itup, 1, tupdesc, &isnull); datum = index_getattr(itup, 1, tupdesc, &isnull);
distance = DatumGetFloat8(FunctionCall2Coll(so->procinfo, so->collation, datum, value));
/* if (so->itemCount < so->maxItems)
* Add virtual tuple {
* scanitem = &so->items[so->itemCount];
* Use procinfo from the index instead of scan key for scanitem->searchPage = searchPage;
* performance scanitem->tid = itup->t_tid;
*/ scanitem->distance = distance;
ExecClearTuple(slot); so->itemCount++;
slot->tts_values[0] = FunctionCall2Coll(so->procinfo, so->collation, datum, value);
slot->tts_isnull[0] = false;
slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
slot->tts_isnull[1] = false;
slot->tts_values[2] = Int32GetDatum((int) searchPage);
slot->tts_isnull[2] = false;
ExecStoreVirtualTuple(slot);
tuplesort_puttupleslot(so->sortstate, slot); /* Add to heap */
pairingheap_add(so->itemQueue, &scanitem->ph_node);
/* Calculate max distance */
if (so->itemCount == so->maxItems)
{
maxDistance = ((IvfflatScanItem *) pairingheap_first(so->itemQueue))->distance;
scanitem = &so->items[so->itemCount];
}
}
else if (distance < maxDistance)
{
/* Reuse */
scanitem->searchPage = searchPage;
scanitem->tid = itup->t_tid;
scanitem->distance = distance;
pairingheap_add(so->itemQueue, &scanitem->ph_node);
/* Remove */
scanitem = (IvfflatScanItem *) pairingheap_remove_first(so->itemQueue);
/* Update max distance */
maxDistance = ((IvfflatScanItem *) pairingheap_first(so->itemQueue))->distance;
}
} }
searchPage = IvfflatPageGetOpaque(page)->nextblkno; searchPage = IvfflatPageGetOpaque(page)->nextblkno;
@@ -166,7 +197,10 @@ GetScanItems(IndexScanDesc scan, Datum value)
} }
} }
tuplesort_performsort(so->sortstate); for (i = 0; i < so->itemCount; i++)
so->sortedItems[i] = (IvfflatScanItem *) pairingheap_remove_first(so->itemQueue);
Assert(pairingheap_is_empty(so->itemQueue));
} }
/* /*
@@ -178,10 +212,6 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
IndexScanDesc scan; IndexScanDesc scan;
IvfflatScanOpaque so; IvfflatScanOpaque so;
int lists; int lists;
AttrNumber attNums[] = {1};
Oid sortOperators[] = {Float8LessOperator};
Oid sortCollations[] = {InvalidOid};
bool nullsFirstFlags[] = {false};
int probes = ivfflat_probes; int probes = ivfflat_probes;
scan = RelationGetIndexScan(index, nkeys, norderbys); scan = RelationGetIndexScan(index, nkeys, norderbys);
@@ -200,27 +230,14 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC); so->normprocinfo = IvfflatOptionalProcInfo(index, IVFFLAT_NORM_PROC);
so->collation = index->rd_indcollation[0]; so->collation = index->rd_indcollation[0];
/* Create tuple description for sorting */
#if PG_VERSION_NUM >= 120000
so->tupdesc = CreateTemplateTupleDesc(3);
#else
so->tupdesc = CreateTemplateTupleDesc(3, false);
#endif
TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
TupleDescInitEntry(so->tupdesc, (AttrNumber) 3, "indexblkno", INT4OID, -1, 0);
/* Prep sort */
so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
#if PG_VERSION_NUM >= 120000
so->slot = MakeSingleTupleTableSlot(so->tupdesc, &TTSOpsMinimalTuple);
#else
so->slot = MakeSingleTupleTableSlot(so->tupdesc);
#endif
so->listQueue = pairingheap_allocate(CompareLists, scan); so->listQueue = pairingheap_allocate(CompareLists, scan);
so->maxItems = 10;
so->itemCount = 0;
so->itemQueue = pairingheap_allocate(CompareItems, scan);
so->items = palloc(sizeof(IvfflatScanItem) * (so->maxItems + 1));
so->sortedItems = palloc(sizeof(IvfflatScanItem *) * so->maxItems);
scan->opaque = so; scan->opaque = so;
return scan; return scan;
@@ -234,13 +251,10 @@ ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int
{ {
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque; IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
#if PG_VERSION_NUM >= 130000
if (!so->first)
tuplesort_reset(so->sortstate);
#endif
so->first = true; so->first = true;
pairingheap_reset(so->listQueue); pairingheap_reset(so->listQueue);
pairingheap_reset(so->itemQueue);
so->itemCount = 0;
if (keys && scan->numberOfKeys > 0) if (keys && scan->numberOfKeys > 0)
memmove(scan->keyData, keys, scan->numberOfKeys * sizeof(ScanKeyData)); memmove(scan->keyData, keys, scan->numberOfKeys * sizeof(ScanKeyData));
@@ -267,6 +281,9 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
{ {
Datum value; Datum value;
/* Count index scan for stats */
pgstat_count_index_scan(scan->indexRelation);
/* Safety check */ /* Safety check */
if (scan->orderByData == NULL) if (scan->orderByData == NULL)
elog(ERROR, "cannot scan ivfflat index without order"); elog(ERROR, "cannot scan ivfflat index without order");
@@ -297,15 +314,18 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
pfree(DatumGetPointer(value)); pfree(DatumGetPointer(value));
} }
if (tuplesort_gettupleslot(so->sortstate, true, false, so->slot, NULL)) if (so->itemCount > 0)
{ {
ItemPointer tid = (ItemPointer) DatumGetPointer(slot_getattr(so->slot, 2, &so->isnull)); IvfflatScanItem *scanitem;
BlockNumber indexblkno = DatumGetInt32(slot_getattr(so->slot, 3, &so->isnull));
so->itemCount--;
scanitem = so->sortedItems[so->itemCount];
#if PG_VERSION_NUM >= 120000 #if PG_VERSION_NUM >= 120000
scan->xs_heaptid = *tid; scan->xs_heaptid = scanitem->tid;
#else #else
scan->xs_ctup.t_self = *tid; scan->xs_ctup.t_self = scanitem->tid;
#endif #endif
if (BufferIsValid(so->buf)) if (BufferIsValid(so->buf))
@@ -317,7 +337,7 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
* *
* https://www.postgresql.org/docs/current/index-locking.html * https://www.postgresql.org/docs/current/index-locking.html
*/ */
so->buf = ReadBuffer(scan->indexRelation, indexblkno); so->buf = ReadBuffer(scan->indexRelation, scanitem->searchPage);
scan->xs_recheckorderby = false; scan->xs_recheckorderby = false;
return true; return true;
@@ -339,7 +359,10 @@ ivfflatendscan(IndexScanDesc scan)
ReleaseBuffer(so->buf); ReleaseBuffer(so->buf);
pairingheap_free(so->listQueue); pairingheap_free(so->listQueue);
tuplesort_end(so->sortstate);
pairingheap_free(so->itemQueue);
pfree(so->items);
pfree(so->sortedItems);
pfree(so); pfree(so);
scan->opaque = NULL; scan->opaque = NULL;

View File

@@ -143,6 +143,11 @@ ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
{ {
Relation rel = info->index; Relation rel = info->index;
if (info->analyze_only)
return stats;
/* stats is NULL if ambulkdelete not called */
/* OK to return NULL if index not changed */
if (stats == NULL) if (stats == NULL)
return NULL; return NULL;

View File

@@ -100,7 +100,7 @@ CheckStateArray(ArrayType *statearray, const char *caller)
return (float8 *) ARR_DATA_PTR(statearray); return (float8 *) ARR_DATA_PTR(statearray);
} }
#if PG_VERSION_NUM < 120000 #if PG_VERSION_NUM < 120003
static pg_noinline void static pg_noinline void
float_overflow_error(void) float_overflow_error(void)
{ {
@@ -416,7 +416,7 @@ array_to_vector(PG_FUNCTION_ARGS)
else if (ARR_ELEMTYPE(array) == FLOAT4OID) else if (ARR_ELEMTYPE(array) == FLOAT4OID)
result->x[i] = DatumGetFloat4(elemsp[i]); result->x[i] = DatumGetFloat4(elemsp[i]);
else if (ARR_ELEMTYPE(array) == NUMERICOID) else if (ARR_ELEMTYPE(array) == NUMERICOID)
result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(elemsp[i]))); result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, elemsp[i]));
else else
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION), (errcode(ERRCODE_DATA_EXCEPTION),
@@ -467,6 +467,7 @@ l2_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
diff = ax[i] - bx[i]; diff = ax[i] - bx[i];
@@ -493,6 +494,7 @@ vector_l2_squared_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
diff = ax[i] - bx[i]; diff = ax[i] - bx[i];
@@ -517,6 +519,7 @@ inner_product(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -538,6 +541,7 @@ vector_negative_inner_product(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -561,6 +565,7 @@ cosine_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
{ {
distance += ax[i] * bx[i]; distance += ax[i] * bx[i];
@@ -568,7 +573,8 @@ cosine_distance(PG_FUNCTION_ARGS)
normb += bx[i] * bx[i]; normb += bx[i] * bx[i];
} }
PG_RETURN_FLOAT8(1 - (distance / (sqrt(norma) * sqrt(normb)))); /* Use sqrt(a * b) over sqrt(a) * sqrt(b) */
PG_RETURN_FLOAT8(1 - (distance / sqrt(norma * normb)));
} }
/* /*
@@ -586,6 +592,7 @@ vector_spherical_distance(PG_FUNCTION_ARGS)
CheckDims(a, b); CheckDims(a, b);
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
distance += a->x[i] * b->x[i]; distance += a->x[i] * b->x[i];
@@ -621,6 +628,7 @@ vector_norm(PG_FUNCTION_ARGS)
float *ax = a->x; float *ax = a->x;
double norm = 0.0; double norm = 0.0;
/* Auto-vectorized */
for (int i = 0; i < a->dim; i++) for (int i = 0; i < a->dim; i++)
norm += ax[i] * ax[i]; norm += ax[i] * ax[i];
@@ -645,6 +653,8 @@ vector_add(PG_FUNCTION_ARGS)
result = InitVector(a->dim); result = InitVector(a->dim);
rx = result->x; rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++) for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] + bx[i]; rx[i] = ax[i] + bx[i];
@@ -669,6 +679,8 @@ vector_sub(PG_FUNCTION_ARGS)
result = InitVector(a->dim); result = InitVector(a->dim);
rx = result->x; rx = result->x;
/* Auto-vectorized */
for (int i = 0, imax = a->dim; i < imax; i++) for (int i = 0, imax = a->dim; i < imax; i++)
rx[i] = ax[i] - bx[i]; rx[i] = ax[i] - bx[i];
@@ -822,7 +834,7 @@ vector_accum(PG_FUNCTION_ARGS)
if (newarr) if (newarr)
{ {
for (int i = 0; i < dim; i++) for (int i = 0; i < dim; i++)
statedatums[i + 1] = Float8GetDatumFast(x[i]); statedatums[i + 1] = Float8GetDatumFast((double) x[i]);
} }
else else
{ {
@@ -950,22 +962,3 @@ vector_avg(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result); PG_RETURN_POINTER(result);
} }
/*
* Generate a random vector
*/
PGDLLEXPORT PG_FUNCTION_INFO_V1(random_vector);
Datum
random_vector(PG_FUNCTION_ARGS)
{
int32 dim = PG_GETARG_INT32(0);
Vector *result;
CheckDim(dim);
result = InitVector(dim);
for (int i = 0; i < dim; i++)
result->x[i] = RandomDouble();
PG_RETURN_POINTER(result);
}

View File

@@ -3,10 +3,8 @@
#include "postgres.h" #include "postgres.h"
#include "port.h" /* for strtof() and random() */ #if PG_VERSION_NUM >= 160000
#include "varatt.h"
#if PG_VERSION_NUM >= 150000
#include "common/pg_prng.h"
#endif #endif
#define VECTOR_MAX_DIM 16000 #define VECTOR_MAX_DIM 16000
@@ -16,14 +14,6 @@
#define PG_GETARG_VECTOR_P(x) DatumGetVector(PG_GETARG_DATUM(x)) #define PG_GETARG_VECTOR_P(x) DatumGetVector(PG_GETARG_DATUM(x))
#define PG_RETURN_VECTOR_P(x) PG_RETURN_POINTER(x) #define PG_RETURN_VECTOR_P(x) PG_RETURN_POINTER(x)
#if PG_VERSION_NUM >= 150000
#define RandomDouble() pg_prng_double(&pg_global_prng_state)
#define RandomInt() pg_prng_uint32(&pg_global_prng_state)
#else
#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
#define RandomInt() random()
#endif
typedef struct Vector typedef struct Vector
{ {
int32 vl_len_; /* varlena header (do not touch directly!) */ int32 vl_len_; /* varlena header (do not touch directly!) */

View File

@@ -22,6 +22,12 @@ SELECT ARRAY[1,2,3]::float8[]::vector;
[1,2,3] [1,2,3]
(1 row) (1 row)
SELECT ARRAY[1,2,3]::numeric[]::vector;
array
---------
[1,2,3]
(1 row)
SELECT '{NULL}'::real[]::vector; SELECT '{NULL}'::real[]::vector;
ERROR: array must not containing NULLs ERROR: array must not containing NULLs
SELECT '{NaN}'::real[]::vector; SELECT '{NaN}'::real[]::vector;

View File

@@ -22,10 +22,28 @@ SELECT round(vector_norm('[1,1]')::numeric, 5);
1.41421 1.41421
(1 row) (1 row)
SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5); SELECT vector_norm('[3,4]');
round vector_norm
--------- -------------
2.23607 5
(1 row)
SELECT vector_norm('[0,1]');
vector_norm
-------------
1
(1 row)
SELECT l2_distance('[0,0]', '[3,4]');
l2_distance
-------------
5
(1 row)
SELECT l2_distance('[0,0]', '[0,1]');
l2_distance
-------------
1
(1 row) (1 row)
SELECT l2_distance('[1,2]', '[3]'); SELECT l2_distance('[1,2]', '[3]');
@@ -38,10 +56,10 @@ SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]'); SELECT inner_product('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1 ERROR: different vector dimensions 2 and 1
SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5); SELECT cosine_distance('[1,2]', '[2,4]');
round cosine_distance
--------- -----------------
0.00000 0
(1 row) (1 row)
SELECT cosine_distance('[1,2]', '[0,0]'); SELECT cosine_distance('[1,2]', '[0,0]');
@@ -50,6 +68,18 @@ SELECT cosine_distance('[1,2]', '[0,0]');
NaN NaN
(1 row) (1 row)
SELECT cosine_distance('[1,1]', '[1,1]');
cosine_distance
-----------------
0
(1 row)
SELECT cosine_distance('[1,1]', '[-1,-1]');
cosine_distance
-----------------
2
(1 row)
SELECT cosine_distance('[1,2]', '[3]'); SELECT cosine_distance('[1,2]', '[3]');
ERROR: different vector dimensions 2 and 1 ERROR: different vector dimensions 2 and 1
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;

View File

@@ -2,6 +2,7 @@ SELECT ARRAY[1,2,3]::vector;
SELECT ARRAY[1.0,2.0,3.0]::vector; SELECT ARRAY[1.0,2.0,3.0]::vector;
SELECT ARRAY[1,2,3]::float4[]::vector; SELECT ARRAY[1,2,3]::float4[]::vector;
SELECT ARRAY[1,2,3]::float8[]::vector; SELECT ARRAY[1,2,3]::float8[]::vector;
SELECT ARRAY[1,2,3]::numeric[]::vector;
SELECT '{NULL}'::real[]::vector; SELECT '{NULL}'::real[]::vector;
SELECT '{NaN}'::real[]::vector; SELECT '{NaN}'::real[]::vector;
SELECT '{Infinity}'::real[]::vector; SELECT '{Infinity}'::real[]::vector;

View File

@@ -2,16 +2,22 @@ SELECT '[1,2,3]'::vector + '[4,5,6]';
SELECT '[1,2,3]'::vector - '[4,5,6]'; SELECT '[1,2,3]'::vector - '[4,5,6]';
SELECT vector_dims('[1,2,3]'); SELECT vector_dims('[1,2,3]');
SELECT round(vector_norm('[1,1]')::numeric, 5);
SELECT round(l2_distance('[1,2]', '[0,0]')::numeric, 5); SELECT round(vector_norm('[1,1]')::numeric, 5);
SELECT vector_norm('[3,4]');
SELECT vector_norm('[0,1]');
SELECT l2_distance('[0,0]', '[3,4]');
SELECT l2_distance('[0,0]', '[0,1]');
SELECT l2_distance('[1,2]', '[3]'); SELECT l2_distance('[1,2]', '[3]');
SELECT inner_product('[1,2]', '[3,4]'); SELECT inner_product('[1,2]', '[3,4]');
SELECT inner_product('[1,2]', '[3]'); SELECT inner_product('[1,2]', '[3]');
SELECT round(cosine_distance('[1,2]', '[2,4]')::numeric, 5); 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,2]', '[3]'); SELECT cosine_distance('[1,2]', '[3]');
SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v;

View File

@@ -44,6 +44,11 @@ sub test_index_replay
return; return;
} }
# Use ARRAY[random(), random(), random(), ...] over
# SELECT array_agg(random()) FROM generate_series(1, $dim)
# to generate different values for each row
my $array_sql = join(",", ('random()') x $dim);
# Initialize primary node # Initialize primary node
$node_primary = get_new_node('primary'); $node_primary = get_new_node('primary');
$node_primary->init(allows_streaming => 1); $node_primary->init(allows_streaming => 1);
@@ -70,7 +75,7 @@ $node_replica->start;
$node_primary->safe_psql("postgres", "CREATE EXTENSION vector;"); $node_primary->safe_psql("postgres", "CREATE EXTENSION vector;");
$node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));"); $node_primary->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim));");
$node_primary->safe_psql("postgres", $node_primary->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, random_vector($dim) FROM generate_series(1, 100000) i;" "INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series(1, 100000) i;"
); );
$node_primary->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);"); $node_primary->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
@@ -86,7 +91,7 @@ for my $i (1 .. 10)
test_index_replay("vacuum $i"); test_index_replay("vacuum $i");
my ($start, $end) = (100001 + ($i - 1) * 10000, 100000 + $i * 10000); my ($start, $end) = (100001 + ($i - 1) * 10000, 100000 + $i * 10000);
$node_primary->safe_psql("postgres", $node_primary->safe_psql("postgres",
"INSERT INTO tst SELECT i % 10, random_vector($dim) FROM generate_series($start, $end) i;" "INSERT INTO tst SELECT i % 10, ARRAY[$array_sql] FROM generate_series($start, $end) i;"
); );
test_index_replay("insert $i"); test_index_replay("insert $i");
} }

View File

@@ -46,7 +46,7 @@ $node->start;
$node->safe_psql("postgres", "CREATE EXTENSION vector;"); $node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));"); $node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector(3));");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT i, random_vector(3) FROM generate_series(1, 100000) i;" "INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
); );
# Generate queries # Generate queries

View File

@@ -13,7 +13,7 @@ $node->start;
$node->safe_psql("postgres", "CREATE EXTENSION vector;"); $node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (i int4 primary key, v vector(3));"); $node->safe_psql("postgres", "CREATE TABLE tst (i int4 primary key, v vector(3));");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT i, random_vector(3) FROM generate_series(1, 100000) i;" "INSERT INTO tst SELECT i, ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
); );
# Check each index type # Check each index type

View File

@@ -13,7 +13,7 @@ $node->start;
$node->safe_psql("postgres", "CREATE EXTENSION vector;"); $node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (v vector(3));"); $node->safe_psql("postgres", "CREATE TABLE tst (v vector(3));");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT random_vector(3) FROM generate_series(1, 100000) i;" "INSERT INTO tst SELECT ARRAY[random(), random(), random()] FROM generate_series(1, 100000) i;"
); );
$node->safe_psql("postgres", "CREATE INDEX lists50 ON tst USING ivfflat (v) WITH (lists = 50);"); $node->safe_psql("postgres", "CREATE INDEX lists50 ON tst USING ivfflat (v) WITH (lists = 50);");

View File

@@ -2,10 +2,12 @@ use strict;
use warnings; use warnings;
use PostgresNode; use PostgresNode;
use TestLib; use TestLib;
use Test::More tests => 5; use Test::More tests => 7;
my $dim = 768; my $dim = 768;
my $array_sql = join(",", ('random()') x $dim);
# Initialize node # Initialize node
my $node = get_new_node('node'); my $node = get_new_node('node');
$node->init; $node->init;
@@ -15,7 +17,7 @@ $node->start;
$node->safe_psql("postgres", "CREATE EXTENSION vector;"); $node->safe_psql("postgres", "CREATE EXTENSION vector;");
$node->safe_psql("postgres", "CREATE TABLE tst (v vector($dim));"); $node->safe_psql("postgres", "CREATE TABLE tst (v vector($dim));");
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT random_vector($dim) FROM generate_series(1, 10000) i;" "INSERT INTO tst SELECT ARRAY[$array_sql] FROM generate_series(1, 10000) i;"
); );
$node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);"); $node->safe_psql("postgres", "CREATE INDEX ON tst USING ivfflat (v);");
@@ -26,14 +28,23 @@ $node->pgbench(
[qr{^$}], [qr{^$}],
"concurrent INSERTs", "concurrent INSERTs",
{ {
"007_inserts" => "INSERT INTO tst SELECT random_vector($dim) FROM generate_series(1, 10) i;" "007_inserts" => "INSERT INTO tst SELECT ARRAY[$array_sql] FROM generate_series(1, 10) i;"
} }
); );
sub idx_scan
{
# Stats do not update instantaneously
# https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-VIEWS
sleep(1);
$node->safe_psql("postgres", "SELECT idx_scan FROM pg_stat_user_indexes WHERE indexrelid = 'tst_v_idx'::regclass;");
}
my $expected = 10000 + 5 * 100 * 10; my $expected = 10000 + 5 * 100 * 10;
my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;"); my $count = $node->safe_psql("postgres", "SELECT COUNT(*) FROM tst;");
is($count, $expected); is($count, $expected);
is(idx_scan(), 0);
$count = $node->safe_psql("postgres", qq( $count = $node->safe_psql("postgres", qq(
SET enable_seqscan = off; SET enable_seqscan = off;
@@ -41,3 +52,4 @@ $count = $node->safe_psql("postgres", qq(
SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t; SELECT COUNT(*) FROM (SELECT v FROM tst ORDER BY v <-> (SELECT v FROM tst LIMIT 1)) t;
)); ));
is($count, $expected); is($count, $expected);
is(idx_scan(), 1);

View File

@@ -17,7 +17,7 @@ $node->safe_psql("postgres", "CREATE TABLE tst (v1 vector(1024), v2 vector(1024)
# Test insert succeeds # Test insert succeeds
$node->safe_psql("postgres", $node->safe_psql("postgres",
"INSERT INTO tst SELECT random_vector($dim), random_vector($dim), random_vector($dim)" "INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
); );
# Change storage to PLAIN # Change storage to PLAIN
@@ -27,6 +27,6 @@ $node->safe_psql("postgres", "ALTER TABLE tst ALTER COLUMN v3 SET STORAGE PLAIN"
# Test insert fails # Test insert fails
my ($ret, $stdout, $stderr) = $node->psql("postgres", my ($ret, $stdout, $stderr) = $node->psql("postgres",
"INSERT INTO tst SELECT random_vector($dim), random_vector($dim), random_vector($dim)" "INSERT INTO tst SELECT array_agg(n), array_agg(n), array_agg(n) FROM generate_series(1, $dim) n"
); );
like($stderr, qr/row is too big/); like($stderr, qr/row is too big/);

View File

@@ -1,4 +1,4 @@
comment = 'vector data type and ivfflat access method' comment = 'vector data type and ivfflat access method'
default_version = '0.4.0' default_version = '0.4.1'
module_pathname = '$libdir/vector' module_pathname = '$libdir/vector'
relocatable = true relocatable = true