Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Open-source vector similarity search for Postgres

License

NotificationsYou must be signed in to change notification settings

coderwpf/pgvector

 
 

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

Build Status

Installation

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

Getting Started

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

Storing

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;

Querying

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

Distances

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;

Aggregates

Average vectors

SELECTAVG(embedding)FROM items;

Average groups of vectors

SELECT category_id,AVG(embedding)FROM itemsGROUP BY category_id;

Indexing

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:

IVFFlat

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:

  1. Create the indexafter the table has some data
  2. Choose an appropriate number of lists - a good place to start isrows / 1000 for up to 1M rows andsqrt(rows) for over 1M rows
  3. When querying, specify an appropriate number ofprobes (higher is better for recall, lower is better for speed) - a good place to start issqrt(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.

Query Options

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;

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.

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.

Index Options

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);

Query Options

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;

Indexing Progress

Checkindexing progress with Postgres 12+

SELECT phase, tuples_done, tuples_totalFROM pg_stat_progress_create_index;

The phases are:

  1. initializing
  2. performing k-means (IVFFlat only)
  3. assigning tuples (IVFFlat only)
  4. loading tuples

Note:tuples_done andtuples_total are only populated during theloading tuples phase

Filtering

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);

Hybrid Search

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;

Performance

UseEXPLAIN ANALYZE to debug performance.

EXPLAIN ANALYZESELECT*FROM itemsORDER BY embedding<->'[3,1,2]'LIMIT5;

Exact Search

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;

Approximate Search

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);

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.

LanguageLibraries / Examples
C++pgvector-cpp
C#pgvector-dotnet
Crystalpgvector-crystal
Dartpgvector-dart
Elixirpgvector-elixir
Gopgvector-go
Haskellpgvector-haskell
Java, Scalapgvector-java
Juliapgvector-julia
Luapgvector-lua
Node.jspgvector-node
Perlpgvector-perl
PHPpgvector-php
Pythonpgvector-python
Rpgvector-r
Rubypgvector-ruby,Neighbor
Rustpgvector-rust
Swiftpgvector-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?

You’ll need to usedimensionality reduction at the moment.

Troubleshooting

Why isn’t a query using an index?

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;

Why isn’t a query using a parallel table scan?

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;

Why are there less results for a query after adding an IVFFlat index?

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;

Reference

Vector Type

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.

Vector Operators

OperatorDescriptionAdded
+element-wise addition
-element-wise subtraction
*element-wise multiplication0.5.0
<->Euclidean distance
<#>negative inner product
<=>cosine distance

Vector Functions

FunctionDescriptionAdded
cosine_distance(vector, vector) → double precisioncosine distance
inner_product(vector, vector) → double precisioninner product
l2_distance(vector, vector) → double precisionEuclidean distance
l1_distance(vector, vector) → double precisiontaxicab distance0.5.0
vector_dims(vector) → integernumber of dimensions
vector_norm(vector) → double precisionEuclidean norm

Aggregate Functions

FunctionDescriptionAdded
avg(vector) → vectoraverage
sum(vector) → vectorsum0.5.0

Installation Notes

Postgres Location

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

Missing Header

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

Windows

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

Additional Installation Methods

Docker

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.

Homebrew

With Homebrew Postgres, you can use:

brew install pgvector

Note: This only adds it to thepostgresql@14 formula

PGXN

Install from thePostgreSQL Extension Network with:

pgxn install vector

APT

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

Yum

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

conda-forge

With Conda Postgres, install fromconda-forge with:

conda install -c conda-forge pgvector

This method iscommunity-maintained by@mmcauliffe

Postgres.app

Download thelatest release with Postgres 15+.

Hosted Postgres

pgvector is available onthese providers.

Upgrading

Install the latest version and run:

ALTER EXTENSION vectorUPDATE;

Upgrade Notes

0.4.0

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;.

0.3.1

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

Thanks to:

History

View thechangelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C86.4%
  • Perl12.3%
  • Other1.3%

[8]ページ先頭

©2009-2025 Movatter.jp