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

# Graph RAG 集成

> 使用 LangChain Python 与 Graph RAG 检索器集成。

本指南提供了 Graph RAG 的简介。有关所有支持功能和配置的详细文档，请参阅
[Graph RAG 项目页面](https://datastax.github.io/graph-rag/)。

## 概述

`langchain-graph-retriever` 包中的 `GraphRetriever` 提供了一个 LangChain
[检索器](/oss/python/langchain/retrieval/)，它结合了基于向量的**非结构化**相似性搜索和基于元数据属性的**结构化**遍历。这使得可以对**现有**向量存储进行基于图的检索。

### 集成详情

| 检索器              | 来源                                                                                                                  |                                       PyPI 包                                       |                                                          最新版本                                                         |                        项目页面                        |
| :--------------- | :------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------: |
| `GraphRetriever` | [github.com/datastax/graph-rag](https://github.com/datastax/graph-rag/tree/main/packages/langchain-graph-retriever) | [`langchain-graph-retriever`](https://pypi.org/project/langchain-graph-retriever/) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-graph-retriever?style=flat-square\&label=%20\&color=orange) | [Graph RAG](https://datastax.github.io/graph-rag/) |

## 优势

* [**基于现有元数据的链接：**](https://datastax.github.io/graph-rag/guide/get-started/)
  无需额外处理即可使用现有的元数据字段。从现有向量存储中检索更多信息！

* [**按需更改链接：**](https://datastax.github.io/graph-rag/guide/edges/)
  边可以动态指定，允许根据问题遍历不同的关系。

* [**可插拔的遍历策略：**](https://datastax.github.io/graph-rag/guide/strategies/)
  使用内置的遍历策略，如 Eager 或 MMR，或定义自定义逻辑来选择要探索的节点。

* [**广泛的兼容性：**](https://datastax.github.io/graph-rag/guide/adapters/)
  提供了适用于多种向量存储的适配器，并且可以轻松添加对其他存储的支持。

## 设置

### 安装

此检索器位于 `langchain-graph-retriever` 包中。

<CodeGroup>
  ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pip install -qU langchain-graph-retriever
  ```

  ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  uv add langchain-graph-retriever
  ```
</CodeGroup>

## 实例化

以下示例将展示如何对一些关于动物的示例文档执行图遍历。

### 前提条件

<details>
  <summary>点击展开详情</summary>

  <div>
    1. 确保您已安装 Python 3.10+

    2. 安装提供示例数据的以下包。
       ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       pip install -qU graph_rag_example_helpers
       ```

    3. 下载测试文档：
       ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
       from graph_rag_example_helpers.datasets.animals import fetch_documents
       animals = fetch_documents()
       ```

    4.     <EmbeddingTabs />
  </div>
</details>

### 填充向量存储

本节展示如何使用示例数据填充各种向量存储。

有关选择以下向量存储之一的帮助，或要添加对您自己的向量存储的支持，请参阅关于
[适配器和支持的存储](https://datastax.github.io/graph-rag/guide/adapters/) 的文档。

<Tabs groupId="vector-store" queryString>
  <Tab title="AstraDB">
    <div style={{ paddingLeft: '30px' }}>
      安装带有 `astra` 额外依赖的 `langchain-graph-retriever` 包：

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langchain-graph-retriever[astra]"
      ```

      然后创建一个向量存储并加载测试文档：

      ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_astradb import AstraDBVectorStore

      vector_store = AstraDBVectorStore.from_documents(
          documents=animals,
          embedding=embeddings,
          collection_name="animals",
          api_endpoint=ASTRA_DB_API_ENDPOINT,
          token=ASTRA_DB_APPLICATION_TOKEN,
      )
      ```

      有关 `ASTRA_DB_API_ENDPOINT` 和 `ASTRA_DB_APPLICATION_TOKEN` 凭据，请参阅 [AstraDB 向量存储指南](/oss/python/integrations/vectorstores/astradb)。

      :::note
      为了更快的初始测试，考虑使用 **InMemory** 向量存储。
      :::
    </div>
  </Tab>

  <Tab title="Apache Cassandra">
    <div style={{ paddingLeft: '30px' }}>
      安装带有 `cassandra` 额外依赖的 `langchain-graph-retriever` 包：

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langchain-graph-retriever[cassandra]"
      ```

      然后创建一个向量存储并加载测试文档：

      ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_community.vectorstores.cassandra import Cassandra
      from langchain_graph_retriever.transformers import ShreddingTransformer

      vector_store = Cassandra.from_documents(
          documents=list(ShreddingTransformer().transform_documents(animals)),
          embedding=embeddings,
          table_name="animals",
      )
      ```

      有关创建 Cassandra 连接的帮助，请参阅
      [Apache Cassandra 向量存储指南](/oss/python/integrations/vectorstores/cassandra#connection-parameters)

      :::note
      Apache Cassandra 不支持在嵌套元数据中搜索。因此，在插入文档时需要使用 [`ShreddingTransformer`](https://datastax.github.io/graph-rag/reference/langchain_graph_retriever/transformers/#langchain_graph_retriever.transformers.shredding.ShreddingTransformer)。
      :::
    </div>
  </Tab>

  <Tab title="OpenSearch">
    <div style={{ paddingLeft: '30px' }}>
      安装带有 `opensearch` 额外依赖的 `langchain-graph-retriever` 包：

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langchain-graph-retriever[opensearch]"
      ```

      然后创建一个向量存储并加载测试文档：

      ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_community.vectorstores import OpenSearchVectorSearch

      vector_store = OpenSearchVectorSearch.from_documents(
          documents=animals,
          embedding=embeddings,
          engine="faiss",
          index_name="animals",
          opensearch_url=OPEN_SEARCH_URL,
          bulk_size=500,
      )
      ```

      有关创建 OpenSearch 连接的帮助，请参阅
      [OpenSearch 向量存储指南](/oss/python/integrations/vectorstores/opensearch)。
    </div>
  </Tab>

  <Tab title="Chroma">
    <div style={{ paddingLeft: '30px' }}>
      安装带有 `chroma` 额外依赖的 `langchain-graph-retriever` 包：

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langchain-graph-retriever[chroma]"
      ```

      然后创建一个向量存储并加载测试文档：

      ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_chroma.vectorstores import Chroma
      from langchain_graph_retriever.transformers import ShreddingTransformer

      vector_store = Chroma.from_documents(
          documents=list(ShreddingTransformer().transform_documents(animals)),
          embedding=embeddings,
          collection_name="animals",
      )
      ```

      有关创建 Chroma 连接的帮助，请参阅
      [Chroma 向量存储指南](/oss/python/integrations/vectorstores/chroma)。

      :::note
      Chroma 不支持在嵌套元数据中搜索。因此，在插入文档时需要使用 [`ShreddingTransformer`](https://datastax.github.io/graph-rag/reference/langchain_graph_retriever/transformers/#langchain_graph_retriever.transformers.shredding.ShreddingTransformer)。
      :::
    </div>
  </Tab>

  <Tab title="InMemory">
    <div style={{ paddingLeft: '30px' }}>
      安装 `langchain-graph-retriever` 包：

      ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langchain-graph-retriever"
      ```

      然后创建一个向量存储并加载测试文档：

      ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_core.vectorstores import InMemoryVectorStore

      vector_store = InMemoryVectorStore.from_documents(
          documents=animals,
          embedding=embeddings,
      )
      ```

      :::tip
      使用 `InMemoryVectorStore` 是开始使用 Graph RAG 的最快方式，但不建议用于生产环境。建议使用 **AstraDB** 或 **OpenSearch**。
      :::
    </div>
  </Tab>
</Tabs>

### 图遍历

此图检索器从与查询最匹配的单个动物开始，然后遍历到共享相同 `habitat` 和/或 `origin` 的其他动物。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from graph_retriever.strategies import Eager
from langchain_graph_retriever import GraphRetriever

traversal_retriever = GraphRetriever(
    store = vector_store,
    edges = [("habitat", "habitat"), ("origin", "origin")],
    strategy = Eager(k=5, start_k=1, max_depth=2),
)
```

上述代码创建了一个图遍历检索器，它从最近的动物（`start_k=1`）开始，检索 5 个文档（`k=5`），并将搜索限制在距离第一个动物最多 2 步的文档（`max_depth=2`）。

`edges` 定义了如何使用元数据值进行遍历。在这种情况下，每个动物都与具有相同 `habitat` 和/或 `origin` 的其他动物相连。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
results = traversal_retriever.invoke("what animals could be found near a capybara?")

for doc in results:
    print(f"{doc.id}: {doc.page_content}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
capybara: capybaras are the largest rodents in the world and are highly social animals.
heron: herons are wading birds known for their long legs and necks, often seen near water.
crocodile: crocodiles are large reptiles with powerful jaws and a long lifespan, often living over 70 years.
frog: frogs are amphibians known for their jumping ability and croaking sounds.
duck: ducks are waterfowl birds known for their webbed feet and quacking sounds.
```

图遍历通过利用数据中的结构化关系来提高检索质量。与标准相似性搜索（见下文）不同，它为文档的选择提供了清晰、可解释的理由。

在这种情况下，文档 `capybara`、`heron`、`frog`、`crocodile` 和 `newt` 都共享相同的 `habitat=wetlands`，如其元数据所定义。这应该会增加文档相关性并提高 LLM 答案的质量。

### 与标准检索的比较

当 `max_depth=0` 时，图遍历检索器的行为类似于标准检索器：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
standard_retriever = GraphRetriever(
    store = vector_store,
    edges = [("habitat", "habitat"), ("origin", "origin")],
    strategy = Eager(k=5, start_k=5, max_depth=0),
)
```

这创建了一个从最近的 5 个动物（`start_k=5`）开始，并在没有任何遍历（`max_depth=0`）的情况下返回它们的检索器。在这种情况下，边定义被忽略。

这本质上等同于：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
standard_retriever = vector_store.as_retriever(search_kwargs={"k":5})
```

对于任一情况，调用检索器返回：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
results = standard_retriever.invoke("what animals could be found near a capybara?")

for doc in results:
    print(f"{doc.id}: {doc.page_content}")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
capybara: capybaras are the largest rodents in the world and are highly social animals.
iguana: iguanas are large herbivorous lizards often found basking in trees and near water.
guinea pig: guinea pigs are small rodents often kept as pets due to their gentle and social nature.
hippopotamus: hippopotamuses are large semi-aquatic mammals known for their massive size and territorial behavior.
boar: boars are wild relatives of pigs, known for their tough hides and tusks.
```

这些文档仅基于相似性进行连接。存储中存在的任何结构化数据都被忽略。与图检索相比，这可能会降低文档相关性，因为返回的结果对回答查询的帮助可能性较低。

## 用法

按照上面的示例，使用 `invoke` 来启动对查询的检索。

***

## API 参考

要探索所有可用参数和高级配置，请参阅
[Graph RAG API 参考](https://datastax.github.io/graph-rag/reference/)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/retrievers/graph_rag.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
