Skip to main content

TypeORM

为了在通用 PostgreSQL 数据库中启用向量搜索,LangChain.js 支持将 TypeORMpgvector Postgres 扩展一起使用。

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

设置

¥Setup

要使用 TypeORM,你需要安装 typeormpg 包:

¥To work with TypeORM, you need to install the typeorm and pg packages:

npm install typeorm
npm install pg
npm install @langchain/openai @langchain/community @langchain/core

使用 docker-compose 设置 pgvector 自托管实例

¥Setup a pgvector self hosted instance with docker-compose

pgvector 提供了一个预构建的 Docker 镜像,可用于快速设置自托管的 Postgres 实例。在下面创建一个名为 docker-compose.yml 的文件:

¥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:

export default {services:{db:{image:'ankane/pgvector',ports:['5432:5432'],volumes:['./data:/var/lib/postgresql/data'],environment:['POSTGRES_PASSWORD=ChangeMe','POSTGRES_USER=myuser','POSTGRES_DB=api']}}};

API Reference:

    然后在同一目录中,运行 docker compose up 来启动容器。

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

    你可以在 官方代码库 中找到有关如何在 pgvector 中设置 pgvector 的更多信息。

    ¥You can find more information on how to setup pgvector in the official repository.

    用法

    ¥Usage

    以下是使用 TypeORMVectorStore 的一个完整示例:

    ¥One complete example of using TypeORMVectorStore is the following:

    import { DataSourceOptions } from "typeorm";
    import { OpenAIEmbeddings } from "@langchain/openai";
    import { TypeORMVectorStore } from "@langchain/community/vectorstores/typeorm";

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

    export const run = async () => {
    const args = {
    postgresConnectionOptions: {
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "myuser",
    password: "ChangeMe",
    database: "api",
    } as DataSourceOptions,
    };

    const typeormVectorStore = await TypeORMVectorStore.fromDataSource(
    new OpenAIEmbeddings(),
    args
    );

    await typeormVectorStore.ensureTableInDatabase();

    await typeormVectorStore.addDocuments([
    { pageContent: "what's this", metadata: { a: 2 } },
    { pageContent: "Cat drinks milk", metadata: { a: 1 } },
    ]);

    const results = await typeormVectorStore.similaritySearch("hello", 2);

    console.log(results);
    };

    API Reference:

    ¥Related