在现代机器学习应用中,特征管理和在线服务是两个至关重要的环节。Google Cloud Vertex AI 提供了一种强大的解决方案,即 Feature Store。它不仅可以让你通过 Google Cloud BigQuery 实现低延迟数据服务,还具备从嵌入向量中进行近邻检索的能力。这篇教程将详细介绍如何使用 VertexFSVectorStore 类,便捷地从 BigQuery 数据中执行低延迟的向量搜索和近似最近邻检索,从而轻松构建功能强大的机器学习应用。
技术背景介绍
Google Vertex AI Feature Store 旨在简化机器学习特征管理过程,并提供在线服务。通过与 BigQuery 集成,它支持低延迟的数据服务和近似邻居检索,非常适合于生产环境下用户面对的生成式 AI 应用。
核心原理解析
VertexFSVectorStore 类结合了统一的数据存储和灵活的向量搜索功能。它允许你在不需要复杂的基础设施设置下进行快速原型设计和批处理检索。通过手动或计划的数据同步,提供了低延迟的检索能力。
代码实现演示
安装库
首先,我们需要安装必要的库:
%pip install --upgrade --quiet langchain langchain-google-vertexai "langchain-google-community[featurestore]"
设置项目环境
确保你设置了项目 ID 和地区:
import IPython
# 重启 Jupyter 环境
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
# 设置项目 ID 和地区
PROJECT_ID = "" # @param {type:"string"}
! gcloud config set project {PROJECT_ID}
REGION = "us-central1" # @param {type: "string"}
初始化向量存储
使用 VertexFSVectorStore 初始化向量存储:
from langchain_google_vertexai import VertexAIEmbeddings
from langchain_google_community import VertexFSVectorStore
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
store = VertexFSVectorStore(
project_id=PROJECT_ID,
dataset_name="my_langchain_dataset",
table_name="doc_and_vectors",
location=REGION,
embedding=embedding,
)
添加文本和执行搜索
向向量存储中添加文本,并执行查询:
# 添加文本
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
store.add_texts(all_texts, metadatas=metadatas)
# 同步数据
store.sync_data()
# 搜索文档
query = "I'd like a fruit."
docs = store.similarity_search(query)
print(docs)
# 按向量搜索
query_vector = embedding.embed_query(query)
docs = store.similarity_search_by_vector(query_vector, k=2)
print(docs)
# 按元数据过滤搜索
docs = store.similarity_search_by_vector(query_vector, filter={"len": 6})
print(docs)
应用场景分析
此技术非常适用于需要实时数据检索和分析的场景,例如个性化推荐、语义搜索以及任何需要快速响应的生成式 AI 应用。
实践建议
- 在执行生产环境部署时,建议设置定时同步以确保数据的一致性。
- 使用 VertexFSVectorStore 时,注意优化数据同步和检索策略以提高性能。
如果遇到问题欢迎在评论区交流。
—END—
908

被折叠的 条评论
为什么被折叠?



