pgvector for vector search in PostgreSQL

pgvector adds vector similarity search to a PostgreSQL database you already run. This page covers the index, distance and sizing decisions, the build sequence, and when a dedicated vector database such as Qdrant is the better fit.

On this page

Why teams add pgvector to the PostgreSQL they already operate

A team that needs similarity search over embeddings and already runs PostgreSQL with backups, replication and access controls can often keep those vectors in the same database as its relational data. The pgvector extension stores vectors in a column type and runs nearest-neighbor queries with ordinary SQL, so the work shifts to index choice, sizing and operations rather than to a new service. Those operations are the part to plan carefully: the index type, the distance function, the memory the index needs and the time a build takes on your data volume all decide whether the system performs well and stays recoverable. This module implementation covers those decisions for a PostgreSQL cluster you control, including the extension install, index design, query tests, backup and restore checks for vector columns, and the access rules that apply to embedding data.

PostgreSQL is released under the PostgreSQL License, a permissive license similar to the BSD and MIT licenses, so the database and its extensions can be deployed without a license fee. pgvector runs on the same PostgreSQL platform described in the pillar, which means it inherits the same major version support windows, the same upgrade paths and the same authentication and replication choices. Confirm with your own team which PostgreSQL major version you run and whether the pgvector release you plan to install supports it, since extension versions must match the server. Teams often bring in a partner when the first index build or the first load test shows that memory or build time is larger than expected, when the search workload needs to grow past one server, or when a security review asks how embedding data is protected and logged. A partner can also help decide whether a dedicated vector database such as Qdrant is the better fit for the workload, a question this page addresses in its later sections.

What pgvector adds to PostgreSQL

pgvector adds vector search to a PostgreSQL server you already run, so embeddings, metadata and access rules can share one database. The cards cover the decisions that shape results: how vectors are stored, whether a query is exact or approximate, which index you build, and how filters interact with ranking. Confirm type limits, operator names and parameter defaults against the pgvector documentation for your version before you commit to a design.

Vector column types

pgvector adds a vector data type, so embeddings sit in ordinary tables beside the rows they describe. The dimension is fixed in the column definition, which means a change of embedding model usually requires re-embedding and rewriting every stored vector. Confirm the supported dimension limit and any reduced-precision types in the pgvector documentation for your release before you size the column.

Exact nearest-neighbor search

Without an index, a query orders rows by their distance to the query vector and scans the table, so results are exact. This makes exact search a useful baseline for measuring how much recall an approximate index gives up on your own data. Cost rises with row count and dimension, so exact search fits smaller tables or pre-filtered subsets. Check the ORDER BY pattern and distance operators in the documentation for your version.

HNSW index

HNSW is a graph-based approximate index that trades build time and memory for query speed and recall. Build parameters are set when the index is created, and search parameters can be adjusted at query time, so tune both against a labeled sample of your queries. Large builds can take a long time and use substantial memory, so plan them as a maintenance task. Confirm parameter names and defaults in the pgvector docs.

IVFFlat index

IVFFlat divides vectors into lists and searches only a subset of lists at query time. The lists are built from rows that already exist, so an index created on an empty or small table can give poor recall until it is rebuilt. Compare build time, memory use and recall with HNSW on your own data before choosing between them. Confirm the list-count guidance and probe setting in the pgvector documentation.

Filters with SQL predicates

WHERE clauses combine with vector ordering in one query, so tenant, status and date filters run in the same database as the search. Restrictive predicates can change whether the planner uses an approximate index, and an approximate index can return fewer rows than a LIMIT requests. Run EXPLAIN and compare results on production-shaped data, and review the iterative scan options in the documentation for your version.

Distance operator choice

pgvector provides several distance operators, and the distance should match how the embedding model was trained. A mismatch does not raise an error; it quietly degrades ranking, which makes it hard to notice in production. Check the model documentation for the recommended metric, and confirm the operator names and any normalization guidance in the pgvector docs for your version.

Choosing HNSW or IVFFlat for your workload

HNSW (hierarchical navigable small world) builds a layered graph over your vectors. Queries start at a sparse top layer and move down through denser layers toward the nearest neighbors, which keeps search fast without scanning the whole table. In pgvector, the main knobs are the graph connectivity set at build time and the search breadth used at query time, which you adjust per session. Because the graph is built incrementally, new rows can be inserted without rebuilding the index, although heavy churn still degrades the graph over time.

  • Build model: the index is a multi-layer graph, so construction does more work per row than a simple partition assignment.
  • Query tuning: search breadth is set per session, so the same index can serve lower-latency and higher-recall queries.
  • Insert behavior: new vectors are added to the graph as they arrive, which suits tables that grow continuously.
  • Memory: the graph and vectors are kept in memory for good speed, so index size should be checked against available RAM.
  • Deletes and updates: dead entries accumulate until vacuum runs, so write-heavy tables need monitoring for index quality.

Before you commit, confirm the pgvector version and the parameter names in its documentation for your PostgreSQL major, then measure recall on a sample of your own queries.

Configuration decisions that shape the build

This table compares the configuration choices that determine how pgvector behaves once data is loaded and queried. Read each row as a decision to settle with the application team and the embedding model provider before the schema is created. The main takeaway is that distance function, dimension and filter design are hard to change later without re-embedding or rebuilding indexes.

DecisionOptions and when each fitsWhat to confirm with the embedding model provider
Index typeHNSW suits most query-heavy workloads where recall and latency matter and the team can afford the memory and longer build time. IVFFlat builds faster and uses less memory, but needs a sensible list count and recall depends on probe settings. Without an index, exact search scans every row and may be acceptable for small tables.Confirm the expected vector count and growth rate, since index build time and memory scale with both. Ask whether the provider publishes recall or quality figures for the chosen dimension.
Distance function (cosine, inner product, L2)Use the operator class that matches how the model was trained. Cosine distance is common for text embeddings. Inner product suits normalized vectors and avoids extra computation. L2 fits models that define similarity by Euclidean distance. A mismatch returns plausible but poor rankings.Confirm the recommended distance metric in the model documentation, and whether vectors are normalized before storage. Ask whether the metric changes across model versions.
Vector dimension and storage typeDimension is fixed per column and drives row size and index memory. Full-precision vectors are the default. Half-precision or reduced-dimension options can lower storage but need validation of retrieval quality. Confirm the column type supports the dimension you plan to use and the index method applies to it.Confirm the output dimension, whether the provider supports shortened or truncated output, and the supported precision of returned values. Ask how dimension changes are handled across model upgrades.
Index before or after bulk loadLoading first and then building the index is usually faster for large initial imports. Indexing first slows inserts but keeps the index current for incremental loads. For IVFFlat, the lists are chosen from data present at build time, so a build on a near-empty table gives poor partitioning.Ask how often embeddings will be regenerated, and whether a full re-embedding would require a complete index rebuild.
Filter strategy with SQL predicatesFilters such as tenant, status or date are combined with the vector order clause in one query. Approximate indexes can return fewer matching rows than requested when a selective filter removes candidates, so teams often use partial indexes, iterative scan settings or narrow predicates. Test filtered queries against realistic selectivity.Not a provider question. Confirm with the application owners which metadata filters are mandatory for access control and how they are stored alongside vectors.
Partitioning by tenant or timePartitioning fits when tenants have very different sizes, retention rules must drop whole periods, or per-partition indexes keep builds manageable. Many small tenants may be better served by a shared table with a tenant column and row-level security. Partitioning adds planning and maintenance overhead.Confirm whether embeddings from different model versions will coexist, since that may require separate partitions or columns per model.

How the pgvector implementation runs, step by step

This sequence takes vector search from a version check to a production index that your team has measured against its own queries, is covered by replication and backups, and can be rolled back if results disappoint.

  1. Confirm the PostgreSQL and pgvector version pairing

    Start by recording the PostgreSQL major version you run and the pgvector release you intend to install, then check that the extension build matches that major version on every node. Confirm the supported window for your PostgreSQL major, since PostgreSQL 14 ends in November 2026 and 15 in November 2027, so a new vector workload should not start on a version close to end of life. The output is a short compatibility record naming both versions, the packaging source and the owner who signed off. Confirm the exact pgvector release notes with the project before you pin a version, because the pairing rules are the project's to state.

  2. Size memory and disk for vector data

    Estimate the row count, vector dimension and element type for each embedded table, then calculate the raw storage for the vectors and the extra space each index will need. HNSW indexes usually need more memory and disk than IVFFlat, and both grow with the data, so size against the largest expected table rather than today's sample. Include headroom for index rebuilds, WAL growth during bulk loads and the backup copies that will hold the same data. The output is a sizing note with assumptions written down, which the team reviews against the host's RAM, shared buffers and disk throughput.

  3. Load a representative sample dataset

    Load a sample that reflects real data: the same embedding model, dimension, filters, tenant splits and value distribution your application will use. Keep the embedding model and version fixed and record them, because vectors from different models cannot be compared. Run the load on a non-production instance first and note load time, table size and the effect on other workloads. The output is a loaded sample and a load record with row counts, timings and the exact embedding pipeline used, so later results can be reproduced.

  4. Build and compare indexes against your own queries

    Create candidate indexes, HNSW and IVFFlat with the parameters you plan to test, and run your own query set against each one with the distance operator your application uses. Measure recall against an exact search over the same sample, query latency under realistic concurrency, index build time and index size. Repeat with filters that match production, because filtered search can change results and speed. The output is a benchmark record listing each index configuration, the recall and latency numbers, build cost and the chosen setting with the reason it won.

  5. Set replication and backup coverage for the indexes

    Confirm that streaming replicas receive the vector tables and their indexes, and that a promoted standby can serve the same queries after failover. Check that base backups and archived WAL cover the extension and the index data, and that the restore procedure includes reinstalling the matching extension version. Plan how the index is rebuilt after a restore if your recovery path does not carry it, and time that rebuild on the sample. The output is a tested restore: a restored copy that runs the agreed queries and returns the same results as the source.

  6. Roll out with a tested rollback path

    Release the index in stages, first to a limited set of queries or a canary application path, and watch latency, error rates and recall-sensitive results. Keep the previous retrieval path or the exact search fallback available until the new index has run through normal traffic and a planned maintenance window. Write down the steps to drop the index, switch the application back and restore the prior configuration, and rehearse them once. The output is a signed rollout record with the rollback steps tested, the monitoring thresholds in place and the named owner who can call a rollback.

Keeping vector indexes recoverable and highly available

A pgvector index is ordinary PostgreSQL data, so its availability and recoverability come from the database cluster around it, not from anything specific to vectors. Streaming replicas copy the write-ahead log to standbys, and hot standby servers can serve read-only similarity queries, which is useful for read-heavy retrieval. The choice to make is between synchronous commit, where a transaction waits for standbys before it is confirmed, and asynchronous replication, where a failover can lose the most recent committed embeddings. Decide that per table or per workload, because embeddings that can be regenerated from source documents may tolerate asynchronous replication, while the source rows and their metadata usually should not.

Point-in-time recovery combines a base backup with archived WAL files, and the same mechanism restores vector columns and their indexes. Be aware that PostgreSQL does not detect a failed primary or promote a standby by itself, so automatic failover depends on an external tool that you select, configure and test. Confirm which tool your team will run, how it fences the old primary, and how clients reach the new primary after promotion.

The operational cost that teams often miss is rebuilding large HNSW or IVFFlat indexes after a restore or a major upgrade. Replaying WAL restores the index pages, but a logical restore from a dump or a dump-based migration needs the index built again, and that build is CPU and memory intensive on a table with millions of vectors. Measure how long a build takes on a copy of production data before go-live, and plan the restore order so the application can serve traffic while indexes complete. Before go-live, run a restore drill that covers a failed primary, a failover, a point-in-time restore to a chosen moment, and a timed index rebuild, and check that query results and recall match the pre-failure baseline.

What drives effort and cost in a pgvector build

This table lists the factors that change how much work a pgvector build takes and which ones a partner should price separately. Read each row as a lever: the first column names the driver, the middle column says how it moves effort, and the last column lists what to ask for in a quote. The main takeaway is that vector count, recall targets and the embedding pipeline usually matter more to scope than the extension installation itself.

DriverEffect on effort and costWhat to ask a partner to price
Vector count and dimensionMore vectors and higher dimensions increase index build time, memory use and disk for both HNSW and IVFFlat indexes. Load and index tests are needed before sizing the server.Sizing test at your expected vector count and dimension, with build time and memory measured on your hardware
Recall and latency targetsTighter recall and latency goals require index parameter tuning, repeated query benchmarks and a clear definition of acceptable results. Looser targets are cheaper to meet.Benchmark plan with a labeled test dataset, recall measurement method and the number of tuning rounds included
Filter complexityQueries that combine vector search with metadata filters, joins or range conditions need planning of indexes on filter columns and may need changes to query shape. Simple equality filters are the least work.Review of every filter pattern the application uses, with query plans checked against the chosen index
Number of tenantsMulti-tenant data raises the design work on row-level isolation, per-tenant indexing choices and noisy-neighbor testing. A single tenant keeps the design simple.Tenant isolation design, access control tests and whether one index or per-tenant partitions are assumed
Replication and backup requirementsVector indexes are part of the database, so standbys and point-in-time recovery carry the same data. Recovery targets and restore tests add work, and rebuilt indexes after restore can take time.Replication topology, backup schedule, restore test and the measured time to rebuild indexes on a restored copy
PostgreSQL upgrade pathMajor upgrades must keep the pgvector extension in step with the new PostgreSQL major version, and index behavior should be retested afterward. Planning the upgrade route early avoids rework.Upgrade plan naming the target PostgreSQL major, the pgvector version pairing and the post-upgrade test set
Embedding pipeline ownershipWho creates, stores and refreshes embeddings often costs more than the database work. Re-embedding after a model change means reprocessing every vector, so ownership and versioning should be decided first.Scope of the ingestion pipeline, the model version tracking method and the plan for re-embedding existing data

How embeddings move from application to pgvector index

The flow starts in the application or embedding pipeline, which calls an embedding model and writes vectors as rows in a PostgreSQL table. The pgvector index is built on that column and updated as rows change, so writes and index maintenance happen in the same database transaction path. Queries arrive through the application, combine vector distance ordering with ordinary SQL filters on tenant or status columns, and return rows from the same server. Check where the embedding model runs, which parts sit inside the trust boundary, and whether the streaming replica and off-site backup copies carry the same access controls as the primary.

Embedding writes, filtered queries, replication and off-site backup inside the client's infrastructure.

When a dedicated vector database fits better

pgvector keeps vectors next to your relational data, which suits many workloads. Some requirements point toward a dedicated engine such as Qdrant, which spreads collections across nodes and runs its own replication. The cards below describe the situations where that trade-off becomes worth testing, and what to check on your own data before deciding.

Very large collections needing sharding

When a collection outgrows what one PostgreSQL server can index and serve at acceptable latency, you need to split vectors across machines. Qdrant distributed mode splits a collection into shards across nodes, coordinated by the Raft consensus protocol. With pgvector, horizontal scaling means adding a sharding layer of your own. Measure index size and query latency on a copy of your real vectors before choosing.

Minimum for production
3 nodes
Qdrant distributed docs

Separate scaling of search and transactions

If vector search traffic grows much faster than your transactional workload, sharing one database means every search competes with order processing for CPU, memory and I/O. A dedicated engine lets you add search capacity without resizing the primary database. Check whether your peak search load and your peak transaction load actually overlap before you split them.

Built-in replication with a replication factor

Qdrant keeps extra copies of each shard through a replication factor, and that factor doubles storage at a factor of 2. In PostgreSQL, you get copies through streaming replication, but the replicas hold whole-database copies managed by separate tooling. Decide whether shard-level copies or database-level standbys match your recovery targets, and price the extra storage either way.

Block storage and node placement

Qdrant needs block-level storage with a POSIX-compatible file system and cannot run on NFS or object storage such as S3. SSD or NVMe drives are recommended. If your platform team can only offer shared network storage for the database tier, a dedicated engine may need its own hardware or volumes. Confirm the storage class in your environment before the design review.

Qdrant installation docs

Securing a default install

Self-deployed Qdrant instances listen on all network interfaces and have no authentication configured by default. Admin and read-only API keys, TLS for REST and gRPC, per-collection JWT permissions and JSON audit logs of authenticated operations are available, but each must be configured. Budget security review time for the dedicated service in the same way you would for the PostgreSQL tier.

Qdrant security docs

Team skills and licensing

Qdrant is open source under the Apache-2.0 license, so the engine can be self-hosted without a license fee. Running it still adds a service your team must patch, back up, monitor and upgrade alongside PostgreSQL. If your team already operates PostgreSQL well and has no one to own a second stateful service, keeping vectors in pgvector may be the lower-risk choice. Compare total operating effort on your own data.

Questions buyers ask before bringing in a partner

What does a pgvector implementation cost and what drives the price?

The cost depends on the written scope, not on the extension itself, which is free to install. The main cost is labor: the time to design the embedding storage, choose and test indexes, load representative data, and set up backups, monitoring and access controls. Infrastructure is the second cost, since vector indexes often need more memory and disk than ordinary tables. Costs recur through hosting, capacity growth and maintenance after each PostgreSQL minor or major release. When you request a quote, ask for one-time work and recurring support as separate lines, and ask which environments (test, staging, production) are covered. A fixed-scope agreement sets deliverables and timelines in writing before work starts.

How long does a pgvector implementation take to complete?

Duration is set by the number of decisions and the amount of data to test, not by installing the extension. The main drivers are the size of the vector dataset, how many index types and distance functions you need to compare, the number of applications that query the data, and how much access control and audit logging must be built in. Build time for an index also grows with table size, so a realistic load test on production-like data often takes longer than the setup itself. Ask any partner to show the phases, the review points and what each phase depends on, and confirm the start date and dependencies in the written scope.

What does the work need from our own team?

Expect to supply several people for defined periods. A data owner should confirm which tables, columns and documents become embeddings and who may query them. An application owner should describe the query patterns, filters and latency expectations. A database administrator needs to grant access to a test server, review the schema and index choices, and agree on backup and restore procedures. A security or compliance contact should review authentication, encryption and logging. An engineer on the embedding pipeline should explain how vectors are generated and refreshed. Ask the partner to list these roles and hours in the scope so your team can plan its time.

Can our own team run a pgvector implementation in house?

A team that already runs PostgreSQL in production can usually handle the extension itself, provided it has time for testing and someone who owns the vector workload after go-live. The harder parts are index choice under real data volumes, query tuning, memory planning, and recovery testing. Teams without these skills often find out late that an index performs poorly under their filters. A practical test is whether your team can produce a load test, a documented restore of the vector tables, and an upgrade plan without outside help. Where any of these is missing, a partner can build them into a fixed-scope engagement and hand over the runbooks.

How does pgvector compare with Qdrant for vector search?

pgvector keeps vectors in the same database as your relational data, so you can join vectors with ordinary tables, use existing backup and access tooling, and avoid running a second database. Qdrant is a dedicated vector search engine, licensed under Apache-2.0 and free to self-host, with its own API, filtering model, sharding and replication. Qdrant's distributed mode uses Raft consensus and recommends at least three nodes for production clusters. Choose pgvector when vector search is one feature inside an existing PostgreSQL application and scale is moderate. Consider Qdrant when vector search is the core workload, needs horizontal scaling or dedicated filtering at volume. Compare both against a load test on your own data.

Do vector indexes need rebuilding after a PostgreSQL upgrade?

It depends on the upgrade method and the pgvector version you run, so confirm it before the upgrade window is set. In-place upgrades with pg_upgrade keep existing data files, but the extension must be installed for the new PostgreSQL major version and its compatibility confirmed. Logical replication or dump and restore moves the data to a new cluster, and indexes are then built again on the target, which takes time for large tables. Check the pgvector release notes for any index format change, and test the upgrade on a copy of production data. Record index build times and query latency before and after, so you can judge whether the upgrade succeeded.

What must we confirm about our PostgreSQL major version first?

Confirm that your PostgreSQL major version is still supported and that your pgvector release supports that major version. PostgreSQL 14 is listed as supported until November 12, 2026, and 15, 16, 17 and 18 have later end dates, so a deployment on 14 may need an upgrade soon. Each major version is supported for five years after its initial release, and minor releases arrive at least every three months. Check the PostgreSQL versioning policy and the extension's compatibility notes, then decide whether to upgrade before or after adding vector search. Ask the partner to include that decision in the written scope.

What does a fixed-scope pgvector engagement include and exclude?

A fixed-scope engagement lists the deliverables, environments, dataset sizes, index options to test, integrations and handover items before work begins. Typical items include schema and index design, a load test with recorded results, backup and restore verification, access control and audit logging design, and runbooks for operators. Exclusions should be just as explicit, such as embedding model selection, application code changes, or production support after handover. DeployOpen plans, implements, hardens, backs up, documents and supports self-hosted open-source platforms in your own infrastructure, and most engagements are scoped this way. Ask for the written scope before comparing quotes.

Where to confirm pgvector and PostgreSQL details

Start with the PostgreSQL documentation for anything that touches the database itself. The PostgreSQL upgrading documentation covers pg_dumpall with restore, pg_upgrade and logical replication, which are the paths you will compare when a major version approaches end of life. The PostgreSQL authentication methods page lists the methods your pg_hba.conf can use, so you can confirm which ones your directory and certificate setup supports before you decide how application roles log in. For replication and failover, the high availability documentation and the failover documentation explain that PostgreSQL does not detect a failed primary by itself, so your HNSW index recovery plan depends on an external tool you still need to select and test.

Confirm pgvector version compatibility with your PostgreSQL major version in the pgvector project's own documentation before you install or upgrade anything. The extension is released separately from PostgreSQL, so a major upgrade of the database can require a matching extension build and an index rebuild plan. Record the exact pgvector version in your change records and check it again during any upgrade rehearsal, including the planner behavior of the vector indexes you created.

For comparison points against a dedicated engine, read the Qdrant documentation on installation requirements, the security documentation on API keys, TLS and audit logging, and the distributed deployment documentation on cluster sizing. Compare those published requirements with your own storage, authentication and recovery targets, and ask your team to write down which features each option must provide before you choose.

How DeployOpen scopes and delivers pgvector work

DeployOpen plans, builds, tests, documents and supports self-hosted open-source platforms inside your own cloud accounts, data centers or air-gapped networks. For pgvector on PostgreSQL, that means agreeing the index choice, data volumes and recall targets in writing before any build starts, then handing over a system your own team can run.

How we scope

  • Written scope names the PostgreSQL major version, pgvector build and the tables and embedding dimensions it will serve.
  • Scope records the HNSW or IVFFlat decision, distance function and the recall and latency tests used to justify it.
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work begins.

How we build

  • Installation and configuration run in your environment, including memory settings, index build parameters and connection handling.
  • Index builds are timed on a copy of your data so the maintenance window and memory needs are known before production.
  • Access controls, row-level filtering and audit logging for vector queries are configured alongside the application's own permissions.

How we hand over

  • Deliverables include architecture notes, index and parameter records, backup and restore runbooks, and the test results behind each decision.
  • Your team receives a restore test and a reindexing procedure so that rebuilding indexes after a major upgrade is a known task.
  • Handover covers how to recheck search quality when embedding models change, so reindexing decisions stay documented.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover.
  • Retainers can cover pgvector version checks against each PostgreSQL minor and major release you run.
  • Support can include periodic recall and latency retests as data volumes grow, with findings and fixes written up for your team.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.