> ## 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 Python 集成 Google Cloud SQL for PostgreSQL 向量存储。

> [Cloud SQL](https://cloud.google.com/sql) 是一种完全托管的关联回归数据库服务，提供高性能、无缝集成和令人印象深刻的可扩展性。它提供 PostgreSQL、PostgreSQL 和 SQL Server 数据库引擎。将您的数据库应用程序扩展到 AI 驱动的体验中，利用 Cloud SQL 的 LangChain 集成。

本笔记本介绍了如何使用 `Cloud SQL for PostgreSQL` 和 `PostgresVectorStore` 类存储向量嵌入。

在 [GitHub](https://github.com/googleapis/langchain-google-cloud-sql-pg-python/) 上了解更多关于该软件包的信息。

[![在 Colab 中打开](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-cloud-sql-pg-python/blob/main/docs/vector_store.ipynb)

## 开始前

要运行此笔记本，您需要执行以下操作：

* [创建 Google Cloud 项目](https://developers.google.com/workspace/guides/create-project)
* [启用 Cloud SQL 管理员 API.](https://console.cloud.google.com/flows/enableapi?apiid=sqladmin.googleapis.com)
* [创建 Cloud SQL 实例.](https://cloud.google.com/sql/docs/postgres/connect-instance-auth-proxy#create-instance)
* [创建 Cloud SQL 数据库.](https://cloud.google.com/sql/docs/postgres/create-manage-databases)
* [向数据库添加用户.](https://cloud.google.com/sql/docs/postgres/create-manage-users)

### 🦜🔗 库安装

安装集成库 `langchain-google-cloud-sql-pg` 和嵌入服务的库 `langchain-google-vertexai`。

```python theme={null}
pip install -qU  langchain-google-cloud-sql-pg langchain-google-vertexai
```

**Colab 仅限:** 取消注释以下单元格以重新启动内核，或使用按钮重新启动内核。对于 Gemini Enterprise Agent Platform Workbench，您可以使用顶部的按钮重新启动终端。

```python theme={null}
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython

# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
```

### 🔐 身份验证

以此笔记本登录的 IAM 用户身份验证 Google Cloud，以便访问您的 Google Cloud 项目。

* 如果您使用 Colab 运行此笔记本，请使用以下单元格并继续。
* 如果您使用 Gemini Enterprise Agent Platform Workbench，请查看 [Gemini Enterprise Agent Platform Workbench 设置说明](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)。

```python theme={null}
from google.colab import auth

auth.authenticate_user()
```

### ☁ 设置您的 Google 云项目

设置您的 Google Cloud 项目，以便在此笔记本中利用 Google Cloud 资源。

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

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

```python theme={null}
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.

PROJECT_ID = "my-project-id"  # @param {type:"string"}

# Set the project id
!gcloud config set project {PROJECT_ID}
```

## 基本用法

### 设置 Cloud SQL 数据库值

在 [Cloud SQL 实例页面](https://console.cloud.google.com/sql?_ga=2.223735448.2062268965.1707700487-2088871159.1707257687) 找到您的数据库值。

```python theme={null}
# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1"  # @param {type: "string"}
INSTANCE = "my-pg-instance"  # @param {type: "string"}
DATABASE = "my-database"  # @param {type: "string"}
TABLE_NAME = "vector_store"  # @param {type: "string"}
```

### PostgresEngine 连接池

将 Cloud SQL 作为向量存储之一的要求和参数是 `PostgresEngine` 对象。`PostgresEngine` 配置了到 Cloud SQL 数据库的连接池，使您的应用程序能够成功连接并遵循行业最佳实践。

要使用 `PostgresEngine.from_instance()` 创建 `PostgresEngine`，您只需要提供 4 件事：

1. `project_id` : Google Cloud 项目中 Cloud SQL 实例所在的项目 ID。
2. `region` : Cloud SQL 实例所在的区域。
3. `instance` : Cloud SQL 实例的名称。
4. `database` : 要连接到的 Cloud SQL 实例上的数据库的名称。

默认情况下，将使用 [IAM 数据库身份验证](https://cloud.google.com/sql/docs/postgres/iam-authentication#iam-db-auth) 作为数据库身份验证方法。此库使用来自环境的 [应用程序默认凭据 (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) 所属的 IAM 主机。

有关 IAM 数据库身份验证的更多信息，请参阅：

* [为 IAM 数据库身份验证配置实例](https://cloud.google.com/sql/docs/postgres/create-edit-iam-instances)
* [使用 IAM 数据库身份验证管理用户](https://cloud.google.com/sql/docs/postgres/add-manage-iam-users)

可选地，也可以使用用户名和密码访问 Cloud SQL 数据库的 [内置数据库身份验证](https://cloud.google.com/sql/docs/postgres/built-in-authentication)。只需向 `PostgresEngine.from_instance()` 提供可选的 `user` 和 `password` 参数：

* `user` : 用于内置数据库身份验证和登录的数据库用户。
* `password` : 用于内置数据库身份验证和登录的数据库密码。

"**注意**：本教程演示了异步接口。所有异步方法都有相应的同步方法。"

```python theme={null}
from langchain_google_cloud_sql_pg import PostgresEngine

engine = await PostgresEngine.afrom_instance(
    project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)
```

### 初始化表

`PostgresVectorStore` 类需要一个数据库表。`PostgresEngine` 引擎有一个辅助方法 `init_vectorstore_table()`，可用于创建具有正确架构的表。

```python theme={null}
from langchain_google_cloud_sql_pg import PostgresEngine

await engine.ainit_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=768,  # Vector size for Gemini Enterprise Agent Platform model (textembedding-gecko@latest)
)
```

### 创建嵌入类实例

您可以使用任何 [LangChain 嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。
您可能需要启用 Gemini Enterprise Agent Platform API 以使用 `VertexAIEmbeddings`。我们建议为生产设置嵌入模型的版本，了解更多关于 [文本嵌入模型](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/text-embeddings-api) 的信息。

```python theme={null}
# enable Gemini Enterprise Agent Platform API
!gcloud services enable aiplatform.googleapis.com
```

```python theme={null}
from langchain_google_vertexai import VertexAIEmbeddings

embedding = VertexAIEmbeddings(
    model_name="textembedding-gecko@latest", project=PROJECT_ID
)
```

### 初始化默认 PostgresVectorStore

```python theme={null}
from langchain_google_cloud_sql_pg import PostgresVectorStore

store = await PostgresVectorStore.create(  # Use .create() to initialize an async vector store
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
)
```

### 添加文本

```python theme={null}
import uuid

all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]

await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)
```

### 删除文本

```python theme={null}
await store.adelete([ids[1]])
```

### 搜索文档

```python theme={null}
query = "I'd like a fruit."
docs = await store.asimilarity_search(query)
print(docs)
```

### 通过向量搜索文档

```python theme={null}
query_vector = embedding.embed_query(query)
docs = await store.asimilarity_search_by_vector(query_vector, k=2)
print(docs)
```

## 添加索引

通过应用向量索引来加快向量搜索查询。了解更多关于 [向量索引](https://cloud.google.com/blog/products/databases/faster-similarity-search-performance-with-pgvector-indexes) 的信息。

```python theme={null}
from langchain_google_cloud_sql_pg.indexes import IVFFlatIndex

index = IVFFlatIndex()
await store.aapply_vector_index(index)
```

### 重新索引

```python theme={null}
await store.areindex()  # Re-index using default index name
```

### 删除索引

```python theme={null}
await store.aadrop_vector_index()  # Delete index using default name
```

## 创建自定义向量存储

向量存储可以利用关系数据来过滤相似性搜索。

创建具有自定义元数据列的表。

```python theme={null}
from langchain_google_cloud_sql_pg import Column

# Set table name
TABLE_NAME = "vectorstore_custom"

await engine.ainit_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=768,  # Gemini Enterprise Agent Platform model: textembedding-gecko@latest
    metadata_columns=[Column("len", "INTEGER")],
)


# Initialize PostgresVectorStore
custom_store = await PostgresVectorStore.create(
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
    metadata_columns=["len"],
    # Connect to an existing VectorStore by customizing the table schema:
    # id_column="uuid",
    # content_column="documents",
    # embedding_column="vectors",
)
```

### 使用元数据过滤器搜索文档

```python theme={null}
import uuid

# Add texts to the Vector Store
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]
await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)

# Use filter on search
docs = await custom_store.asimilarity_search_by_vector(query_vector, filter="len >= 6")

print(docs)
```

***

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


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