Retrieval workflows in n8n with PostgreSQL and pgvector

Keeping n8n retrieval embeddings in your existing PostgreSQL estate with pgvector covers table design, local embedding models, index and filter trade-offs, and when a dedicated vector database is worth running.

On this page

Why n8n retrieval workflows can run on PostgreSQL and pgvector

If your team already runs PostgreSQL and wants retrieval for n8n AI workflows without adding another stateful system, pgvector stores embeddings in the same database as your relational data. That means the documents, their metadata, access attributes and the vectors that represent them can share one backup scope, one set of credentials, one patching cycle and one set of operational runbooks. The PGVector node in n8n writes embedding rows into a table and runs similarity queries against that table as part of a retrieval flow, so an agent or chain gets the context it needs without a separate vector service in the path. The node is the piece that connects your n8n canvas to that table, and the rest of the design sits in PostgreSQL.

The choice fits best when the vectors are tied closely to records you already keep in PostgreSQL, such as support tickets, policy documents, product catalogs or case notes, and when filters on those records matter to the answer. Joining vector results to ordinary tables, enforcing row-level rules and reusing existing PostgreSQL high availability and point-in-time recovery are straightforward reasons to keep the data together. Before committing, confirm the PostgreSQL version your platform team supports, the embedding dimension your chosen local model produces, and whether your expected corpus size and query rate are acceptable on the pgvector index types you plan to use. Those numbers come from your own environment and your model, so measure them on a representative sample rather than assume them.

How n8n, a local embedding model and PostgreSQL fit together

A document enters an n8n workflow on the main instance or a worker, which sends the text to a local embedding model endpoint. The returned vectors are written to a pgvector table in PostgreSQL, and at query time the same model embeds the question, a similarity search runs against the indexed column, and the top matches are passed to the LLM as context. Check that the embedding model and the query use the same dimensions, that the database and model hosts sit inside the trust boundary, and that only the retrieved passages leave it for the language model.

Documents and queries flow through n8n, a local embedding model and pgvector inside the trust boundary.

Which pgvector index and table options fit which workload

This table compares exact search, HNSW and IVFFlat indexes, the 2,000-dimension indexing limit, halfvec and sparsevec types, and metadata filter design. Read each row against your corpus size, embedding width and how often queries carry filters. The main takeaway is that the default exact search is often the right starting point, and approximate indexes need filter testing before you rely on them.

OptionWhen it fitsTrade-offWhat to confirm
Exact nearest neighbor search (no index)Small tables, evaluation runs, or filtered queries where accuracy matters more than latencyEvery query scans all candidate rows, so latency grows with table sizeMeasure query time on a realistic row count in your own environment
HNSW indexLarger tables with low-latency retrieval needs and vectors up to 2,000 dimensionsFaster approximate search, but index build and memory costs rise with data volume, and results are approximateRecall and latency on your queries, and the index build time on your hardware
IVFFlat indexLarge tables where you can rebuild the index as data changes and tune list counts for your dataApproximate results that depend on cluster quality, so recall can drop as data shifts without rebuildsRecall after bulk inserts and whether your rebuild schedule matches your ingest pattern
Vector columns above 2,000 dimensionsEmbedding models that produce wide vectors and need exact search or a non-indexed columnStandard vector indexing does not cover this width, so plan for exact search or a narrower embeddingThe dimension count of your chosen model and whether a smaller output size is available
halfvec typeWide embeddings where storage and index size matter and half-precision values keep acceptable qualityLower precision than the vector type, so verify retrieval quality against a test setWhether your model's outputs hold quality at half precision
sparsevec typeSparse representations where most dimensions are zero, such as keyword-style weightingSuited to sparse data only, and dense embeddings gain nothing from itThat your embedding method actually produces sparse output
Metadata filter designQueries scoped by tenant, document source, date or access groupApproximate indexes apply filters after the index scan, so selective filters can return fewer rows than requestedResult counts for your most selective filters with iterative index scans enabled
Iterative index scansFiltered approximate queries where filters remove many candidate rowsExtra scanning adds latency, and the strict or relaxed ordering choice affects resultsWhich ordering mode your pgvector version supports and its effect on latency

Choosing embeddings from local models versus hosted providers

The embedding model sets the vector dimension, the cost and speed of ingestion, and where your document text is sent. Each card below is a decision or check that connects the model choice to the pgvector table and the n8n workflows that read it.

Match dimensions to the column

A vector column is declared with a fixed dimension, and every row must match it. Confirm the output dimension of your chosen embedding model in your environment before you create the table, because a later model with a different size means a new column or a new table. Check the dimension your n8n embeddings node returns during a test run, not only the model card. pgvector can index columns up to 2,000 dimensions, so confirm your model stays inside that limit if you plan to use an HNSW or IVFFlat index.

pgvector README

Host local models with Ollama or vLLM

A local model run through Ollama or vLLM keeps document text on hosts you control, but the team then owns GPU or CPU capacity, model storage, patching and an API that n8n can reach on a private network. Ollama is typically simpler for small ingestion jobs, while vLLM is aimed at serving workloads with more demanding throughput needs. Confirm model support, hardware requirements and API compatibility with your chosen runtime before you commit to a model.

Plan throughput for bulk ingestion

Initial loads of a large document set often run far longer than daily updates, so the first ingestion is the real capacity test. Measure how many chunks per minute your embedding host produces, then size batch size, retry behavior and n8n execution timeouts around that number. A hosted provider usually scales through its own rate limits, while a local host is limited by the hardware you bought, so ask for those limits in writing before you schedule the load.

Re-embed when the model changes

Vectors from different models are not comparable, so changing the embedding model means re-embedding every stored chunk, including the ones you thought were stable. Keep the model name and version in a column or metadata field so you can tell which rows came from which model. Plan the re-embedding as a separate workflow that writes to a new table, then switch queries over once the new index is built and checked.

Confirm data residency end to end

A hosted embedding API receives the full text of every chunk it embeds, which can include personal, health or contractual data. Check the provider's data handling terms, retention and whether requests are used for training, and write that answer into your data classification. A local model keeps the text inside your network, but only if the n8n node, the model host and the logs all stay on that network, so trace each hop.

Assign ownership of model updates

Someone must decide when a model is upgraded, who tests retrieval quality afterward and who approves the re-embedding cost in time and compute. For hosted providers, the vendor may retire or change model versions on its own schedule, so track deprecation notices. For local models, the team chooses the version, so record the pinned tag in your configuration and treat upgrades as a change request with a retrieval test before release.

How to set up the PGVector node with a pgvector table

This sequence takes a PostgreSQL server from version check to a working retrieval path, so the PGVector node in n8n reads and writes a fixed-dimension table under a dedicated role. Each step ends with a check you can run before moving on.

  1. Confirm PostgreSQL version support

    The platform or database team confirms the PostgreSQL major version the cluster runs and checks it against the supported list in the PostgreSQL versioning policy. pgvector supports PostgreSQL 13 and later, but PostgreSQL 14 is supported only until November 12, 2026, so a new deployment should normally start on a version with a later end-of-support date (18, 17, 16 or 15 at the time of writing). Confirm the version with a query such as SELECT version(); on the target server. The step is done when the version is recorded in the change ticket and the team has agreed a plan for the next major upgrade.

  2. Install the pgvector extension

    A database administrator installs the pgvector extension package that matches the PostgreSQL major version, using the packaging method your platform already uses (operating system packages, a container image or a managed service option). Then connect to the target database as a privileged user and run CREATE EXTENSION vector; in that database. Check the installed release with SELECT extversion FROM pg_extension WHERE extname = 'vector'; and confirm it is a release you have reviewed in the pgvector CHANGELOG. The step is done when the query returns a version string and the extension appears in the database's extension list.

  3. Create the table with a fixed vector dimension

    Design the table with an id column, a text column for the chunk, a metadata column of type jsonb for source identifiers and access tags, and a vector column whose dimension equals the output size of the embedding model you have chosen. For example, a table might declare embedding vector(768) if your local model returns 768 values (illustrative). The dimension cannot be mixed within one column, so changing models later means a new column or table and re-embedding. Confirm the output size from the model's documentation before you run CREATE TABLE. The step is done when \d+ on the table shows the expected column types.

  4. Create the approximate index

    Create an index on the vector column that matches the distance operator your queries will use, such as cosine distance for most sentence embeddings. Choose between HNSW and IVFFlat with the pgvector README as your reference, and remember that pgvector indexes vector columns of up to 2,000 dimensions. Without an index, pgvector runs exact nearest neighbor search, which is accurate but slower on large tables. Create the index after loading enough rows to be representative if your index type benefits from it, and record the build time for later comparison. The step is done when EXPLAIN on a sample similarity query shows the planner choosing the index on a test table of realistic size.

  5. Create a dedicated n8n database role

    The database administrator creates a login role for n8n that owns nothing and holds only the privileges the workflow needs: SELECT, INSERT and, if updates or deletes are part of the flow, UPDATE and DELETE on the one retrieval table. Grant USAGE on its schema and avoid superuser or table-owner rights. Keep this role separate from the role n8n uses for its own execution database, so a leaked retrieval credential cannot read workflow data. Confirm the grants with \dp on the table and by logging in as the new role and attempting a query on an unrelated table, which should fail. The step is done when the role can read and write the retrieval table and is refused elsewhere.

  6. Configure the PGVector credential in n8n

    An n8n administrator creates a PGVector credential in n8n with the host, port, database, the dedicated role and its password, and SSL settings that match the server's certificate policy. Store the password only in the credential, never in a workflow expression or a shared note. Then add a PGVector node to a test workflow, select the credential, enter the table name and set the embedding model connection that produces the same dimension as the column. Confirm the node reports a successful connection when you run it on its own. The step is done when the credential test succeeds and the node lists the target table without errors.

  7. Insert a test document

    In the test workflow, pass a short known sentence through the embedding model and write it to the table with the PGVector node in insert mode, storing the source identifier in metadata. Using a document whose content you know makes the later retrieval result easy to judge. Check the row directly with a query such as SELECT id, metadata, vector_dims(embedding) FROM your_table; and confirm the dimension returned equals the value declared in the column definition. The step is done when the row exists, the metadata is correct and the vector dimension matches.

  8. Run a retrieval check

    Send a question that paraphrases the test sentence through the same embedding model and run the PGVector node in retrieve mode with a small result limit. The known document should appear at or near the top of the results. Repeat the check with an unrelated question and confirm the test document does not dominate the results, then run a query with a metadata filter to confirm filtering behaves as you expect. Filters applied after an approximate index scan can remove too many rows, so if results are sparse, review the iterative index scan options in the pgvector README. The step is done when the expected document is returned and the team has recorded the query, the result and the settings used.

When a dedicated vector database such as Qdrant is worth running

Keep vectors in PostgreSQL until a measured requirement pushes you out. The first test is vector scale and filtering: how many embeddings you expect, how large the dimensions are, and how often queries combine similarity search with tenant, permission or date filters. pgvector supports exact search by default and HNSW and IVFFlat indexes for approximate search, and it notes that filters are applied after the index scan, with iterative index scans available when filters remove too many candidates. If your collection is modest and your filters are simple, that path is usually enough. If you expect heavy filtering across large collections, benchmark your own data and query mix before deciding, because neither option is faster in general.

The second test is whether search and relational workloads must scale separately. Because pgvector lives inside PostgreSQL, embeddings share the same backups, replication, roles and upgrade windows as your other data, which is an operational advantage for many teams. A dedicated store such as Qdrant, an Apache-2.0 licensed vector search engine that published v1.19.2 on October 5, 2026, lets you size and restart the search tier without touching the database that runs your business records. Confirm the license terms for your own use with the project before you rely on them, and review the Qdrant project on GitHub for current release details.

The third test is team operating skills. A second data system adds its own backups, restore tests, access controls, monitoring and upgrade cycle, and someone on your team must own them. Ask whether your team already runs PostgreSQL well, including tested point-in-time recovery and planned major upgrades, and whether it can take on another stateful service. The sibling topic on n8n with Qdrant as a self-hosted vector store covers how the two connect in practice, and you should work through that setup before committing to a second store.

Securing the database that holds embeddings and source text

The PostgreSQL database behind a retrieval workflow holds both the vectors and the source text they were made from, plus n8n's own credentials. Securing it means controlling who and what connects, how credentials reach workers, where the database can be reached from, and what text is allowed into the embedding pipeline in the first place.

Dedicated n8n database role

Create a separate PostgreSQL role for n8n and grant it only the schemas and tables its retrieval workflows touch. Keep administrative roles out of n8n's connection settings so a compromised workflow cannot alter schema or read unrelated application tables. Review the grants whenever a new vector table or workflow is added, since default privileges can widen access over time.

Password hashing with SCRAM

PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM, so set password_encryption to scram-sha-256 and confirm that the n8n role's password was stored in that form. Check the pg_hba.conf rules so that the n8n role is matched only by the method you intend, not by a broader entry for all users.

PostgreSQL authentication methods

Certificate, LDAP and other options

PostgreSQL documents password, GSSAPI, SSPI, LDAP, RADIUS, certificate, PAM and OAuth methods. Certificate authentication suits a fixed service connection from n8n hosts, while LDAP or GSSAPI can centralize database access with your directory. Confirm that your n8n version and database driver support the method you choose before you commit to it.

Encryption key shared with workers

In queue mode, workers and webhook processors must have the same encryption key as the main instance so they can decrypt credentials stored in the database. Store that key in your secrets manager, not in a shared compose file, and plan how a rotation reaches every worker at the same time. Losing the key makes stored credentials unreadable.

n8n queue mode docs

Database network isolation

Place PostgreSQL on a private network segment that only the n8n main instance, workers and approved administration hosts can reach. Put a connection pooler such as PgBouncer between n8n and the database if connection counts grow, and keep the pooler inside the same segment. Block direct access from user workstations and from the internet, and confirm that backups and replicas follow the same rules.

Audit of embedded text

Decide before ingestion which fields, documents and personal data may be embedded and stored. Keep a record of each source document, its ingestion date and the embedding model used, so you can find and delete vectors when a source is removed. Remember that embeddings can still reflect the content they came from, so they carry the same classification as the source text.

Questions buyers ask before adding pgvector to n8n

What does a pgvector retrieval workflow in n8n cost to build?

No fixed figure can be stated here, because cost follows from the written scope. The main cost components are the time to design the table and ingestion pipeline, the work to connect n8n credentials and embedding models, retrieval testing against real questions, and the handover. Costs rise with the number of document sources, the volume and format of files (scanned PDFs need extra extraction work), the number of embedding models under evaluation, and the access rules that must be enforced at query time. Costs fall when the database and model hosts already exist and sample documents are clean. Ask any quote to itemize design, build, testing and handover separately, and to state which parts recur, such as re-embedding after a model change or pgvector upgrades.

How long does a first pgvector retrieval workflow take to stand up?

Duration depends on scope and access, and the largest variable is usually how quickly the database, model host and sample documents become available. A first workflow typically moves through four stages: confirm the PostgreSQL estate and extension availability, design the table and metadata, build ingestion and retrieval in n8n, then test answers against a known question set. Delays commonly come from change approvals for installing the extension, slow access to source documents, and disagreement about which metadata filters are required. Ask for a timeline that lists each stage, the dependency it waits on and the person who unblocks it.

What must our team provide before the engagement starts?

The team needs to provide three things at minimum. First, database access: a PostgreSQL instance where the pgvector extension can be installed under change control, with a role that can create the schema and tables. Second, model hosts: an embedding model endpoint, either a local model or an approved provider, with its hardware or API limits documented. Third, sample documents: a representative set covering each source, format, sensitivity class and access group, plus a set of questions with known answers. Also provide the name of the person who approves data use, because it determines which documents may be embedded at all.

Can an internal team build this without a partner?

Yes, if the team already runs PostgreSQL and has someone who has built n8n workflows against an API. The work is mostly ordinary database and workflow engineering, and the PGVector node documentation in n8n covers the basic setup. The skills gaps usually appear in three places: choosing index and distance settings with filters, designing access control so retrieval never returns a document a user cannot open, and producing evidence that retrieval quality holds. If none of these is covered internally, the cost of learning them on a live system is usually higher than the cost of a scoped review.

When is it worth bringing in a partner for this work?

A partner is worth considering when the retrieval workflow will hold regulated or sensitive data, when access rules must be enforced per document, or when a compliance reviewer will ask how the system was tested. Partners are also useful when the team must run the database, n8n and model hosts together on infrastructure it controls, and wants the design written down before the build starts. DeployOpen plans, implements, hardens, documents and supports self-hosted platforms in the client's own infrastructure, and most engagements are fixed-scope with scope, deliverables and timelines agreed in writing before work starts.

How do re-embedding and upgrades change the work over time?

Re-embedding is a recurring cost. Changing the embedding model usually means every stored vector must be regenerated, because vectors from different models are not comparable, so plan the table with a model identifier column and a way to build a new table beside the old one. Upgrades add a second recurring stream. pgvector 0.8.7 was released on October 1, 2026, and supports PostgreSQL 13 and later, but PostgreSQL 13 is unsupported, and PostgreSQL 14 support ends November 12, 2026. Minor PostgreSQL releases replace executables and restart, while major upgrades need pg_upgrade, a dump and restore, or logical replication. Ask any quote to state who re-embeds, who tests after each upgrade and how long a rollback path is kept.

When is a dedicated vector database worth it instead of pgvector?

Keep vectors in pgvector when the data already lives in PostgreSQL, when joins with relational records and access tables matter, and when the team already operates PostgreSQL backups, replication and pooling. Consider a dedicated store such as Qdrant, which is Apache-2.0 licensed and whose v1.19.2 was published on October 5, 2026, when vector volume, query load or filtering needs grow beyond what the team can tune in the existing estate. Verify both options on your own data, because pgvector filtering applies after the index is scanned and needs iterative index scans when filters remove too many results.

How DeployOpen scopes and delivers n8n retrieval on PostgreSQL

DeployOpen plans n8n retrieval workflows on the PostgreSQL estate you already run, so embeddings sit beside the data they describe. Each engagement starts with a written scope that names the sources, models, tables and access rules, and the build runs in infrastructure you control.

How we scope

  • Inventory the source documents, their owners, sensitivity and update frequency before choosing a table design.
  • Agree in writing which PGVector node operations, embedding models and workflows are in scope.
  • Confirm whether your PostgreSQL version, pgvector version and hosting platform support the planned index type.

How we build

  • Design the embedding table, metadata columns and HNSW or IVFFlat index against your real filter patterns.
  • Build the n8n ingestion and retrieval workflows with credentials stored under your encryption key management.
  • Test retrieval quality on your own sample questions, including filtered queries where results may drop.

How we hand over

  • Document the schema, index settings, workflow logic, credential ownership and the embedding model version in use.
  • Walk your database and automation teams through backups, restore tests and how to re-embed documents after a model change.
  • Record upgrade steps for pgvector and PostgreSQL so the next version change has a written plan.

How we support

  • Support is fixed-scope at the start, and ongoing support, upgrades and continuous testing are available as a retainer.
  • Retainers can cover pgvector and PostgreSQL patch reviews, n8n version upgrades and retrieval quality checks.
  • Ask any implementation partner for a quote tied to the written scope, including who maintains the database after handover.

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.