> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Qdrant 集成

> 使用 LangChain Python 与 Qdrant 向量存储进行集成。

> [Qdrant](https://qdrant.tech/documentation/)（读作：quadrant）是一个向量相似度搜索引擎。它提供了一个生产就绪的服务，具有便捷的 API 用于存储、搜索和管理带有额外负载和扩展过滤支持的向量。这使得它适用于各种神经网络或基于语义的匹配、分面搜索和其他应用。

本文档演示了如何在 LangChain 中使用 Qdrant 进行密集（即基于嵌入）、稀疏（即文本搜索）和混合检索。`QdrantVectorStore` 类通过 Qdrant 的新 [Query API](https://qdrant.tech/blog/qdrant-1.10.x/) 支持多种检索模式。它要求您运行 Qdrant v1.10.0 或更高版本。

## 设置

运行 Qdrant 有多种模式，根据选择的不同，会有一些细微差别。选项包括：

* 本地模式，无需服务器
* Docker 部署
* Qdrant Cloud

请参阅 [Qdrant 安装说明](https://qdrant.tech/documentation/install/)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-qdrant
```

### 凭据

运行此笔记本中的代码不需要凭据。

如果您希望获得最佳级别的模型调用自动跟踪，您也可以设置您的 [LangSmith](/langsmith/home) API 密钥，取消下面注释：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 初始化

### 本地模式

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

#### 内存中

对于某些测试场景和快速实验，您可能更喜欢将所有数据仅保留在内存中，这样当客户端被销毁时（通常在脚本/笔记本结束时）数据会被移除。

<EmbeddingTabs />

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 服务器，也可以将向量存储在磁盘上，以便在运行之间持久存在。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 容器](https://qdrant.tech/documentation/install/) 在本地启动 Qdrant，还是选择使用 [官方 Helm chart](https://github.com/qdrant/qdrant-helm) 进行 Kubernetes 部署，连接此类实例的方式都是相同的。您需要提供一个指向服务的 URL。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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](https://cloud.qdrant.io/) 上设置完全托管的 Qdrant 集群。包含一个永久免费的 1GB 集群供您试用。使用托管版 Qdrant 的主要区别在于，您需要提供 API 密钥以防止您的部署被公开访问。该值也可以设置在 `QDRANT_API_KEY` 环境变量中。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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()` 方法。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
qdrant = QdrantVectorStore.from_existing_collection(
    embedding=embeddings,
    collection_name="my_documents",
    url="http://localhost:6333",
)
```

## 管理向量存储

一旦创建了向量存储，我们可以通过添加和删除不同项目来与其交互。

### 向向量存储添加项目

我们可以使用 `add_documents` 函数向向量存储添加项目。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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))]
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
vector_store.add_documents(documents=documents, ids=uuids)
```

### 从向量存储删除项目

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
vector_store.delete(ids=[uuids[-1]])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
True
```

## 查询向量存储

一旦创建向量存储并添加了相关文档，您很可能希望在运行链或代理期间查询它。

### 直接查询

使用 Qdrant 向量存储的最简单场景是执行相似度搜索。在底层，我们的查询将被编码为向量嵌入，并用于在 Qdrant 集合中找到相似的文档。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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}]")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* 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` 参数提供 [密集嵌入](https://python.langchain.com/docs/integrations/embeddings/) 值。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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`](https://github.com/langchain-ai/langchain/blob/master/libs/partners/qdrant/langchain_qdrant/sparse_embeddings.py) 接口作为 `sparse_embedding` 参数的值。

`langchain-qdrant` 包开箱即用提供了基于 [FastEmbed](https://github.com/qdrant/fastembed) 的实现。

要使用它，请安装 FastEmbed 包。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU fastembed
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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` 参数提供 [密集嵌入](https://python.langchain.com/docs/integrations/embeddings/) 值。
* 必须提供使用任何稀疏嵌入提供商实现的 [`SparseEmbeddings`](https://github.com/langchain-ai/langchain/blob/master/libs/partners/qdrant/langchain_qdrant/sparse_embeddings.py) 接口作为 `sparse_embedding` 参数的值。

请注意，如果您已使用 `HYBRID` 模式添加了文档，则在搜索时可以切换到任何检索模式，因为集合中同时有密集和稀疏向量。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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
```

如果您想执行相似度搜索并接收相应的分数，可以运行：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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}]")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* [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 参考](https://reference.langchain.com/python/langchain-qdrant/qdrant/QdrantVectorStore)

### 元数据过滤

Qdrant 拥有 [广泛的过滤系统](https://qdrant.tech/documentation/concepts/filtering/)，支持丰富的类型。也可以通过向 `similarity_search_with_score` 和 `similarity_search` 方法传递额外参数来在 LangChain 中使用过滤器。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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}]")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
* The top 10 soccer players in the world right now. [{'source': 'website', '_id': 'b0964ab5-5a14-47b4-a983-37fa5c5bd154', '_collection_name': 'demo_collection'}]
```

### 转换为检索器进行查询

您还可以将向量存储转换为检索器，以便在链中更轻松地使用。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("Stealing from the bank is a crime")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[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) 用法

关于如何使用此向量存储进行检索增强生成 (RAG) 的指南，请参阅以下部分：

* [教程](/oss/python/langchain/rag)
* [操作指南：使用 RAG 问答](https://python.langchain.com/docs/how_to/#qa-with-rag)
* [检索概念文档](https://python.langchain.com/docs/concepts/retrieval)

## 自定义 Qdrant

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

### 命名向量

Qdrant 支持按命名向量 [每个点多个向量](https://qdrant.tech/documentation/concepts/collections/#collection-with-multiple-vectors)。如果您处理外部创建的集合或想要使用不同名称的向量，可以通过提供其名称来配置它。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 假设嵌入是由文档生成的，我们保留上下文数据，这样您就可以提取原始文本。

默认情况下，您的文档将按以下负载结构存储：

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
    "page_content": "Lorem ipsum dolor sit amet",
    "metadata": {
        "foo": "bar"
    }
}
```

但是，您可以决定对页面内容和元数据使用不同的键。如果您已经有想要重用的集合，这很有用。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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 参考](https://reference.langchain.com/python/langchain-qdrant/qdrant/QdrantVectorStore)

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\vectorstores\qdrant.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
