- Notifications
You must be signed in to change notification settings - Fork0
Open-source vector similarity search for Postgres
License
Hope247code/pgvector
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Open-source vector similarity search for Postgres
Supports
- exact and approximate nearest neighbor search
- L2 distance, inner product, and cosine distance
- anylanguage with a Postgres client
Compile and install the extension (supports Postgres 11+)
cd /tmpgit clone --branch v0.4.2 https://github.com/pgvector/pgvector.gitcd pgvectormakemake install# may need sudo
Then load it in databases where you want to use it
CREATE EXTENSION vector;
See theinstallation notes if you run into issues
You can also install it withDocker,Homebrew,PGXN,APT,Yum, orconda-forge
Create a vector column with 3 dimensions
CREATETABLEitems (idbigserialPRIMARY KEY, embedding vector(3));
Insert vectors
INSERT INTO items (embedding)VALUES ('[1,2,3]'), ('[4,5,6]');
Get the nearest neighbors by L2 distance
SELECT*FROM itemsORDER BY embedding<->'[3,1,2]'LIMIT5;
Also supports inner product (<#>
) and cosine distance (<=>
)
Note:<#>
returns the negative inner product since Postgres only supportsASC
order index scans on operators
Create a new table with a vector column
CREATETABLEitems (idbigserialPRIMARY KEY, embedding vector(3));
Or add a vector column to an existing table
ALTERTABLE items ADD COLUMN embedding vector(3);
Insert vectors
INSERT INTO items (embedding)VALUES ('[1,2,3]'), ('[4,5,6]');
Upsert vectors
INSERT INTO items (id, embedding)VALUES (1,'[1,2,3]'), (2,'[4,5,6]')ON CONFLICT (id) DOUPDATESET embedding=EXCLUDED.embedding;
Update vectors
UPDATE itemsSET embedding='[1,2,3]'WHERE id=1;
Delete vectors
DELETEFROM itemsWHERE id=1;
Get the nearest neighbors to a vector
SELECT*FROM itemsORDER BY embedding<->'[3,1,2]'LIMIT5;
Get the nearest neighbors to a row
SELECT*FROM itemsWHERE id!=1ORDER BY embedding<-> (SELECT embeddingFROM itemsWHERE id=1)LIMIT5;
Get rows within a certain distance
SELECT*FROM itemsWHERE embedding<->'[3,1,2]'<5;
Note: Combine withORDER BY
andLIMIT
to use an index
Get the distance
SELECT embedding<->'[3,1,2]'AS distanceFROM items;
For inner product, multiply by -1 (since<#>
returns the negative inner product)
SELECT (embedding<#> '[3,1,2]') * -1 AS inner_product FROM items;
For cosine similarity, use 1 - cosine distance
SELECT1- (embedding<=>'[3,1,2]')AS cosine_similarityFROM items;
Average vectors
SELECTAVG(embedding)FROM items;
Average groups of vectors
SELECT category_id,AVG(embedding)FROM itemsGROUP BY category_id;
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:
- Create the indexafter the table has some data
- Choose an appropriate number of lists - a good place to start is
rows / 1000
for up to 1M rows andsqrt(rows)
for over 1M rows - When querying, specify an appropriate number ofprobes (higher is better for recall, lower is better for speed) - a good place to start is
lists / 10
for up to 1M rows andsqrt(lists)
for over 1M rows
Add an index for each distance function you want to use.
L2 distance
CREATEINDEXON items USING ivfflat (embedding vector_l2_ops) WITH (lists=100);
Inner product
CREATEINDEXON items USING ivfflat (embedding vector_ip_ops) WITH (lists=100);
Cosine distance
CREATEINDEXON items USING ivfflat (embedding vector_cosine_ops) WITH (lists=100);
Vectors with up to 2,000 dimensions can be indexed.
Specify the number of probes (1 by default)
SETivfflat.probes=10;
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 won’t use the index)
UseSET LOCAL
inside a transaction to set it for a single query
BEGIN;SET LOCALivfflat.probes=10;SELECT ...COMMIT;
Checkindexing progress with Postgres 12+
SELECT phase, tuples_done, tuples_totalFROM pg_stat_progress_create_index;
The phases are:
initializing
performing k-means
sorting tuples
loading tuples
Note:tuples_done
andtuples_total
are only populated during theloading tuples
phase
Considerpartial indexes for queries with aWHERE
clause
SELECT*FROM itemsWHERE category_id=123ORDER BY embedding<->'[3,1,2]'LIMIT5;
can be indexed with:
CREATEINDEXON items USING ivfflat (embedding vector_l2_ops) WITH (lists=100)WHERE (category_id=123);
To index many different values ofcategory_id
, considerpartitioning oncategory_id
.
CREATETABLEitems (embedding vector(3), category_idint) PARTITION BY LIST(category_id);
UseEXPLAIN ANALYZE
to debug performance.
EXPLAIN ANALYZESELECT*FROM itemsORDER BY embedding<->'[3,1,2]'LIMIT5;
To speed up queries without an index, increasemax_parallel_workers_per_gather
.
SET max_parallel_workers_per_gather=4;
If vectors are normalized to length 1 (likeOpenAI embeddings), use inner product for best performance.
SELECT*FROM itemsORDER BY embedding<#> '[3,1,2]' LIMIT 5;
To speed up queries with an index, increase the number of inverted lists (at the expense of recall).
CREATEINDEXON items USING ivfflat (embedding vector_l2_ops) WITH (lists=1000);
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 |
C# | pgvector-dotnet |
Crystal | pgvector-crystal |
Elixir | pgvector-elixir |
Go | pgvector-go |
Haskell | pgvector-haskell |
Java, Scala | pgvector-java |
Julia | pgvector-julia |
Lua | pgvector-lua |
Node.js | pgvector-node |
Perl | pgvector-perl |
PHP | pgvector-php |
Python | pgvector-python |
R | pgvector-r |
Ruby | pgvector-ruby,Neighbor |
Rust | pgvector-rust |
Swift | pgvector-swift |
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.
You’ll need to usedimensionality reduction at the moment.
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
Each vector takes4 * dimensions + 8
bytes of storage. Each element is a single precision floating-point number (like thereal
type in Postgres), and all elements must be finite (noNaN
,Infinity
or-Infinity
). Vectors can have up to 16,000 dimensions.
Operator | Description |
---|---|
+ | element-wise addition |
- | element-wise subtraction |
<-> | Euclidean distance |
<#> | negative inner product |
<=> | cosine distance |
Function | Description |
---|---|
cosine_distance(vector, vector) → double precision | cosine distance |
inner_product(vector, vector) → double precision | inner product |
l2_distance(vector, vector) → double precision | Euclidean distance |
vector_dims(vector) → integer | number of dimensions |
vector_norm(vector) → double precision | Euclidean norm |
Function | Description |
---|---|
avg(vector) → vector | arithmetic mean |
If your machine has multiple Postgres installations, specify the path topg_config with:
export PG_CONFIG=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config
Then re-run the installation instructions (runmake clean
beforemake
if needed). Ifsudo
is needed formake install
, use:
sudo --preserve-env=PG_CONFIG make install
If compilation fails withfatal error: postgres.h: No such file or directory
, make sure Postgres development files are installed on the server.
For Ubuntu and Debian, use:
sudo apt install postgresql-server-dev-15
Note: Replace15
with your Postgres server version
Support for Windows is currently experimental. Usenmake
to build:
set"PGROOT=C:\Program Files\PostgreSQL\15"git clone --branch v0.4.2 https://github.com/pgvector/pgvector.gitcd pgvectornmake /F Makefile.winnmake /F Makefile.win install
Get theDocker image with:
docker pull ankane/pgvector
This adds pgvector to thePostgres image (run it the same way).
You can also build the image manually:
git clone --branch v0.4.2 https://github.com/pgvector/pgvector.gitcd pgvectordocker build -t pgvector.
With Homebrew Postgres, you can use:
brew install pgvector
Note: This only adds it to thepostgresql@14
formula
Install from thePostgreSQL Extension Network with:
pgxn install vector
Debian and Ubuntu packages are available from thePostgreSQL APT Repository. Follow thesetup instructions and run:
sudo apt install postgresql-15-pgvector
Note: Replace15
with your Postgres server version
RPM packages are available from thePostgreSQL Yum Repository. Follow thesetup instructions for your distribution and run:
sudo yum install pgvector_15# orsudo dnf install pgvector_15
Note: Replace15
with your Postgres server version
With Conda Postgres, install fromconda-forge with:
conda install -c conda-forge pgvector
This method iscommunity-maintained by@mmcauliffe
pgvector is available onthese providers.
To request a new extension on other providers:
- Google Cloud SQL - vote or comment onthis page
- DigitalOcean Managed Databases - vote or comment onthis page
- Heroku Postgres - vote or comment onthis page
Install the latest version and run:
ALTER EXTENSION vectorUPDATE;
If upgrading with Postgres < 13, remove this line fromsql/vector--0.3.2--0.4.0.sql
:
ALTERTYPE vectorSET (STORAGE= extended);
Then runmake install
andALTER EXTENSION vector UPDATE;
.
If upgrading from 0.2.7 or 0.3.0, recreate allivfflat
indexes after upgrading to ensure all data is indexed.
-- Postgres 12+REINDEX INDEX CONCURRENTLY index_name;-- Postgres < 12CREATEINDEXCONCURRENTLY temp_nameON table USING ivfflat (column opclass);DROPINDEX CONCURRENTLY index_name;ALTERINDEX 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 thechangelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs andsubmit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
git clone https://github.com/pgvector/pgvector.gitcd pgvectormakemake install
To run all tests:
make installcheck# regression testsmake prove_installcheck# TAP tests
To run single tests:
make installcheck REGRESS=functions# regression testmake 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
About
Open-source vector similarity search for Postgres
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- C84.8%
- Perl12.4%
- Makefile2.2%
- Other0.6%