跳到主要内容
Cloud SQL 是一种完全托管的关系型数据库服务,提供高性能、无缝集成和出色的可扩展性,并提供 PostgreSQL 等数据库引擎。 本指南概述了如何使用 Cloud SQL for PostgreSQL 通过 PostgresLoader 类加载文档。

概览

开始之前

要使用此包,您首先需要完成以下步骤
  1. 选择或创建一个 Cloud Platform 项目。
  2. 为您的项目启用结算功能。
  3. 启用 Cloud SQL Admin API。
  4. 设置身份验证。
  5. 创建 CloudSQL 实例
  6. 创建 CloudSQL 数据库
  7. 向数据库添加用户

身份验证

使用 gcloud auth login 命令在本地对您的 Google Cloud 账户进行身份验证。

设置您的 Google Cloud 项目

设置您的 Google Cloud 项目 ID 以在本地利用 Google Cloud 资源
gcloud config set project YOUR-PROJECT-ID
如果您不知道您的项目 ID,请尝试以下操作
  • 运行 gcloud config list
  • 运行 gcloud projects list
  • 查看支持页面:查找项目 ID

设置 PostgresLoader 实例

要使用 PostgresLoader 类,您需要安装 @langchain/google-cloud-sql-pg 包,然后按照以下步骤操作。 首先,您需要登录您的 Google Cloud 账户并根据您的 Google Cloud 项目设置以下环境变量;这些变量将根据您如何配置(fromInstance、fromEngine、fromEngineArgs)您的 PostgresEngine 实例来定义:
PROJECT_ID="your-project-id"
REGION="your-project-region" // example: "us-central1"
INSTANCE_NAME="your-instance"
DB_NAME="your-database-name"
DB_USER="your-database-user"
PASSWORD="your-database-password"

设置实例

要实例化 PostgresLoader,您首先需要通过 PostgresEngine 创建数据库连接。
import {
  PostgresLoader,
  PostgresEngine,
  PostgresEngineArgs,
} from "@langchain/google-cloud-sql-pg";
import * as dotenv from "dotenv";

dotenv.config();

const peArgs: PostgresEngineArgs = {
  user: process.env.DB_USER ?? "",
  password: process.env.PASSWORD ?? "",
};

// PostgresEngine instantiation
const engine: PostgresEngine = await PostgresEngine.fromInstance(
  process.env.PROJECT_ID ?? "",
  process.env.REGION ?? "",
  process.env.INSTANCE_NAME ?? "",
  process.env.DB_NAME ?? "",
  peArgs
);

使用 table_name 参数加载文档

加载器从表中返回文档列表,其中第一列作为页面内容,所有其他列作为元数据。默认表将第一列作为页面内容,第二列作为元数据(JSON)。每行都成为一个文档。
const documentLoaderArgs: PostgresLoaderOptions = {
  tableName: "test_table_custom",
  contentColumns: ["fruit_name", "variety"],
  metadataColumns: [
    "fruit_id",
    "quantity_in_stock",
    "price_per_unit",
    "organic",
  ],
  format: "text",
};

const documentLoaderInstance = await PostgresLoader.initialize(
  PEInstance,
  documentLoaderArgs
);

使用 SQL 查询加载文档

查询参数允许用户指定自定义 SQL 查询,其中可以包含过滤器以从数据库加载特定文档。
const documentLoaderArgs: PostgresLoaderOptions = {
  query: "SELECT * FROM my_fruit_table",
  contentColumns: ["fruit_name", "variety"],
  metadataColumns: [
    "fruit_id",
    "quantity_in_stock",
    "price_per_unit",
    "organic",
  ],
  format: "text",
};

const documentLoaderInstance = await PostgresLoader.initialize(
  PEInstance,
  docucumetLoaderArgs
);

设置页面内容格式

加载器返回文档列表,每行一个文档,页面内容采用指定字符串格式,即文本(空格分隔的连接)、JSON、YAML、CSV 等。JSON 和 YAML 格式包含标题,而文本和 CSV 不包含字段标题。
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.