> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Google Cloud SQL for PostgreSQL 集成

> 使用 LangChain JavaScript 与 Google Cloud SQL for PostgreSQL 向量存储进行集成。

[Cloud SQL](https://cloud.google.com/sql) 是一个全托管的关系型数据库服务，提供高性能、无缝集成以及出色的可扩展性，并支持 PostgreSQL 等数据库引擎。

本指南简要介绍了如何使用 Cloud SQL for PostgreSQL 通过 `PostgresVectorStore` 类存储向量嵌入。

## 概述

### 集成详情

| 类                     | 包                                                                                                | [Python 支持](https://python.langchain.com/docs/integrations/vectorstores/google_cloud_sql_pg/) |   版本  |
| :-------------------- | :----------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------: | :---: |
| `PostgresVectorStore` | [`@langchain/google-cloud-sql-pg`](https://www.npmjs.com/package/@langchain/google-cloud-sql-pg) |                                               ✅                                               | 0.0.1 |

### 开始之前

为了使用此包，您需要先完成以下步骤：

1. [选择或创建一个 Cloud Platform 项目。](https://developers.google.com/workspace/guides/create-project)
2. [为您的项目启用计费。](https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project)
3. [启用 Cloud SQL Admin API。](https://console.cloud.google.com/flows/enableapi?apiid=sqladmin.googleapis.com)
4. [设置身份验证。](https://cloud.google.com/docs/authentication)
5. [创建 CloudSQL 实例](https://cloud.google.com/sql/docs/postgres/connect-instance-auth-proxy#create-instance)
6. [创建 CloudSQL 数据库](https://cloud.google.com/sql/docs/postgres/create-manage-databases)
7. [向数据库添加用户](https://cloud.google.com/sql/docs/postgres/create-manage-users)

### 身份验证

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

### 设置您的 Google Cloud 项目

设置您的 Google Cloud 项目 ID，以便在本地利用 Google Cloud 资源：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
gcloud config set project YOUR-PROJECT-ID
```

如果您不知道您的项目 ID，请尝试以下方法：

* 运行 `gcloud config list`。
* 运行 `gcloud projects list`。
* 查看支持页面：[查找项目 ID](https://support.google.com/googleapi/answer/7014113)。

## 设置 PostgresVectorStore 实例

要使用 PostgresVectorStore 库，您需要安装 `@langchain/google-cloud-sql-pg` 包，然后按照以下步骤操作。

首先，您需要登录到您的 Google Cloud 账户，并根据您的 Google Cloud 项目设置以下环境变量；这些变量将根据您希望如何配置（fromInstance、fromEngine、fromEngineArgs）您的 PostgresEngine 实例来定义：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
PROJECT_ID="your-project-id"
REGION="your-project-region" // 示例："us-central1"
INSTANCE_NAME="your-instance"
DB_NAME="your-database-name"
DB_USER="your-database-user"
PASSWORD="your-database-password"
```

### 设置实例

要实例化 PostgresVectorStore，您首先需要通过 PostgresEngine 创建数据库连接，然后初始化向量存储表，最后调用 `.initialize()` 方法来实例化向量存储。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import {
  Column,
  PostgresEngine,
  PostgresEngineArgs,
  PostgresVectorStore,
  PostgresVectorStoreArgs,
  VectorStoreTableArgs,
} from "@langchain/google-cloud-sql-pg";
import { SyntheticEmbeddings } from "@langchain/core/utils/testing"; // 用作嵌入服务
import * as dotenv from "dotenv";

dotenv.config();

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

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

const vectorStoreArgs: VectorStoreTableArgs = {
  metadataColumns: [new Column("page", "TEXT"), new Column("source", "TEXT")],
};

// 向量存储表初始化
await engine.initVectorstoreTable("my_vector_store_table", 768, vectorStoreArgs);
const embeddingService = new SyntheticEmbeddings({ vectorSize: 768 });

const pvectorArgs: PostgresVectorStoreArgs = {
  metadataColumns: ["page", "source"],
};

// PostgresVectorStore 实例化
const vectorStore = await PostgresVectorStore.initialize(
  engine,
  embeddingService,
  "my_vector_store_table",
  pvectorArgs
);

```

## 管理向量存储

### 向向量存储添加文档

您可以通过传递或不传递 ID 来向向量存储添加文档：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { v4 as uuidv4 } from "uuid";
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "细胞的动力源是线粒体",
  metadata: { page: 0, source: "https://example.com" },
};

const document2: Document = {
  pageContent: "建筑物由砖块构成",
  metadata: { page: 1, source: "https://example.com" },
};

const document3: Document = {
  pageContent: "线粒体由脂质构成",
  metadata: { page: 2, source: "https://example.com" },
};

const document4: Document = {
  pageContent: "2024 年奥运会在巴黎举行",
  metadata: { page: 3, source: "https://example.com" },
};

const documents = [document1, document2, document3, document4];

const ids = [uuidv4(), uuidv4(), uuidv4(), uuidv4()];

await vectorStore.addDocuments(documents, { ids: ids });

```

### 从向量存储删除文档

您可以通过传递要删除的 ID 数组来从向量存储中删除一个或多个文档：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// 删除一个文档
const id1 = ids[0];
await vectorStore.delete({ ids: [id1] });

// 删除多个文档
await vectorStore.delete({ ids: ids });

```

## 搜索文档

一旦您的向量存储创建完成并添加了相关文档，您很可能希望在运行链或代理时查询它。

### 直接查询

执行简单的相似性搜索可以按如下方式进行：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const filter = `"source" = "https://example.com"`;

const results = await vectorStore.similaritySearch("生物学", 2, filter);

for (const doc of results) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}

```

如果您想执行相似性搜索并获取相应的分数，可以运行：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const filter = `"source" = "https://example.com"`;
const resultsWithScores = await vectorStore.similaritySearchWithScore(
  "生物学",
  2,
  filter
);

for (const [doc, score] of resultsWithScores) {
  console.log(
    `* [相似度=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(doc.metadata)}]`
  );
}

```

### 使用最大边际相关性搜索进行查询

最大边际相关性优化了查询的相似性和所选文档之间的多样性。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const options = {
  k: 4,
  filter: `"source" = 'https://example.com'`,
};

const results = await vectorStoreInstance.maxMarginalRelevanceSearch("生物学", options);

for (const doc of results) {
  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}

```

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\javascript\integrations\vectorstores\google_cloudsql_pg.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
