探索Google Vertex AI Vector Search:打造灵活高效的向量数据库

75 阅读2分钟
# 探索Google Vertex AI Vector Search:打造灵活高效的向量数据库

## 引言
在当今数据驱动的世界中,机器学习和人工智能应用需要快速可靠的方式来处理和搜索大量数据。Google Cloud Vertex AI Vector Search,作为业内领先的高规模低延迟向量数据库,提供了这种能力。本文将引导您了解如何使用Google Vertex AI Vector Search来创建、部署和查询向量数据库。

## 主要内容

### 创建索引并部署到终端
创建一个新的索引并将其部署到终端是使用Vertex AI Vector Search的第一步。

```python
# 设置项目和存储常量
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>"

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

from google.cloud import aiplatform
from langchain_google_vertexai import VertexAIEmbeddings

aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)

# 使用VertexAIEmbeddings作为嵌入模型
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",  # 可选值:BATCH_UPDATE, 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
)

从文本创建VectorStore

假设已经有一个索引和终端。

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,  # 使用API代理服务提高访问稳定性
)

vector_store.add_texts(texts=texts)

常见问题和解决方案

  1. 长时间的索引创建:索引的创建和部署可能需要大量时间(最多可达1小时)。建议在非高峰期进行操作,并制定合理的规划。

  2. 区域网络限制:在某些地区,访问Google API可能受到限制。开发者可以考虑使用API代理服务来提高访问稳定性。

总结和进一步学习资源

Google Vertex AI Vector Search 提供了强大的能力来支持大规模向量相似性匹配。通过有效使用其功能,开发者可以大大提升AI应用的性能和可靠性。

进一步学习资源

参考资料

  • Google Cloud 官方文档
  • Langchain API 文档

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

---END---