在现代数据驱动的应用中,结合AI进行智能化的数据存储和检索变得越来越重要。今天,我们将探索如何使用Google AlloyDB for PostgreSQL,与Langchain集成,通过AlloyDBVectorStore类将向量嵌入存储到数据库中。
技术背景介绍
AlloyDB是Google提供的一种完全托管的关系型数据库服务,它与PostgreSQL完全兼容。它不仅性能卓越,且可无缝集成,具备惊人的可扩展性。通过AlloyDB的Langchain集成,我们可以将AI功能扩展到数据库应用中。
核心原理解析
AlloyDBVectorStore类是一个帮助开发者在AlloyDB数据库中存储和检索向量嵌入的工具。它利用向量的数学特性来实现高效的相似度搜索,这对于构建推荐系统等AI应用至关重要。
代码实现演示
下面是一个完整的代码示例,它展示了如何设置AlloyDB并存储向量嵌入。
# 安装必要的库
%pip install --upgrade --quiet langchain-google-alloydb-pg langchain-google-vertexai
# 认证Google Cloud账户以访问项目资源
from google.colab import auth
auth.authenticate_user()
# 设置Google Cloud项目ID
PROJECT_ID = "my-project-id" # 请替换为你的项目ID
# 配置项目资源
!gcloud config set project {PROJECT_ID}
# 设置AlloyDB数据库相关配置
REGION = "us-central1"
CLUSTER = "my-cluster"
INSTANCE = "my-primary"
DATABASE = "my-database"
TABLE_NAME = "vector_store"
# 创建AlloyDB连接池
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, # 向量大小来自VertexAI模型
)
# 配置嵌入服务
from langchain_google_vertexai import VertexAIEmbeddings
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
# 初始化AlloyDB向量存储
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)
# 根据向量进行搜索
query_vector = embedding.embed_query(query)
docs = await store.asimilarity_search_by_vector(query_vector, k=2)
print(docs)
# 创建和应用索引以加速搜索
from langchain_google_alloydb_pg.indexes import IVFFlatIndex
index = IVFFlatIndex()
await store.aapply_vector_index(index)
# 重建索引
await store.areindex()
# 删除索引
await store.adrop_vector_index()
应用场景分析
这种向量存储适用于需要快速相似性搜索的应用场景,如智能推荐、语义搜索等。利用AlloyDB的强大性能以及Langchain的灵活性,开发者能够轻松构建高效的AI应用。
实践建议
- 确保Google Cloud账户的配置正确,以顺利访问AlloyDB资源。
- 在生产环境中使用特定版本的嵌入模型以确保稳定性。
- 认真设计数据库架构,以便能够充分利用向量索引的优势。
如果遇到问题欢迎在评论区交流。
—END—