Skip to content

Vector Databases and When pgvector is Enough

Published Updated

A vector database stores and indexes embeddings so it can find the closest matches to a query. If your data already lives in PostgreSQL, start with pgvector and measure how well it handles your real searches. A dedicated store earns its place when you need to scale search separately or when pgvector misses your targets for speed or retrieval quality.

What a Vector Database Does

A vector database finds records by comparing a query’s embedding with the embeddings it has indexed. An embedding is a list of numbers that a model produces from text, an image or another input. In a text search, the model aims to place phrases with similar meanings near each other in that numerical space.

Suppose a policy says “Staff can work from home” and an employee searches for “Employees may work remotely”. A text embedding model can put these sentences close together even though they use different words. The application embeds the question with the same model it used for the policy, then the database returns the nearest stored vectors and their records.

A keyword index looks for matching terms or variants it knows about. It has no measure of how close two embeddings are. Keywords are useful when someone enters a product code or an exact error message, which is why semantic search can work alongside keyword search.

How Similarity Search Works

Similarity search scores each candidate by how close it is to the query vector. Use the measure recommended by your embedding model and build the index for the same measure.

Cosine similarity compares the angle between vectors. Vectors pointing in the same direction score highest, regardless of their lengths. The dot product also takes length into account, so a longer vector can score higher even if it points less directly towards the query.

Euclidean distance measures the straight-line distance between the ends of two vectors. A smaller distance means a closer match.

Cosine distance is one minus cosine similarity. The cosine similarity calculator shows how changing the direction of a vector changes the score.

An exact search compares every eligible vector. An approximate nearest neighbour index skips much of that work and can miss some of the true nearest matches. Recall measures how many of those matches the search actually returns.

  • Hierarchical navigable small world (HNSW) connects nearby vectors in a graph. The search follows links towards closer matches. In pgvector, HNSW typically uses more memory and takes longer to build than IVFFlat, with better recall at the same query speed.
  • An inverted file (IVF) groups vectors into clusters and searches a subset of clusters near the query. pgvector’s implementation is called IVFFlat. Train it on representative data and search more clusters to improve recall, at the cost of query time.

Metadata filters can change where the trade-off lands. A search restricted to one department may discard most candidates if the database applies the filter after scanning the vector index. In pgvector, an approximate scan can then return fewer rows than requested. On pgvector 0.8.0 or later, iterative scans can search farther within configured limits. For a narrow filter, such as a department with a small document collection, test whether an exact search over the eligible rows is fast enough.

pgvector: Vector Search Inside PostgreSQL

pgvector adds a vector data type, similarity operators and approximate indexes to PostgreSQL. Azure Database for PostgreSQL Flexible Server, Amazon RDS for PostgreSQL, Amazon Aurora PostgreSQL and Google Cloud SQL for PostgreSQL all document support for the extension. The available extension version depends on the service and PostgreSQL version.

Keeping embeddings with business data lets you use SQL joins and existing PostgreSQL backup processes. A search can join policy extracts to their current document records, for example. You can also enforce row-level security with PostgreSQL policies when the application connects as a role bound by those policies. Test with the application’s role because table owners normally bypass row-level security.

This SQL example uses a fresh database where you have permission to install the extension. It creates a three-dimensional vector column for made-up data and builds an HNSW index for cosine distance.

CREATE EXTENSION IF NOT EXISTS vector;

-- Store two sample vectors with their source text.
CREATE TABLE "policyChunks" (
  id integer PRIMARY KEY,
  passage text NOT NULL,
  embedding vector(3) NOT NULL
);

INSERT INTO "policyChunks" (id, passage, embedding) VALUES
  (1, 'Staff can work from home', '[1,0.1,0]'),
  (2, 'Book the meeting room', '[0,1,0]');

-- Index for cosine distance, then request the nearest row.
CREATE INDEX "policyChunksEmbeddingIdx"
  ON "policyChunks" USING hnsw (embedding vector_cosine_ops);

SELECT id, passage
FROM "policyChunks"
ORDER BY embedding <=> '[1,0,0]'::vector
LIMIT 1;

The query returns row 1. PostgreSQL may choose a table scan on a table this small. For real data, set the column’s dimension to the size of the model’s output. The standard single-precision vector column can store up to 16,000 dimensions, while pgvector’s HNSW and IVFFlat indexes support up to 2,000 dimensions for that type. Half-precision indexing raises the limit to 4,000 with a loss of numerical precision.

There is no fixed number of vectors at which to switch databases. Benchmark a dedicated store if search competes with transactions for memory or filtered queries miss your recall target at peak load. Independent scaling can also make sense if search traffic grows much faster than database writes. Compare both systems under the same workload before adding a second store.

Dedicated Vector Databases and Search Services

Dedicated vector databases make sense when vector retrieval is a workload you need to scale separately. A search engine with vector support is a better fit when exact terms and meaning-based matches need to appear in the same results.

Option When it fits What to account for
Dedicated vector database, such as Pinecone, Weaviate, Qdrant or Milvus Vector queries need their own capacity or the index needs capabilities your current database lacks. Keep document changes, deletions and access rules in sync with the system that owns the records.
Search engine, such as Elasticsearch, OpenSearch or Azure AI Search Search needs to combine vector matches with keywords, exact identifiers or facets. Plan how to copy updates into the search index and how to rank the combined results.
Cloud-managed service Your team wants the provider to run the database or search infrastructure. This can be managed PostgreSQL, a search service or a dedicated vector database. Compare the plans against the features you need, how they bill and where data is processed. You still own retrieval quality and application permissions.

An Australian region can reduce network travel time if your application runs there. It can also help you meet a requirement to keep certain data in Australia. Region support depends on the service and deployment type. For example, Zilliz Cloud, the managed service based on Milvus, lists Sydney on Amazon Web Services for its on-demand plans.

Check where backups and replicas live and where the application sends queries to make embeddings. Those locations can differ from where the vector index runs. Data sovereignty explains how to assess those paths.

Choosing a Vector Database for Production

Start with the database your team already operates if it supports vector search and can enforce your access rules. You can measure the workload before you take on a second backup process, a second set of permissions and a pipeline to keep two stores in sync.

  • Estimate how many chunks you will index, their vector dimensions and how much the collection will grow. Count chunks rather than source files.
  • Measure how often records change or disappear. Track the longest acceptable delay before a change appears in search.
  • List the filters a query must apply. Test narrow filters and different access levels, including whether a deleted document or a record a user cannot access ever appears.
  • Map the regions that store, back up and process embeddings. Include the embedding model and any separate search service.
  • Identify who can tune the index and restore the database. Compare the cost of extra database memory with provider charges for storage, requests and data transfer.

For organisations and agencies covered by the Privacy Act 1988, storing a numerical embedding can still involve personal information. The Office of the Australian Information Commissioner explains that information can be personal if it is about someone who can reasonably be identified in context. An embedding derived from a staff record, for example, can still be linked to that person through a record ID or other data you hold. Apply your access, retention and deletion controls to embeddings that remain personal information as well as to the source records. OAIC guidance on de-identification.

Back up the store and test restoring it with the records and permissions it depends on. Monitor how long searches take under normal and peak load. When you change to an embedding model that produces vectors in a different space, re-embed the source content into a separate index. Send queries to that index with the matching model once it passes the same retrieval checks.

Before committing to a store, collect real questions and have people familiar with the records mark which documents answer each one. Include paraphrases, exact identifiers and questions asked by users with different permissions. Run the same questions against each candidate using the same embedding model and filters.

Measure how many known relevant documents appear in the first few results, how often queries exceed your latency target and whether any results violate permissions. Compare the indexed search with an exact search on the same eligible vectors. If both miss the same relevant passage, look at chunking or the embedding model. If only the indexed search misses it, tune the index and filters. Move stores if the existing database still falls short under realistic query and update load.

What Data Sovereignty Means for AI in Australia

Data sovereignty means your data is subject to laws where it’s stored or processed and laws that apply to the provider. In Australia, that also shapes sovereign cloud and sovereign AI choices.