Open-source vector similarity search for Postgres
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
Compile and install the extension (supports Postgres 10+)
git clone --branch v0.3.2 https://github.com/pgvector/pgvector.git
cd pgvector
make
make install # may need sudo
Then load it in databases where you want to use it
CREATE EXTENSION vector;
You can also install it with Docker, Homebrew, or PGXN
Create a vector column with 3 dimensions
CREATE TABLE items (embedding vector(3));
Insert values
INSERT INTO items VALUES ('[1,2,3]'), ('[4,5,6]');
Get the nearest neighbor by L2 distance
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 1;
Also supports inner product (<#>
) and cosine distance (<=>
)
Note: <#>
returns the negative inner product since Postgres only supports ASC
order index scans on operators
Speed up queries with an approximate index. Add an index for each distance function you want to use.
L2 distance
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops);
Inner product
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops);
Cosine distance
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.
Specify the number of inverted lists (100 by default)
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
A good place to start is 4 * sqrt(rows)
Specify the number of probes (1 by default)
SET ivfflat.probes = 1;
A higher value improves recall at the cost of speed.
Use SET LOCAL
inside a transaction to set it for a single query
BEGIN;
SET LOCAL ivfflat.probes = 1;
SELECT ...
COMMIT;
Check indexing progress with Postgres 12+
SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index;
The phases are:
initializing
sampling table
performing k-means
sorting tuples
loading tuples
Note: tuples_done
and tuples_total
are only populated during the loading tuples
phase
Consider partial indexes for queries with a WHERE
clause
SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
can be indexed with:
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WHERE (category_id = 123);
To index many different values of category_id
, consider partitioning on category_id
.
CREATE TABLE items (embedding vector(3), category_id int) PARTITION BY LIST(category_id);
To speed up queries without an index, increase max_parallel_workers_per_gather
.
SET max_parallel_workers_per_gather = 4;
To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 1000);
Each vector takes 4 * dimensions + 8
bytes of storage. Each element is a float, and all elements must be finite (no NaN
, Infinity
or -Infinity
). Vectors can have up to 1024 dimensions.
Operator | Description |
---|---|
+ | element-wise addition |
- | element-wise subtraction |
<-> | Euclidean distance |
<#> | negative inner product |
<=> | cosine distance |
Function | Description |
---|---|
cosine_distance(vector, vector) | cosine distance |
inner_product(vector, vector) | inner product |
l2_distance(vector, vector) | Euclidean distance |
vector_dims(vector) | number of dimensions |
vector_norm(vector) | Euclidean norm |
Libraries that use pgvector:
- pgvector-python (Python)
- Neighbor (Ruby)
- pgvector-ruby (Ruby)
- pgvector-node (Node.js)
- pgvector-go (Go)
- pgvector-php (PHP)
- pgvector-rust (Rust)
- pgvector-cpp (C++)
- pgvector-elixir (Elixir)
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.
Yes, pgvector uses the write-ahead log (WAL), which allows for replication and point-in-time recovery.
Two things you can try are:
- use dimensionality reduction
- compile Postgres with a larger block size (
./configure --with-blocksize=32
) and edit the limit insrc/vector.h
Get the Docker image with:
docker pull ankane/pgvector
This adds pgvector to the Postgres image.
You can also build the image manually
git clone --branch v0.3.2 https://github.com/pgvector/pgvector.git
cd pgvector
docker build -t pgvector .
With Homebrew Postgres, you can use:
brew install pgvector/brew/pgvector
Install from the PostgreSQL Extension Network with:
pgxn install vector
Some Postgres providers only support specific extensions. To request a new extension:
- Amazon RDS - follow the instructions on this page
- Google Cloud SQL - follow the instructions on this page
- DigitalOcean Managed Databases - vote or comment on this page
- Azure Database for PostgreSQL - follow the instructions on this page
Install the latest version and run:
ALTER EXTENSION vector UPDATE;
If upgrading from 0.2.7 or 0.3.0, recreate all ivfflat
indexes after upgrading to ensure all data is indexed.
-- Postgres 12+
REINDEX INDEX CONCURRENTLY index_name;
-- Postgres < 12
CREATE INDEX CONCURRENTLY temp_name ON table USING ivfflat (column opclass);
DROP INDEX CONCURRENTLY index_name;
ALTER INDEX temp_name RENAME TO index_name;
Thanks to:
- PASE: PostgreSQL Ultra-High-Dimensional Approximate Nearest Neighbor Search Extension
- Faiss: A Library for Efficient Similarity Search and Clustering of Dense Vectors
- Using the Triangle Inequality to Accelerate k-means
- k-means++: The Advantage of Careful Seeding
- Concept Decompositions for Large Sparse Text Data using Clustering
View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
git clone https://github.com/pgvector/pgvector.git
cd pgvector
make
make install
To run all tests:
make installcheck # regression tests
make prove_installcheck # TAP tests
To run single tests:
make installcheck REGRESS=functions # regression test
make prove_installcheck PROVE_TESTS=test/t/001_wal.pl # TAP test
To enable benchmarking:
make clean && PG_CFLAGS=-DIVFFLAT_BENCH make && make install
Resources for contributors