- Notifications
You must be signed in to change notification settings - Fork0
Open-source vector similarity search for Postgres
License
coderwpf/pgvector
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Open-source vector similarity search for Postgres
Store your vectors with the rest of your data. Supports:
- exact and approximate nearest neighbor search
- L2 distance, inner product, and cosine distance
- anylanguage with a Postgres client
PlusACID compliance, point-in-time recovery, JOINs, and all of the othergreat features of Postgres
Compile and install the extension (supports Postgres 11+)
cd /tmpgit clone --branch v0.5.0 https://github.com/pgvector/pgvector.gitcd pgvectormakemake install# may need sudo
See theinstallation notes if you run into issues
You can also install it withDocker,Homebrew,PGXN,APT,Yum, orconda-forge, and it comes preinstalled withPostgres.app and manyhosted providers
Enable the extension (do this once in each database where you want to use it)
CREATE EXTENSION vector;
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]')*-1AS inner_productFROM 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 speed. Unlike typical indexes, you will see different results for queries after adding an approximate index.
Supported index types are:
An IVFFlat index divides vectors into lists, and then searches a subset of those lists that are closest to the query vector. It has faster build times and uses less memory than HNSW, but has lower query performance (in terms of speed-recall tradeoff).
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
sqrt(lists)
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;
An HNSW index creates a multilayer graph. It has slower build times and uses more memory than IVFFlat, but has better query performance (in terms of speed-recall tradeoff). There’s no training step like IVFFlat, so the index can be created without any data in the table.
Add an index for each distance function you want to use.
L2 distance
CREATEINDEXON items USING hnsw (embedding vector_l2_ops);
Inner product
CREATEINDEXON items USING hnsw (embedding vector_ip_ops);
Cosine distance
CREATEINDEXON items USING hnsw (embedding vector_cosine_ops);
Vectors with up to 2,000 dimensions can be indexed.
Specify HNSW parameters
m
- the max number of connections per layer (16 by default)ef_construction
- the size of the dynamic candidate list for constructing the graph (64 by default)
CREATEINDEXON items USING hnsw (embedding vector_l2_ops) WITH (m=16, ef_construction=64);
Specify the size of the dynamic candidate list for search (40 by default)
SEThnsw.ef_search=100;
A higher value provides better recall at the cost of speed.
UseSET LOCAL
inside a transaction to set it for a single query
BEGIN;SET LOCALhnsw.ef_search=100;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
(IVFFlat only)assigning tuples
(IVFFlat only)loading tuples
Note:tuples_done
andtuples_total
are only populated during theloading tuples
phase
There are a few ways to index nearest neighbor queries with aWHERE
clause
SELECT*FROM itemsWHERE category_id=123ORDER BY embedding<->'[3,1,2]'LIMIT5;
Create an index on oneor more of theWHERE
columns for exact search
CREATEINDEXON items (category_id);
Or apartial index on the vector column for approximate search
CREATEINDEXON items USING ivfflat (embedding vector_l2_ops) WITH (lists=100)WHERE (category_id=123);
Usepartitioning for approximate search on many different values of theWHERE
columns
CREATETABLEitems (embedding vector(3), category_idint) PARTITION BY LIST(category_id);
Use together with Postgresfull-text search for hybrid search (Python example).
SELECT id, contentFROM items, plainto_tsquery('hello search') queryWHERE textsearch @@ queryORDER BY ts_rank_cd(textsearch, query)DESCLIMIT5;
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]'LIMIT5;
To speed up queries with an IVFFlat 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 |
Dart | pgvector-dart |
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 cost estimation in pgvector < 0.4.3 does not always work well with the planner. You can encourage the planner to use an index for a query with:
BEGIN;SET LOCAL enable_seqscan= off;SELECT ...COMMIT;
The planner doesn’t considerout-of-line storage in cost estimates, which can make a serial scan look cheaper. You can reduce the cost of a parallel scan for a query with:
BEGIN;SET LOCAL min_parallel_table_scan_size=1;SET LOCAL parallel_setup_cost=1;SELECT ...COMMIT;
or choose to store vectors inline:
ALTERTABLE items ALTER COLUMN embeddingSET STORAGE PLAIN;
The index was likely created with too little data for the number of lists. Drop the index until the table has more data.
DROPINDEX index_name;
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 | Added |
---|---|---|
+ | element-wise addition | |
- | element-wise subtraction | |
* | element-wise multiplication | 0.5.0 |
<-> | Euclidean distance | |
<#> | negative inner product | |
<=> | cosine distance |
Function | Description | Added |
---|---|---|
cosine_distance(vector, vector) → double precision | cosine distance | |
inner_product(vector, vector) → double precision | inner product | |
l2_distance(vector, vector) → double precision | Euclidean distance | |
l1_distance(vector, vector) → double precision | taxicab distance | 0.5.0 |
vector_dims(vector) → integer | number of dimensions | |
vector_norm(vector) → double precision | Euclidean norm |
Function | Description | Added |
---|---|---|
avg(vector) → vector | average | |
sum(vector) → vector | sum | 0.5.0 |
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. EnsureC++ support in Visual Studio is installed, and run:
call"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat"
Note: The exact path will vary depending on your Visual Studio version and edition
Then usenmake
to build:
set"PGROOT=C:\Program Files\PostgreSQL\15"git clone --branch v0.5.0 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.5.0 https://github.com/pgvector/pgvector.gitcd pgvectordocker build --build-arg PG_MAJOR=15 -t myuser/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
Download thelatest release with Postgres 15+.
pgvector is available onthese providers.
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
- Efficient and Robust Approximate Nearest Neighbor Search using Hierarchical Navigable Small World Graphs
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
- C86.4%
- Perl12.3%
- Other1.3%