> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/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 向量存储。

[云 SQL](https://cloud.google.com/sql)是一个完全托管的关联回归数据库服务，提供高性能、无缝集成、令人印象深刻的可扩展性，并提供PostgreSQL等数据库引擎。

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

## 概述

### 集成细节

| 类 | 包 | [PY支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/google_cloud_sql_pg.md) | 版本 |
| :- | :- | :-: | :-: |
| `PostgresVectorStore` | [`@langchain/google-cloud-sql-pg`](https://www.npmjs.com/package/@langchain/google-cloud-sql-pg) | ✅ | ![NPM - 版本](https://img.shields.io/npm/v/@langchain/google-cloud-sql-pg?style=flat-square\&label=%20&) |

### 开始前

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

1. [选择或创建云平台项目.](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. [启用云 SQL管理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云项目

将您的Google Cloud项目ID设置为在本地利用Google Cloud资源：

```bash theme={null}
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`包，然后按照以下步骤操作。

```bash npm theme={null}
npm install @langchain/google-cloud-sql-pg @langchain/core
```

```bash yarn theme={null}
yarn add @langchain/google-cloud-sql-pg @langchain/core
```

```bash pnpm theme={null}
pnpm add @langchain/google-cloud-sql-pg @langchain/core
```

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

```bash theme={null}
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"
```

### 设置实例

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

```typescript theme={null}
import {
  Column,
  PostgresEngine,
  PostgresEngineArgs,
  PostgresVectorStore,
  PostgresVectorStoreArgs,
  VectorStoreTableArgs,
} from "@langchain/google-cloud-sql-pg";
import { SyntheticEmbeddings } from "@langchain/core/utils/testing"; // This is used as an Embedding service
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
);

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

// Vector store table initialization
await engine.initVectorstoreTable("my_vector_store_table", 768, vectorStoreArgs);
const embeddingService = new SyntheticEmbeddings({ vectorSize: 768 });

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

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

```

## 管理向量存储

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

要将文档添加到向量存储，您可以通过传递或不传递ID来执行

```typescript theme={null}
import type { Document } from "@langchain/core/documents";

const document1: Document = {
  pageContent: "The powerhouse of the cell is the mitochondria",
  metadata: { page: 0, source: "https://example.com" },
};

const document2: Document = {
  pageContent: "Buildings are made out of brick",
  metadata: { page: 1, source: "https://example.com" },
};

const document3: Document = {
  pageContent: "Mitochondria are made out of lipids",
  metadata: { page: 2, source: "https://example.com" },
};

const document4: Document = {
  pageContent: "The 2024 Olympics are in Paris",
  metadata: { page: 3, source: "https://example.com" },
};

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

const ids = [crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID()];

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

```

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

您可以通过传递要删除的ID数组来删除一个或多个文档：

```typescript theme={null}
// deleting a document
const id1 = ids[0];
await vectorStore.delete({ ids: [id1] });

// deleting more than one document
await vectorStore.delete({ ids: ids });

```

## 搜索文档

一旦您的向量存储创建完成，并且相关文档已添加，您很可能希望在您的链或智能体运行期间查询它。

### 直接查询

执行简单的相似度搜索可以按以下方式完成：

```typescript theme={null}
const filter = `"source" = "https://example.com"`;

const results = await vectorStore.similaritySearch("biology", 2, filter);

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

```

如果您想执行相似度搜索并接收相应的分数，可以运行：

```typescript theme={null}
const filter = `"source" = "https://example.com"`;
const resultsWithScores = await vectorStore.similaritySearchWithScore(
  "biology",
  2,
  filter
);

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

```

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

最大边际相关性优化查询的相似度以及选定文档之间的多样性。

```typescript theme={null}
const options = {
  k: 4,
  filter: `"source" = 'https://example.com'`,
};

const results = await vectorStore.maxMarginalRelevanceSearch("biology", options);

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

```

***

> 官方原文：[src/oss/javascript/integrations/vectorstores/google\_cloudsql\_pg.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/vectorstores/google_cloudsql_pg.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.