Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

pgvector

> 编程语言
Open source

Open-source vector similarity search for Postgres

22.4K stars0 likes2 views
WebsiteGitHub

About

Open-source vector similarity search for Postgres

pgvector

Open-source vector similarity search for Postgres

Store your vectors with the rest of your data. Supports:

  • exact and approximate nearest neighbor search
  • single-precision, half-precision, binary, and sparse vectors
  • L2 distance, inner product, cosine distance, L1 distance, Hamming distance, and Jaccard distance
  • any language with a Postgres client

Plus ACID compliance, point-in-time recovery, JOINs, and all of the other great features of Postgres

Have a lot of vectors? Use quantization to scale

Installation

Linux and Mac

Compile and install the extension (supports Postgres 13+)

bash
cd /tmp
git clone --branch v0.8.6 https://github.com/pgvector/pgvector.git
cd pgvector
make
make install # may need sudo

See the installation notes if you run into issues

You can also install it with Docker, Homebrew, PGXN, APT, Yum, pkg, APK, or conda-forge, and it comes preinstalled with Postgres.app and many hosted providers. There are also instructions for GitHub Actions.

Windows

Ensure C++ support in Visual Studio is installed and run x64 Native Tools Command Prompt for VS [version] as administrator. Then use nmake to build:

cmd
set "PGROOT=C:\Program Files\PostgreSQL\18"
cd %TEMP%
git clone --branch v0.8.6 https://github.com/pgvector/pgvector.git
cd pgvector
nmake /F Makefile.win
nmake /F Makefile.win install

See the installation notes if you run into issues

You can also install it with Docker or conda-forge.

Getting Started

Enable the extension (do this once in each database where you want to use it)

tsql
CREATE EXTENSION vector;

Create a vector column with 3 dimensions

sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));

Insert vectors

sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');

Get the nearest neighbors by L2 distance

sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;

Also supports inner product (<#>), cosine distance (<=>), and L1 distance (<+>)

Note: <#> returns the negative inner product since Postgres only supports ASC order index scans on operators

Storing

Create a new table with a vector column

sql
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));

Or add a vector column to an existing table

sql
ALTER TABLE items ADD COLUMN embedding vector(3);

Also supports half-precision, binary, and sparse vectors

Insert vectors

sql
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');

Or load vectors in bulk using COPY (example)

sql
COPY items (embedding) FROM STDIN WITH (FORMAT BINARY);

Upsert vectors

sql
INSERT INTO items (id, embedding) VALUES (1, '[1,2,3]'), (2, '[4,5,6]')
    ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;

Update vectors

sql
UPDATE items SET embedding = '[1,2,3]' WHERE id = 1;

Delete vectors

sql
DELETE FROM items WHERE id = 1;

Querying

Get the nearest neighbors to a vector

sql
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;

Supported distance functions are:

  • <-> - L2 distance
  • <#> - (negative) inner product
  • <=> - cosine distance
  • <+> - L1 distance
  • <~> - Hamming distance (binary vectors)
  • <%> - Jaccard distance (binary vectors)

Get the nearest neighbors to a row

sql
SELECT * FROM items WHERE id != 1 ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1) LIMIT 5;

Get rows within a certain distance

sql
SELECT * FROM items WHERE embedding <-> '[3,1,2]' < 5;

Note: Combine with ORDER BY and LIMIT to use an index

Distances

Get the distance

sql
SELECT embedding <-> '[3,1,2]' AS distance FROM items;

For inner product, multiply by -1 (since <#> returns the negative inner product)

tsql
SELECT (embedding <#> '[3,1,2]') * -1 AS inner_product FROM items;

For cosine similarity, use 1 - cosine distance

sql
SELECT 1 - (embedding <=> '[3,1,2]') AS cosine_similarity FROM items;

Aggregates

Average vectors

sql
SELECT AVG(embedding) FROM items;

Average groups of vectors

sql
SELECT category_id, AVG(embedding) FROM items GROUP 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:

  • HNSW
  • IVFFlat

HNSW

An HNSW index creates a multilayer graph. It has better query performance than IVFFlat (in terms of speed-recall tradeoff), but has slower build times and uses more memory. Also, an index can be created without any data in the table since there isn’t a training step like IVFFlat.

Add an index for each distance function you want to use.

L2 distance

sql
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);

Note: Use halfvec_l2_ops for halfvec and sparsevec_l2_ops for sparsevec (and similar with the other distance functions)

Inner product

sql
CREATE INDEX ON items USING hnsw (embedding vector_ip_ops);

Cosine distance

sql
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);

L1 distance

sql
CREATE INDEX ON items USING hnsw (embedding vector_l1_ops);

Hamming distance

sql
CREATE INDEX ON items USING hnsw (embedding bit_hamming_ops);

Jaccard distance

sql
CREATE INDEX ON items USING hnsw (embedding bit_jaccard_ops);

Supported types are:

  • vector - up to 2,000 dimensions
  • halfvec - up to 4,000 dimensions
  • bit - up to 64,000 dimensions
  • sparsevec - up to 1,000 non-zero elements

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)
sql
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WITH (m = 16, ef_construction = 64);

A higher value of ef_construction provides better recall at the cost of index build time / insert speed.

Query Options

Specify the size of the dynamic candidate list for search (40 by default)

sql
SET hnsw.ef_search = 100;

A higher value provides better recall at the cost of speed.

Use SET LOCAL inside a transaction to set it for a single query

sql
BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT ...
COMMIT;

Index Build Time

Indexes build significantly faster when the graph fits into maintenance_work_mem

sql
SET maintenance_work_mem = '8GB';

A notice is shown when the graph no longer fits

NOTICE:  hnsw graph no longer fits into maintenance_work_mem after 100000 tuples
DETAIL:  Building will take significantly more time.
HINT:  Increase maintenance_work_mem to speed up builds.

Note: Do not set maintenance_work_mem so high that it exhausts the memory on the server

Like other index types, it’s faster to create an index after loading your initial data

You can also speed up index creation by increasing the number of parallel workers (2 by default)

sql
SET max_parallel_maintenance_workers = 7; -- plus leader

For a large number of workers, you may need to increase max_parallel_workers (8 by default)

The index options also have a significant impact on build time (use the defaults unless seeing low recall)

Use binary quantization for faster build times at scale

Indexing Progress

Check indexing progress

sql
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;

The phases for HNSW are:

  1. initializing
  2. loading tuples

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 index after the table has some data
  2. Choose an appropriate number of lists - a good place to start is rows / 1000 for up to 1M rows and sqrt(rows) for over 1M rows
  3. When querying, specify an appropriate number of probes (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

sql
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);

Note: Use halfvec_l2_ops for halfvec (and similar with the other distance functions)

Inner product

sql
CREATE INDEX ON items USING ivfflat (embedding vector_ip_ops) WITH (lists = 100);

Cosine distance

sql
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);

Hamming distance

sql
CREATE INDEX ON items USING ivfflat (embedding bit_hamming_ops) WITH (lists = 100);

Supported types are:

  • vector - up to 2,000 dimensions
  • halfvec - up to 4,000 dimensions
  • bit - up to 64,000 dimensions

Query Options

Specify the number of probes (1 by default)

sql
SET ivfflat.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)

Use SET LOCAL inside a transaction to set it for a single query

sql
BEGIN;
SET LOCAL ivfflat.probes = 10;
SELECT ...
COMMIT;

Index Build Time

Speed up index creation on large tables by increasing the number of parallel workers (2 by default)

sql
SET max_parallel_maintenance_workers = 7; -- plus leader

For a large number of workers, you may also need to increase max_parallel_workers (8 by default)

Indexing Progress

Check indexing progress

sql
SELECT phase, round(100.0 * tuples_done / nullif(tuples_total, 0), 1) AS "%" FROM pg_stat_progress_create_index;

The phases for IVFFlat are:

  1. initializing
  2. performing k-means
  3. assigning tuples
  4. loading tuples

Note: % is only populated during the loading tuples phase

Filtering

There are a few ways to index nearest neighbor queries with a WHERE clause.

sql
SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIMIT 5;

A good place to start is creating an index on the filter column. This can provide fast, exact nearest neighbor search in many cases. Postgres has a number of index types for this: B-tree (default), hash, GiST, SP-GiST, GIN, and BRIN.

sql
CREATE INDEX ON items (category_id);

For multiple columns, consider a multicolumn index.

sql
CREATE INDEX ON items (location_id, category_id);

Exact indexes work well for conditions that match a low percentage of rows. Otherwise, approximate indexes can work better.

sql
CREATE INDEX ON ite

Issues· 17 open

View all issuesOpen on GitHub
  • #846

    Unexpected use of Index Scan in ANN query without LIMIT or enable_indexscan

    Updated Sep 25, 2026
  • #1025

    HNSW: insertPage rewinds to unfittable deleted slots after VACUUM, causing near-full index scan per insert with variable-size types (sparsevec) — reproduction for #975

    Updated Sep 25, 2026
  • #906

    Plans to adopt PostgreSQL 18 parallel I/O for index page reads?

    Updated Sep 23, 2026
  • #1003

    Support RabitQ in pgvector

    Updated Sep 18, 2026
  • #27

    Ideas

    Updated Sep 10, 2026
  • #761

    Enhancement: multicolumn vector index design

    Updated Aug 18, 2026
  • #521

    Are either int8 or fp8 vectors planned?

    Updated Aug 7, 2026
  • #749

    Enhancement: Increase 1,000 non-zero elements limit to 1,200 for sparsevec when creating HNSW index

    Updated Apr 20, 2026
  • #235

    RFC: Setting search defaults as an index option

    Updated Feb 28, 2024

> Tags

Capproximate-nearest-neighbor-searchnearest-neighbor-search

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言