!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Providers](/v0.1/docs/integrations/platforms/)
    
    *   [Providers](/v0.1/docs/integrations/platforms/)
    *   [Anthropic](/v0.1/docs/integrations/platforms/anthropic/)
    *   [AWS](/v0.1/docs/integrations/platforms/aws/)
    *   [Google](/v0.1/docs/integrations/platforms/google/)
    *   [Microsoft](/v0.1/docs/integrations/platforms/microsoft/)
    *   [OpenAI](/v0.1/docs/integrations/platforms/openai/)
*   [Components](/v0.1/docs/integrations/components/)
    
    *   [LLMs](/v0.1/docs/integrations/llms/)
        
    *   [Chat models](/v0.1/docs/integrations/chat/)
        
    *   [Document loaders](/v0.1/docs/integrations/document_loaders/)
        
    *   [Document transformers](/v0.1/docs/integrations/document_transformers/)
        
    *   [Document compressors](/v0.1/docs/integrations/document_compressors/)
        
    *   [Text embedding models](/v0.1/docs/integrations/text_embedding/)
        
    *   [Vector stores](/v0.1/docs/integrations/vectorstores/)
        
        *   [Memory](/v0.1/docs/integrations/vectorstores/memory/)
        *   [AnalyticDB](/v0.1/docs/integrations/vectorstores/analyticdb/)
        *   [Astra DB](/v0.1/docs/integrations/vectorstores/astradb/)
        *   [Azure AI Search](/v0.1/docs/integrations/vectorstores/azure_aisearch/)
        *   [Azure Cosmos DB](/v0.1/docs/integrations/vectorstores/azure_cosmosdb/)
        *   [Cassandra](/v0.1/docs/integrations/vectorstores/cassandra/)
        *   [Chroma](/v0.1/docs/integrations/vectorstores/chroma/)
        *   [ClickHouse](/v0.1/docs/integrations/vectorstores/clickhouse/)
        *   [CloseVector](/v0.1/docs/integrations/vectorstores/closevector/)
        *   [Cloudflare Vectorize](/v0.1/docs/integrations/vectorstores/cloudflare_vectorize/)
        *   [Convex](/v0.1/docs/integrations/vectorstores/convex/)
        *   [Couchbase](/v0.1/docs/integrations/vectorstores/couchbase/)
        *   [Elasticsearch](/v0.1/docs/integrations/vectorstores/elasticsearch/)
        *   [Faiss](/v0.1/docs/integrations/vectorstores/faiss/)
        *   [Google Vertex AI Matching Engine](/v0.1/docs/integrations/vectorstores/googlevertexai/)
        *   [SAP HANA Cloud Vector Engine](/v0.1/docs/integrations/vectorstores/hanavector/)
        *   [HNSWLib](/v0.1/docs/integrations/vectorstores/hnswlib/)
        *   [LanceDB](/v0.1/docs/integrations/vectorstores/lancedb/)
        *   [Milvus](/v0.1/docs/integrations/vectorstores/milvus/)
        *   [Momento Vector Index (MVI)](/v0.1/docs/integrations/vectorstores/momento_vector_index/)
        *   [MongoDB Atlas](/v0.1/docs/integrations/vectorstores/mongodb_atlas/)
        *   [MyScale](/v0.1/docs/integrations/vectorstores/myscale/)
        *   [Neo4j Vector Index](/v0.1/docs/integrations/vectorstores/neo4jvector/)
        *   [Neon Postgres](/v0.1/docs/integrations/vectorstores/neon/)
        *   [OpenSearch](/v0.1/docs/integrations/vectorstores/opensearch/)
        *   [PGVector](/v0.1/docs/integrations/vectorstores/pgvector/)
        *   [Pinecone](/v0.1/docs/integrations/vectorstores/pinecone/)
        *   [Prisma](/v0.1/docs/integrations/vectorstores/prisma/)
        *   [Qdrant](/v0.1/docs/integrations/vectorstores/qdrant/)
        *   [Redis](/v0.1/docs/integrations/vectorstores/redis/)
        *   [Rockset](/v0.1/docs/integrations/vectorstores/rockset/)
        *   [SingleStore](/v0.1/docs/integrations/vectorstores/singlestore/)
        *   [Supabase](/v0.1/docs/integrations/vectorstores/supabase/)
        *   [Tigris](/v0.1/docs/integrations/vectorstores/tigris/)
        *   [Turbopuffer](/v0.1/docs/integrations/vectorstores/turbopuffer/)
        *   [TypeORM](/v0.1/docs/integrations/vectorstores/typeorm/)
        *   [Typesense](/v0.1/docs/integrations/vectorstores/typesense/)
        *   [Upstash Vector](/v0.1/docs/integrations/vectorstores/upstash/)
        *   [USearch](/v0.1/docs/integrations/vectorstores/usearch/)
        *   [Vectara](/v0.1/docs/integrations/vectorstores/vectara/)
        *   [Vercel Postgres](/v0.1/docs/integrations/vectorstores/vercel_postgres/)
        *   [Voy](/v0.1/docs/integrations/vectorstores/voy/)
        *   [Weaviate](/v0.1/docs/integrations/vectorstores/weaviate/)
        *   [Xata](/v0.1/docs/integrations/vectorstores/xata/)
        *   [Zep](/v0.1/docs/integrations/vectorstores/zep/)
    *   [Retrievers](/v0.1/docs/integrations/retrievers/)
        
    *   [Tools](/v0.1/docs/integrations/tools/)
        
    *   [Agents and toolkits](/v0.1/docs/integrations/toolkits/)
        
    *   [Chat Memory](/v0.1/docs/integrations/chat_memory/)
        
    *   [Stores](/v0.1/docs/integrations/stores/)
        

*   [](/v0.1/)
*   [Components](/v0.1/docs/integrations/components/)
*   [Vector stores](/v0.1/docs/integrations/vectorstores/)
*   PGVector

On this page

PGVector
========

To enable vector search in a generic PostgreSQL database, LangChain.js supports using the [`pgvector`](https://github.com/pgvector/pgvector) Postgres extension.

Setup[​](#setup "Direct link to Setup")
---------------------------------------

To work with PGVector, you need to install the `pg` package:

*   npm
*   Yarn
*   pnpm

    npm install pg

    yarn add pg

    pnpm add pg

### Setup a `pgvector` self hosted instance with `docker-compose`[​](#setup-a-pgvector-self-hosted-instance-with-docker-compose "Direct link to setup-a-pgvector-self-hosted-instance-with-docker-compose")

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/openai @langchain/community

    yarn add @langchain/openai @langchain/community

    pnpm add @langchain/openai @langchain/community

`pgvector` provides a prebuilt Docker image that can be used to quickly setup a self-hosted Postgres instance. Create a file below named `docker-compose.yml`:

    # Run this command to start the database:# docker-compose up --buildversion: "3"services:  db:    hostname: 127.0.0.1    image: ankane/pgvector    ports:      - 5432:5432    restart: always    environment:      - POSTGRES_DB=api      - POSTGRES_USER=myuser      - POSTGRES_PASSWORD=ChangeMe    volumes:      - ./init.sql:/docker-entrypoint-initdb.d/init.sql

And then in the same directory, run `docker compose up` to start the container.

You can find more information on how to setup `pgvector` in the [official repository](https://github.com/pgvector/pgvector).

Usage[​](#usage "Direct link to Usage")
---------------------------------------

Security

User-generated data such as usernames should not be used as input for table and column names.  
**This may lead to SQL Injection!**

One complete example of using `PGVectorStore` is the following:

    import { OpenAIEmbeddings } from "@langchain/openai";import {  DistanceStrategy,  PGVectorStore,} from "@langchain/community/vectorstores/pgvector";import { PoolConfig } from "pg";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/pgvectorconst config = {  postgresConnectionOptions: {    type: "postgres",    host: "127.0.0.1",    port: 5433,    user: "myuser",    password: "ChangeMe",    database: "api",  } as PoolConfig,  tableName: "testlangchain",  columns: {    idColumnName: "id",    vectorColumnName: "vector",    contentColumnName: "content",    metadataColumnName: "metadata",  },  // supported distance strategies: cosine (default), innerProduct, or euclidean  distanceStrategy: "cosine" as DistanceStrategy,};const pgvectorStore = await PGVectorStore.initialize(  new OpenAIEmbeddings(),  config);await pgvectorStore.addDocuments([  { pageContent: "what's this", metadata: { a: 2 } },  { pageContent: "Cat drinks milk", metadata: { a: 1 } },]);const results = await pgvectorStore.similaritySearch("water", 1);console.log(results);/*  [ Document { pageContent: 'Cat drinks milk', metadata: { a: 1 } } ]*/// Filtering is supportedconst results2 = await pgvectorStore.similaritySearch("water", 1, {  a: 2,});console.log(results2);/*  [ Document { pageContent: 'what's this', metadata: { a: 2 } } ]*/// Filtering on multiple values using "in" is supported tooconst results3 = await pgvectorStore.similaritySearch("water", 1, {  a: {    in: [2],  },});console.log(results3);/*  [ Document { pageContent: 'what's this', metadata: { a: 2 } } ]*/await pgvectorStore.delete({  filter: {    a: 1,  },});const results4 = await pgvectorStore.similaritySearch("water", 1);console.log(results4);/*  [ Document { pageContent: 'what's this', metadata: { a: 2 } } ]*/await pgvectorStore.end();

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [DistanceStrategy](https://api.js.langchain.com/types/langchain_community_vectorstores_pgvector.DistanceStrategy.html) from `@langchain/community/vectorstores/pgvector`
*   [PGVectorStore](https://api.js.langchain.com/classes/langchain_community_vectorstores_pgvector.PGVectorStore.html) from `@langchain/community/vectorstores/pgvector`

You can also specify a `collectionTableName` and a `collectionName` to partition vectors between multiple users or namespaces.

### Advanced: reusing connections[​](#advanced-reusing-connections "Direct link to 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.

    import { OpenAIEmbeddings } from "@langchain/openai";import { PGVectorStore } from "@langchain/community/vectorstores/pgvector";import pg from "pg";// First, follow set-up instructions at// https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/pgvectorconst reusablePool = new pg.Pool({  host: "127.0.0.1",  port: 5433,  user: "myuser",  password: "ChangeMe",  database: "api",});const originalConfig = {  pool: reusablePool,  tableName: "testlangchain",  collectionName: "sample",  collectionTableName: "collections",  columns: {    idColumnName: "id",    vectorColumnName: "vector",    contentColumnName: "content",    metadataColumnName: "metadata",  },};// Set up the DB.// Can skip this step if you've already initialized the DB.// await PGVectorStore.initialize(new OpenAIEmbeddings(), originalConfig);const pgvectorStore = new PGVectorStore(new OpenAIEmbeddings(), originalConfig);await pgvectorStore.addDocuments([  { pageContent: "what's this", metadata: { a: 2 } },  { pageContent: "Cat drinks milk", metadata: { a: 1 } },]);const results = await pgvectorStore.similaritySearch("water", 1);console.log(results);/*  [ Document { pageContent: 'Cat drinks milk', metadata: { a: 1 } } ]*/const pgvectorStore2 = new PGVectorStore(new OpenAIEmbeddings(), {  pool: reusablePool,  tableName: "testlangchain",  collectionTableName: "collections",  collectionName: "some_other_collection",  columns: {    idColumnName: "id",    vectorColumnName: "vector",    contentColumnName: "content",    metadataColumnName: "metadata",  },});const results2 = await pgvectorStore2.similaritySearch("water", 1);console.log(results2);/*  []*/await reusablePool.end();

#### API Reference:

*   [OpenAIEmbeddings](https://api.js.langchain.com/classes/langchain_openai.OpenAIEmbeddings.html) from `@langchain/openai`
*   [PGVectorStore](https://api.js.langchain.com/classes/langchain_community_vectorstores_pgvector.PGVectorStore.html) from `@langchain/community/vectorstores/pgvector`

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

OpenSearch

](/v0.1/docs/integrations/vectorstores/opensearch/)[

Next

Pinecone

](/v0.1/docs/integrations/vectorstores/pinecone/)

*   [Setup](#setup)
    *   [Setup a `pgvector` self hosted instance with `docker-compose`](#setup-a-pgvector-self-hosted-instance-with-docker-compose)
*   [Usage](#usage)
    *   [Advanced: reusing connections](#advanced-reusing-connections)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.