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

Hope247code/pgvector

 
 

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

Build Status

Installation

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

Getting Started

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]') * -1 AS inner_product FROM 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 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 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 islists / 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.

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;

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
  3. sorting tuples
  4. loading tuples

Note:tuples_done andtuples_total are only populated during theloading tuples phase

Partial Indexes

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

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]' LIMIT 5;

Approximate Search

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

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

Why am I seeing less results after adding an index?

The index was likely created with too little data for the number of lists. Drop the index until the table has more data.

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

OperatorDescription
+element-wise addition
-element-wise subtraction
<->Euclidean distance
<#>negative inner product
<=>cosine distance

Vector Functions

FunctionDescription
cosine_distance(vector, vector) → double precisioncosine distance
inner_product(vector, vector) → double precisioninner product
l2_distance(vector, vector) → double precisionEuclidean distance
vector_dims(vector) → integernumber of dimensions
vector_norm(vector) → double precisionEuclidean norm

Aggregate Functions

FunctionDescription
avg(vector) → vectorarithmetic mean

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

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.4.2 https://github.com/pgvector/pgvector.gitcd pgvectordocker build -t 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

Hosted Postgres

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

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

  • C84.8%
  • Perl12.4%
  • Makefile2.2%
  • Other0.6%

[8]ページ先頭

©2009-2025 Movatter.jp