轻松驾驭Google Vertex AI Vector Search:快速构建高效向量数据库

58 阅读2分钟

引言

在现代AI应用中,如何高效管理和检索大量的向量数据是一项重要挑战。Google Vertex AI Vector Search提供了业界领先的高效低延迟向量数据库服务,非常适用于需要快速相似度匹配的任务。本文将为您详细讲解如何使用Google Vertex AI Vector Search,帮助您快速入门并构建自己的向量数据库。

主要内容

创建并部署索引

在使用Vertex AI 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>"

# 创建存储桶
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI

使用VertexAIEmbeddings作为嵌入模型

from google.cloud import aiplatform
from langchain_google_vertexai import VertexAIEmbeddings

# 初始化AI平台
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)

# 嵌入模型初始化
embedding_model = VertexAIEmbeddings(model_name="textembedding-gecko@003")

创建一个空索引并部署

# 创建索引
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.deploy_index(
    index=my_index, deployed_index_id=DEPLOYED_INDEX_ID
)

创建向量存储

利用已有的索引和端点,创建一个简单的向量存储:

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)

常见问题和解决方案

问题1:创建索引耗时较长

  • 解决方案:这是由于索引构建需要一定计算过程。建议提前计划并合理安排时间。

问题2:网络访问受限

总结和进一步学习资源

通过本文,您应该能够掌握如何创建和使用Google Vertex AI Vector Search来管理和检索向量数据。想深入学习,可以参考Google的官方文档或者Lange Chain API文档.

参考资料

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