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

安装配置

运行 Qdrant 有多种模式,不同模式下会有一些细微差别。选项包括:
  • 本地模式,无需服务器
  • Docker 部署
  • Qdrant Cloud
安装说明请参见此处
pip install -qU langchain-qdrant

凭据

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

初始化

本地模式

Python 客户端提供了在本地模式下运行代码的选项,无需运行 Qdrant 服务器。这非常适合测试和调试,或只存储少量向量。嵌入可以完全保存在内存中,也可以持久化到磁盘上。

内存模式

对于某些测试场景和快速实验,您可能希望将所有数据仅保存在内存中,这样当客户端销毁时数据就会被删除——通常在脚本/notebook 结束时。
# | 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 chart 进行 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

查询向量存储

创建向量存储并添加相关文档后,您很可能希望在链或 agent 运行期间对其进行查询。

直接查询

使用 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 参考:python.langchain.com/api_reference/qdrant/qdrant/langchain_qdrant.qdrant.QdrantVectorStore.html