Skip to main content
Qdrant(读作:quadrant)是一个向量相似性搜索引擎。它提供了一个生产就绪的服务,具有便捷的 API,用于存储、搜索和管理向量,并支持附加负载和扩展过滤功能。它使其适用于各种神经网络或基于语义的匹配、分面搜索和其他应用。
本文档演示了如何将 Qdrant 与 LangChain 结合使用,用于稠密(即基于嵌入的)、稀疏(即文本搜索)和混合检索。QdrantVectorStore 类通过 Qdrant 的新 Query API 支持多种检索模式。它要求您运行 Qdrant v1.10.0 或更高版本。

设置

运行 Qdrant 有多种模式,根据所选模式,会有一些细微差异。选项包括:
  • 本地模式,无需服务器
  • Docker 部署
  • Qdrant Cloud
请参阅 Qdrant 安装说明
pip install -qU langchain-qdrant

凭证

运行此笔记本中的代码无需任何凭证。 如果您希望获得最佳的模型调用自动跟踪,也可以通过取消注释下方来设置您的 LangSmith API 密钥:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

初始化

本地模式

Python 客户端提供了在本地模式下运行代码的选项,而无需运行 Qdrant 服务器。这对于测试、调试或仅存储少量向量非常有用。嵌入可以完全保留在内存中或持久化到磁盘。

内存中

对于某些测试场景和快速实验,您可能更喜欢将所有数据仅保留在内存中,这样当客户端被销毁时(通常在脚本/笔记本结束时)数据会被移除。
# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
from langchain_qdrant import QdrantVectorStore
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams

client = QdrantClient(":memory:")

client.create_collection(
    collection_name="demo_collection",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

vector_store = QdrantVectorStore(
    client=client,
    collection_name="demo_collection",
    embedding=embeddings,
)

磁盘存储

本地模式,不使用 Qdrant 服务器,也可以将向量存储在磁盘上,以便在运行之间持久保存。
client = QdrantClient(path="/tmp/langchain_qdrant")

client.create_collection(
    collection_name="demo_collection",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

vector_store = QdrantVectorStore(
    client=client,
    collection_name="demo_collection",
    embedding=embeddings,
)

本地服务器部署

无论您选择使用 Docker 容器 在本地启动 Qdrant,还是使用 官方 Helm 图表 选择 Kubernetes 部署,连接到此类实例的方式都是相同的。您需要提供一个指向服务的 URL。
url = "<---qdrant url here --->"
docs = []  # put docs here
qdrant = QdrantVectorStore.from_documents(
    docs,
    embeddings,
    url=url,
    prefer_grpc=True,
    collection_name="my_documents",
)

Qdrant Cloud

如果您不想忙于管理基础设施,可以选择在 Qdrant Cloud 上设置一个完全托管的 Qdrant 集群。包含一个永久免费的 1GB 集群供试用。使用托管版本的 Qdrant 的主要区别是,您需要提供一个 API 密钥来保护您的部署免受公开访问。该值也可以在 QDRANT_API_KEY 环境变量中设置。
url = "<---qdrant cloud cluster url here --->"
api_key = "<---api key here--->"
qdrant = QdrantVectorStore.from_documents(
    docs,
    embeddings,
    url=url,
    prefer_grpc=True,
    api_key=api_key,
    collection_name="my_documents",
)

使用现有集合

要获取 langchain_qdrant.Qdrant 的实例而不加载任何新文档或文本,可以使用 Qdrant.from_existing_collection() 方法。
qdrant = QdrantVectorStore.from_existing_collection(
    embedding=embeddings,
    collection_name="my_documents",
    url="http://localhost:6333",
)

管理向量存储

创建向量存储后,我们可以通过添加和删除不同项来与之交互。

向向量存储添加项

我们可以使用 add_documents 函数向向量存储添加项。
from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocolate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees Fahrenheit.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
vector_store.add_documents(documents=documents, ids=uuids)

从向量存储删除项

vector_store.delete(ids=[uuids[-1]])
True

查询向量存储

一旦您的向量存储创建完毕并添加了相关文档,您很可能希望在运行链或代理时对其进行查询。

直接查询

使用 Qdrant 向量存储的最简单场景是执行相似性搜索。在底层,我们的查询将被编码为向量嵌入,并用于在 Qdrant 集合中查找相似文档。
results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
* Building an exciting new project with LangChain - come check it out! [{'source': 'tweet', '_id': 'd3202666-6f2b-4186-ac43-e35389de8166', '_collection_name': 'demo_collection'}]
* LangGraph is the best framework for building stateful, agentic applications! [{'source': 'tweet', '_id': '91ed6c56-fe53-49e2-8199-c3bb3c33c3eb', '_collection_name': 'demo_collection'}]
QdrantVectorStore 支持 3 种相似性搜索模式。可以使用 retrieval_mode 参数进行配置。
  • 稠密向量搜索(默认)
  • 稀疏向量搜索
  • 混合搜索

稠密向量搜索

稠密向量搜索涉及通过基于向量的嵌入计算相似性。要仅使用稠密向量进行搜索:
  • retrieval_mode 参数应设置为 RetrievalMode.DENSE。这是默认行为。
  • 应向 embedding 参数提供一个稠密嵌入值。
from langchain_qdrant import QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with dense vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config=VectorParams(size=3072, distance=Distance.COSINE),
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    embedding=embeddings,
    retrieval_mode=RetrievalMode.DENSE,
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs

稀疏向量搜索

要仅使用稀疏向量进行搜索:
  • retrieval_mode 参数应设置为 RetrievalMode.SPARSE
  • 必须提供 SparseEmbeddings 接口的实现,使用任何稀疏嵌入提供程序,作为 sparse_embedding 参数的值。
langchain-qdrant 包提供了一个基于 FastEmbed 的开箱即用实现。 要使用它,请安装 FastEmbed 包。
pip install -qU fastembed
from langchain_qdrant import FastEmbedSparse, QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient, models
from qdrant_client.http.models import Distance, SparseVectorParams, VectorParams

sparse_embeddings = FastEmbedSparse(model_name="Qdrant/bm25")

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with sparse vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config={"dense": VectorParams(size=3072, distance=Distance.COSINE)},
    sparse_vectors_config={
        "sparse": SparseVectorParams(index=models.SparseIndexParams(on_disk=False))
    },
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    sparse_embedding=sparse_embeddings,
    retrieval_mode=RetrievalMode.SPARSE,
    sparse_vector_name="sparse",
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs

混合向量搜索

要使用稠密和稀疏向量执行混合搜索并进行分数融合:
  • retrieval_mode 参数应设置为 RetrievalMode.HYBRID
  • 应向 embedding 参数提供一个稠密嵌入值。
  • 必须提供 SparseEmbeddings 接口的实现,使用任何稀疏嵌入提供程序,作为 sparse_embedding 参数的值。
请注意,如果您使用 HYBRID 模式添加了文档,则可以在搜索时切换到任何检索模式,因为集合中同时提供了稠密和稀疏向量。
from langchain_qdrant import FastEmbedSparse, QdrantVectorStore, RetrievalMode
from qdrant_client import QdrantClient, models
from qdrant_client.http.models import Distance, SparseVectorParams, VectorParams

sparse_embeddings = FastEmbedSparse(model_name="Qdrant/bm25")

# Create a Qdrant client for local storage
client = QdrantClient(path="/tmp/langchain_qdrant")

# Create a collection with both dense and sparse vectors
client.create_collection(
    collection_name="my_documents",
    vectors_config={"dense": VectorParams(size=3072, distance=Distance.COSINE)},
    sparse_vectors_config={
        "sparse": SparseVectorParams(index=models.SparseIndexParams(on_disk=False))
    },
)

qdrant = QdrantVectorStore(
    client=client,
    collection_name="my_documents",
    embedding=embeddings,
    sparse_embedding=sparse_embeddings,
    retrieval_mode=RetrievalMode.HYBRID,
    vector_name="dense",
    sparse_vector_name="sparse",
)

qdrant.add_documents(documents=documents, ids=uuids)

query = "How much money did the robbers steal?"
found_docs = qdrant.similarity_search(query)
found_docs
如果您想执行相似性搜索并接收相应的分数,可以运行:
results = vector_store.similarity_search_with_score(
    query="Will it be hot tomorrow", k=1
)
for doc, score in results:
    print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
* [SIM=0.531834] The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees. [{'source': 'news', '_id': '9e6ba50c-794f-4b88-94e5-411f15052a02', '_collection_name': 'demo_collection'}]
有关 QdrantVectorStore 所有可用搜索函数的完整列表,请阅读 API 参考

元数据过滤

Qdrant 拥有一个广泛的过滤系统,支持丰富的类型。也可以在 LangChain 中使用过滤器,通过向 similarity_search_with_scoresimilarity_search 方法传递一个额外的参数。
from qdrant_client import models

results = vector_store.similarity_search(
    query="Who are the best soccer players in the world?",
    k=1,
    filter=models.Filter(
        should=[
            models.FieldCondition(
                key="page_content",
                match=models.MatchValue(
                    value="The top 10 soccer players in the world right now."
                ),
            ),
        ]
    ),
)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
* The top 10 soccer players in the world right now. [{'source': 'website', '_id': 'b0964ab5-5a14-47b4-a983-37fa5c5bd154', '_collection_name': 'demo_collection'}]

通过转换为检索器进行查询

您还可以将向量存储转换为检索器,以便在链中更轻松地使用。
retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("Stealing from the bank is a crime")
[Document(metadata={'source': 'news', '_id': '50d8d6ee-69bf-4173-a6a2-b254e9928965', '_collection_name': 'demo_collection'}, page_content='Robbers broke into the city bank and stole $1 million in cash.')]

用于检索增强生成的用法

有关如何将此向量存储用于检索增强生成 (RAG) 的指南,请参阅以下部分:

自定义 Qdrant

有选项可以在 LangChain 应用程序中使用现有的 Qdrant 集合。在这种情况下,您可能需要定义如何将 Qdrant 点映射到 LangChain Document

命名向量

Qdrant 支持通过命名向量为每个点多个向量。如果您使用外部创建的集合,或者希望使用不同名称的向量,可以通过提供其名称来配置它。
from langchain_qdrant import RetrievalMode

QdrantVectorStore.from_documents(
    docs,
    embedding=embeddings,
    sparse_embedding=sparse_embeddings,
    location=":memory:",
    collection_name="my_documents_2",
    retrieval_mode=RetrievalMode.HYBRID,
    vector_name="custom_vector",
    sparse_vector_name="custom_sparse_vector",
)

元数据

Qdrant 将您的向量嵌入与可选的 JSON 类似有效负载一起存储。有效负载是可选的,但由于 LangChain 假设嵌入是从文档生成的,因此我们保留上下文数据,以便您也可以提取原始文本。 默认情况下,您的文档将存储在以下有效负载结构中:
{
    "page_content": "Lorem ipsum dolor sit amet",
    "metadata": {
        "foo": "bar"
    }
}
但是,您可以决定为页面内容和元数据使用不同的键。如果您有一个想要重用的现有集合,这很有用。
QdrantVectorStore.from_documents(
    docs,
    embeddings,
    location=":memory:",
    collection_name="my_documents_2",
    content_payload_key="my_page_content_key",
    metadata_payload_key="my_meta",
)

API 参考

有关所有 QdrantVectorStore 功能和配置的详细文档,请前往 API 参考