> ## 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 AlloyDB for PostgreSQL 集成

> 使用 LangChain 与 Google AlloyDB for PostgreSQL 向量存储集成。

> [AlloyDB](https://cloud.google.com/alloydb) 是一个完全托管的关系型数据库服务，提供高性能、无缝集成和令人印象深刻的可扩展性。AlloyDB 与 PostgreSQL 100% 兼容。利用 AlloyDB 的 LangChain 集成扩展您的数据库应用，构建 AI 驱动的体验。

本笔记本介绍如何使用 `AlloyDB for PostgreSQL` 通过 `AlloyDBVectorStore` 类存储向量嵌入。

**AlloyDB AI 功能**：该集成原生支持 `alloydb_ai_nl` 和 `google_ml_integration` 扩展，提供数据库原生的 AI 能力：

* **零调参 ScaNN**：通过 `ScaNNIndex(mode="AUTO")` 实现自动调优、自我管理的向量索引。
* **列式引擎与向量辅助**：通过 `ColumnarEngine` 动态加速向量查询。
* **语义重排序**：使用 `AlloyDBDocumentCompressor`（基于 `google_ml.rank`）在数据库内原生重排序检索文档。
* **自然语言到 SQL**：使用 `AlloyDBToolkit` 构建原生 SQL 智能体。
* **数据库内 AI 工具**：直接在 SQL 中调用 LLM 函数（ `AlloyDBIfTool`、`AlloyDBSummaryTool`、`AlloyDBSentimentTool`）。
* **多模态嵌入**：在数据库内原生生成向量（例如使用 `aembed_image()`）。

更多关于该包的信息请参考 [GitHub](https://github.com/googleapis/langchain-google-alloydb-pg-python/)。

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-alloydb-pg-python/blob/main/docs/vector_store.ipynb)

## 开始前

运行本笔记本前需完成以下步骤：

* [创建 Google Cloud 项目](https://developers.google.com/workspace/guides/create-project)
* [启用 AlloyDB API](https://console.cloud.google.com/flows/enableapi?apiid=alloydb.googleapis.com)
* [创建 AlloyDB 集群和实例.](https://cloud.google.com/alloydb/docs/cluster-create)
* [创建 AlloyDB 数据库.](https://cloud.google.com/alloydb/docs/quickstart/create-and-connect)
* [为数据库添加用户.](https://cloud.google.com/alloydb/docs/database-users/about)

### 🦜🔗 库安装

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

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

**Colab 仅用**：取消注释下方单元格以重启内核或使用重启按钮。对于 Gemini 企业代理平台工作台，可通过顶部按钮重启终端。

```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 进行认证以访问您的项目。

* 若使用 Colab 运行本笔记本，请使用下方单元格继续。
* 若使用 Gemini 企业代理平台工作台，请查阅 [Gemini 企业代理平台工作台设置指南](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}
```

## 基础用法

### 设置 AlloyDB 数据库值

在 [AlloyDB 实例页面](https://console.cloud.google.com/alloydb/clusters) 中查找您的数据库值。

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

### AlloyDBEngine 连接池

作为向量存储的 AlloyDB 要求提供 `AlloyDBEngine` 对象。 `AlloyDBEngine` 配置连接池以实现应用程序与 AlloyDB 数据库的稳定连接，并遵循行业最佳实践。

使用 `AlloyDBEngine.from_instance()` 创建 `AlloyDBEngine` 需提供以下 5 个参数：

1. `project_id`：Google Cloud 项目 ID（AlloyDB 实例所在项目）
2. `region`：AlloyDB 实例所在区域
3. `cluster`：AlloyDB 集群名称
4. `instance`：AlloyDB 实例名称
5. `database`：要连接的数据库名称

默认使用 [IAM 数据库认证](https://cloud.google.com/alloydb/docs/connect-iam) 作为认证方式。本库会从环境变量中获取 [应用默认凭据 (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) 的 IAM 主体。

可选地，也可使用 [内置数据库认证](https://cloud.google.com/alloydb/docs/database-users/about)（需提供用户名/密码）。此时需传入 `user` 和 `password` 参数给 `AlloyDBEngine.from_instance()`：

* `user`：内置数据库认证及登录使用的数据库用户
* `password`：内置数据库认证及登录使用的数据库密码

**注意**：本教程演示异步接口。所有异步方法均有对应的同步方法。

```python theme={null}
from langchain_google_alloydb_pg import AlloyDBEngine

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

### 初始化表

`AlloyDBVectorStore` 类需要数据库表。 `AlloyDBEngine` 引擎的 `init_vectorstore_table()` 方法可帮助创建符合规范的数据表结构。

```python theme={null}
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)。
如需使用 `VertexAIEmbeddings`，需启用 Gemini 企业代理平台 API。建议为生产环境设置嵌入模型版本，了解更多信息请查阅 [文本嵌入模型](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
)
```

### 初始化默认 AlloyDBVectorStore

```python theme={null}
from langchain_google_alloydb_pg import AlloyDBVectorStore

store = await AlloyDBVectorStore.create(
    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_alloydb_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.adrop_vector_index()  # Delete index using default name
```

## 创建自定义向量存储

向量存储可利用关系数据对相似度搜索进行过滤。

创建包含自定义元数据列的表。

```python theme={null}
from langchain_google_alloydb_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 AlloyDBVectorStore
custom_store = await AlloyDBVectorStore.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\_alloydb.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/vectorstores/google_alloydb.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


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