在本文中,我们将介绍如何使用Weaviate Vector Store进行混合搜索。混合搜索结合了传统的文本搜索与向量搜索,具有更高的搜索精度。本文将从创建Weaviate客户端、下载数据、加载文档、建立VectorStoreIndex及执行查询等方面进行全面讲解。
创建Weaviate客户端
首先,我们需要创建一个Weaviate客户端。这里我们可以选择连接到云实例或本地实例。
import weaviate
resource_owner_config = weaviate.AuthClientPassword(
username="<username>",
password="<password>",
)
# 连接到云实例
# client = weaviate.Client("https://<cluster-id>.semi.network/", auth_client_secret=resource_owner_config)
# 连接到本地实例
client = weaviate.Client("http://localhost:8080")
下载数据
我们将下载Paul Graham的文章数据。
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
加载文档
接下来,我们将文档加载到内存中。
from llama_index.core import SimpleDirectoryReader
# 加载文档
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
使用WeaviateVectorStore建立VectorStoreIndex
from llama_index.core import StorageContext
from llama_index.vector_stores.weaviate import WeaviateVectorStore
vector_store = WeaviateVectorStore(weaviate_client=client)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
# 可选:您也可以手动定义index_name
# index_name = "test_prefix"
# vector_store = WeaviateVectorStore(weaviate_client=client, index_name=index_name)
使用默认的向量搜索进行查询
我们可以使用默认的向量搜索来对索引进行查询。
query_engine = index.as_query_engine(similarity_top_k=2)
response = query_engine.query("What did the author do growing up?")
from llama_index.core.response.notebook_utils import display_response
display_response(response)
使用混合搜索进行查询
混合搜索结合了bm25和向量搜索,alpha参数决定了权重比例(alpha=0时偏向bm25,alpha=1时偏向向量搜索)。
# 使用混合搜索
query_engine = index.as_query_engine(
vector_store_query_mode="hybrid", similarity_top_k=2
)
response = query_engine.query(
"What did the author do growing up?",
)
display_response(response)
设置alpha=0以偏向bm25
query_engine = index.as_query_engine(
vector_store_query_mode="hybrid", similarity_top_k=2, alpha=0.0
)
response = query_engine.query(
"What did the author do growing up?",
)
display_response(response)
可能遇到的错误
- 连接错误:如果连接Weaviate实例失败,请检查您的URL是否正确以及网络是否通畅。
- 认证错误:请确保您的用户名和密码正确,且有相应的访问权限。
- 数据下载错误:确保您的网络连接正常且下载地址有效。
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!
参考资料: