Skip to main content
Compatibility: Only available on Node.js.
To enable vector search in generic PostgreSQL databases, LangChain.js supports using the pgvector Postgres extension. This guide covers PGVector vector stores using the standalone @langchain/pgvector package. For usage and configuration examples, see the package README.
The examples on this page import PGVectorStore from @langchain/pgvector. If your project still uses @langchain/community, import it from @langchain/community/vectorstores/pgvector instead and use the community package API reference.
The @langchain/community package is no longer maintained. Examples that import from @langchain/community may be outdated or broken. Use with caution.

Overview

Integration details

Setup

To use PGVector vector stores, set up a Postgres instance with the pgvector extension enabled, then install @langchain/pgvector, the pg driver, and @langchain/core. This guide uses OpenAI embeddings as an example. You can use other supported embeddings models instead.

Setting up an instance

There are many ways to connect to Postgres depending on how you’ve set up your instance. Here’s one example of a local setup using a prebuilt Docker image provided by the pgvector team. Create a file with the below content named docker-compose.yml:
And then in the same directory, run docker compose up to start the container. You can also use a managed Postgres service that supports the vector extension. For example, Prisma Postgres supports pgvector. Run npx create-db@latest to create a temporary database and print its connection string. Store the connection string in a DATABASE_URL environment variable, then set postgresConnectionOptions to { connectionString: process.env.DATABASE_URL } in the config under Instantiation. PGVectorStore.initialize() runs CREATE EXTENSION IF NOT EXISTS vector before it creates the table, so you do not need to enable the extension first. You can find more information on how to setup pgvector in the official repository.

Credentials

To connect to your Postgres instance, you’ll need corresponding credentials. For a full list of supported options, see the node-postgres docs. If you are using OpenAI embeddings for this guide, you’ll need to set your OpenAI key as well:
If you want to get automated tracing of your model calls you can also set your LangSmith API key by uncommenting below:

Instantiation

To instantiate the vector store, call the .initialize() static method. This will automatically check for the presence of a table, given by tableName in the passed config. If it is not there, it will create it with the required columns.
Security: User-generated data such as usernames should not be used as input for table and column names. This may lead to SQL Injection!

Manage vector store

Add items to vector store

Delete items from vector store

Query vector store

Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent.

Query directly

Performing a simple similarity search can be done as follows:
The above filter syntax supports exact match, but the following are also supported:

Using the in operator

Using the notIn operator

Using the arrayContains operator

If you want to execute a similarity search and receive the corresponding scores you can run:

Query by turning into retriever

You can also transform the vector store into a retriever for easier usage in your chains.

Usage for retrieval-augmented generation

For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:

Advanced: reusing connections

You can reuse connections by creating a pool, then creating new PGVectorStore instances directly via the constructor. Note that you should call .initialize() to set up your database at least once to set up your tables properly before using the constructor.

Create HNSW index

By default, the extension performs a sequential scan search, with 100% recall. You might consider creating an HNSW index for approximate nearest neighbor (ANN) search to speed up similaritySearchVectorWithScore execution time. To create the HNSW index on your vector column, use the createHnswIndex() method. The method parameters include:
  • dimensions: Defines the number of dimensions in your vector data type, up to 2000. For example, use 1536 for OpenAI’s text-embedding-ada-002 and Amazon’s amazon.titan-embed-text-v1 models.
  • m?: The max number of connections per layer (16 by default). Index build time improves with smaller values, while higher values can speed up search queries.
  • efConstruction?: The size of the dynamic candidate list for constructing the graph (64 by default). A higher value can potentially improve the index quality at the cost of index build time.
  • distanceFunction?: The distance function name you want to use, is automatically selected based on the distanceStrategy.
For more info, see the Pgvector GitHub repo and the HNSW paper from Malkov Yu A. and Yashunin D. A.. 2020. Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs

Closing connections

Make sure you close the connection when you are finished to avoid excessive resource consumption:

Further reading

For PGVectorStore usage and configuration examples, see the package README.