Skip to main content

PGVector

To enable vector search in a generic PostgreSQL database, LangChain.js supports using the pgvector Postgres extension.

Setup

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

npm install pg

Setup a pgvector self hosted instance with docker-compose

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:

services:
db:
image: ankane/pgvector
ports:
- 5433:5432
volumes:
- ./data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=ChangeMe
- POSTGRES_USER=myuser
- POSTGRES_DB=api

API Reference:

    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.

    Usage

    One complete example of using PGVectorStore is the following:

    import { OpenAIEmbeddings } from "langchain/embeddings/openai";
    import { PGVectorStore } from "langchain/vectorstores/pgvector";
    import { PoolConfig } from "pg";

    // First, follow set-up instructions at
    // https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/pgvector

    const 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",
    },
    };

    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 } } ]
    */

    await pgvectorStore.end();

    API Reference: