> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/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 的新 [查询 API](https://qdrant.tech/blog/qdrant-1.10.x/) 支持多种检索模式。它要求您运行 Qdrant v1.10.0 或更高版本。

## 设置

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

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

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

```python theme={null}
pip install -qU langchain-qdrant
```

### 凭证

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

如果您想获得最先进的模型调用自动跟踪，您也可以通过取消注释下方设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```python theme={null}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 初始化

### 本地模式

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

#### 内存中

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

```python theme={null}
# | output: false
# | echo: false
from langchain_openai import OpenAIEmbeddings

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

```python theme={null}
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={null}
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 图表](https://github.com/qdrant/qdrant-helm)选择 Kubernetes 部署，连接到此类实例的方式将完全相同。您需要提供一个指向服务的 URL。

```python theme={null}
url = "<---qdrant url here --->"
docs = []  # put docs here
qdrant = QdrantVectorStore.from_documents(
    docs,
    embeddings,
    url=url,
    prefer_grpc=True,
    collection_name="my_documents",
)
```

### Qdrant 云

如果您不想让自己忙于管理基础设施，可以选择在 [Qdrant Cloud](https://cloud.qdrant.io/) 上设置一个完全托管的 Qdrant 集群。包含一个免费的 1GB 集群供试用。使用托管的 Qdrant 版本的主要区别在于，您需要提供一个 API 密钥来保护您的部署不被公开访问。该值也可以设置在一个 `QDRANT_API_KEY` 环境变量中。

```python theme={null}
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={null}
qdrant = QdrantVectorStore.from_existing_collection(
    embedding=embeddings,
    collection_name="my_documents",
    url="http://localhost:6333",
)
```

## 管理向量存储

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

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

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

```python theme={null}
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={null}
vector_store.add_documents(documents=documents, ids=uuids)
```

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

```python theme={null}
vector_store.delete(ids=[uuids[-1]])
```

```text theme={null}
True
```

## 查询向量存储

一旦您的向量存储创建完成，并且相关文档已添加，您很可能希望在您的链或智能体运行期间查询它。

### 直接查询

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

```python theme={null}
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={null}
* 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` 支持三种相似度搜索模式。它们可以通过 `retrieval_mode` 参数进行配置。

* 密集向量搜索（默认）
* 稀疏向量搜索
* 混合搜索

### 密集向量搜索

密集向量搜索涉及通过基于向量的嵌入计算相似度。仅使用密集向量进行搜索：

* 应将 `retrieval_mode` 参数设置为 `RetrievalMode.DENSE`。这是默认行为。
* 应向 `embedding` 参数提供 [密集嵌入](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md) 值。

```python theme={null}
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={null}
pip install -qU fastembed
```

```python theme={null}
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://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md) 值。
* 必须提供一个使用任何稀疏嵌入提供者的 [`SparseEmbeddings`](https://github.com/langchain-ai/langchain/blob/master/libs/partners/qdrant/langchain_qdrant/sparse_embeddings.py) 接口实现，作为 `sparse_embedding` 参数的值。

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

```python theme={null}
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={null}
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={null}
* [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={null}
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={null}
* The top 10 soccer players in the world right now. [{'source': 'website', '_id': 'b0964ab5-5a14-47b4-a983-37fa5c5bd154', '_collection_name': 'demo_collection'}]
```

### 将向量存储转换为检索器

你也可以将向量存储转换为检索器，以便在链中更方便地使用。

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

```text theme={null}
[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）的指南，请参阅以下章节：

* [检索文档](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)
* [使用 LangChain 构建 RAG 应用](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/rag.md)
* [智能体 RAG](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/agentic-rag.md)

## 自定义 qdrant

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

### 命名向量

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

```python theme={null}
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={null}
{
    "page_content": "Lorem ipsum dolor sit amet",
    "metadata": {
        "foo": "bar"
    }
}
```

然而，你也可以决定使用不同的键来表示页面内容和元数据。如果已经有一个你想要重用的集合，这会很有用。

```python theme={null}
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 参考]\[QdrantVectorStore]

***

> 官方原文：[src/oss/python/integrations/vectorstores/qdrant.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/vectorstores/qdrant.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.