混合搜索
LangChain 中的标准搜索是通过向量相似度完成的。然而,许多向量存储实现(Astra DB、ElasticSearch、Neo4J、AzureSearch 等)也支持更高级的搜索,将向量相似度搜索与其他搜索技术(全文、BM25 等)结合起来。这通常被称为 "混合(Hybrid)" 搜索。
第 1 步:确保你使用的向量存储支持混合搜索
目前,LangChain 中没有统一的方式来执行混合搜索。每个向量存储可能有各自的实现方式。这通常以关键字参数的形式暴露,在 similarity_search 期间传入。通过阅读文档或源代码,弄清楚你使用的向量存储是否支持混合搜索,如果支持,如何使用它。
第 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",
)使用标准的 索引分析器 (opens in a new tab) 创建 Cassandra 向量存储。需要索引分析器来启用词项匹配。
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",
]
)如果我们执行标准的相似度搜索,会得到所有文档:
vectorstore.as_retriever().invoke("What city did I visit last?")[Document(page_content='In 2022, I visited New York'),
Document(page_content='In 2023, I visited Paris'),
Document(page_content='In 2021, I visited New Orleans')]Astra DB 向量存储的 body_search 参数可用于按词项 new 过滤搜索。
vectorstore.as_retriever(search_kwargs={"body_search": "new"}).invoke(
"What city did I visit last?"
)[Document(page_content='In 2022, I visited New York'),
Document(page_content='In 2021, I visited New Orleans')]我们现在可以创建用于进行问答的链
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()这里我们将检索器标记为具有一个可配置字段。所有向量存储检索器都有 search_kwargs 字段。它只是一个字典,包含向量存储特定的字段
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?")Paris我们现在可以带可配置选项调用链。search_kwargs 是可配置字段的 id。该值是用于 Astra DB 的搜索关键字参数。
chain.invoke(
"What city did I visit last?",
config={"configurable": {"search_kwargs": {"body_search": "new"}}},
)New York