> ## Documentation Index
> Fetch the complete documentation index at: https://cortex-e852fafe-t3code-rewrite-docs-declutter.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Context Graphs

> How HydraDB models relationships between chunks using triplets to improve query quality.

## 1. What it is

A context graph records how the things in your content relate: which team owns which service, which policy governs which process, which decision replaced which.

The named things are **entities**. A relationship connects two of them, for example `Payments team → owns → billing service`. That three-part statement is a **triplet**: `source`, `relation`, and `target`.

Following these connections is **graph traversal**. A **hop** is one connection; following two or more is called **multi-hop** retrieval. Search results can include these relationships alongside the matching passages (chunks).

***

## 2. What it does

When `graph_context: true` is set on a query call (the default), HydraDB returns relationship data alongside the retrieved chunks, showing how those chunks connect to each other and to your query. Set `graph_context: false` to drop the graph slice when you only need ranked chunks. This takes effect only in `fast` mode: `thinking` mode (including `auto` routed to thinking) always returns the graph.

This helps your LLM answer questions that connect information across chunks or sources. Similarity search finds the relevant content; the graph shows how it fits together.

***

## 3. When to use it

Use context graphs when:

* Answers require synthesising information across multiple chunks.
* Relational context matters for correctness: cause and effect, ownership, sequence, dependency.
* You need multi-hop reasoning ("What team owns the service that failed?", "What depends on this API?").

Skip them for direct factual lookups. Graph traversal adds response size and can add latency, so reserve it for queries where relational structure materially improves the answer.

***

## 4. How it works

Context graphs are hybrid: relationships are extracted at ingestion time and traversed at query time.

**At ingestion**, HydraDB extracts relationships from your data and stores them in the graph. Sources can also declare explicit relationships to other sources via a `relations` payload at ingestion. Or skip extraction for a document and supply the entities and relations yourself with [Bring Your Own Graph](/essentials/v2/bring-your-own-graph).

**At query**, when `graph_context: true` is set (the default):

1. HydraDB runs hybrid retrieval to find relevant chunks.
2. It follows graph connections to find relationships relevant to the retrieved passages.
3. It returns multi-hop paths from the query (`query_paths`), relationship paths between retrieved chunks (`chunk_relations`), and a chunk-to-path-group mapping (`chunk_id_to_group_ids`).

When no relevant relationships are found, the graph fields are empty. That is not an error; there is simply no structure to show for that query.

***

## 5. Key concepts

**Triplets:** The unit of the graph. Each triplet is a `source`, a `relation`, and a `target`, where `source` and `target` are entity objects and `relation` describes the connection between them.

Example: `billing_policy` (source) `governs` (relation) `failed_payment_handling` (target)

**`query_paths`:** Multi-hop chains of triplets connecting the query to retrieved chunks. Each path carries a relevancy score and the chunk IDs whose traversal produced it.

**`chunk_relations`:** Paths describing how returned chunks relate to one another. Same shape as `query_paths`; the difference is the anchor: query-driven vs chunk-to-chunk.

**`chunk_id_to_group_ids`:** Maps each chunk ID to the path-group identifiers (e.g. `p_0`, `p_1`) it belongs to. Use it to group retrieved chunks by which graph path produced them.

**Connected subgraph:** The graph also holds relations between *items* rather than between entities: a Slack reply and the message it answers, a page and the pages it links to, a comment and its ticket. Given one item's id, [Connected Subgraph](/api-reference/v2/endpoint/subgraph) follows those links, visiting nearby items first, and returns connected items up to the requested depth and result limit (the rest of the thread, the hierarchy above and below, the items it references) with the relations among them. Reach for it when one query result is not enough and you need what surrounds it; it is also what the dashboard's **Subgraph** button opens.

For full field schemas, see the [Query API Reference](/api-reference/v2/endpoint/query-overview).

***

## 6. Minimal working example

<CodeGroup>
  ```bash cURL theme={"dark"}
  curl -X POST 'https://api.hydradb.com/query' \
    -H "Authorization: Bearer $HYDRA_DB_API_KEY" \
    -H "API-Version: 2" \
    -H "Content-Type: application/json" \
    -d '{
      "database": "acme_corp",
      "query": "How does the billing system handle failed payments?",
      "type": "knowledge",
      "query_by": "hybrid",
      "mode": "thinking",
      "graph_context": true
    }'
  ```

  ```typescript TypeScript SDK theme={"dark"}
  const result = await client.query({
    database: "acme_corp",
    query: "How does the billing system handle failed payments?",
    type: "knowledge",
    queryBy: "hybrid",
    mode: "thinking",
    graphContext: true,
  });

  if (result.data?.graphContext) {
    for (const path of result.data.graphContext.queryPaths) {
      for (const t of path.triplets) {
        console.log(
          `${t.source.name} - ${t.relation.canonicalPredicate} → ${t.target.name}`,
        );
      }
    }
  }
  ```

  ```python Python SDK theme={"dark"}
  result = client.query(
      database="acme_corp",
      query="How does the billing system handle failed payments?",
      type="knowledge",
      query_by="hybrid",
      mode="thinking",
      graph_context=True,
  )

  if result.data.graph_context:
      for path in result.data.graph_context.query_paths:
          for t in path.triplets:
              print(
                  t.source.name,
                  " - ",
                  t.relation.canonical_predicate,
                  "→",
                  t.target.name,
              )
  ```
</CodeGroup>

The `data` payload of a response with graph context looks like:

```text theme={"dark"}
{
  "chunks": [ /* ranked chunks */ ],
  "graph_context": {
    "query_paths": [
      {
        "triplets": [
          {
            "source": { "name": "billing_policy", "type": "POLICY" },
            "relation": { "canonical_predicate": "governs" },
            "target": { "name": "failed_payment_handling", "type": "PROCESS" }
          }
        ],
        "relevancy_score": 0.84,
        "group_id": "p_0",
        "source_chunk_ids": ["chunk_abc", "chunk_def"]
      }
    ],
    "chunk_relations": [],
    "chunk_id_to_group_ids": { "chunk_abc": ["p_0"] }
  }
}
```

***

## 7. Using graph context in your prompt

To include graph relationships in your LLM prompt, use the `buildContextString` / `build_context_string` helper from [How to Use API Results](/essentials/v2/api-results). It handles `query_paths`, `chunk_relations`, and `chunk_id_to_group_ids` automatically.

The helper formats triplets as:

```
[billing_policy] -> governs -> [failed_payment_handling]: policy covering retry logic
  ↳ [failed_payment_handling] -> triggers -> [notification_service]: sends customer alert
```

***

## 8. Common mistakes

**Forgetting to disable when you don't need it:** Graph context adds response size and a small traversal cost. If your code path only consumes `chunks`, set `graph_context: false` to drop it (this takes effect only in `fast` mode).

**Treating triplets as flat strings:** `source`, `relation`, and `target` are objects with their own fields. Read them as structured data.

***

## Related

* [Query](/essentials/v2/query): how chunks and graph context are retrieved together
* [Bring Your Own Graph: per source](/essentials/v2/bring-your-own-graph): supply your own entities and relations instead of auto-extraction
* [Memories](/essentials/v2/memories): user-scoped context for personalization
* [Knowledge](/essentials/v2/knowledge): document-level context for shared retrieval
* [How to Use API Results](/essentials/v2/api-results): formatting graph context for LLM prompts
* [Query API Reference](/api-reference/v2/endpoint/query-overview): full graph response schema
* [Connected Subgraph](/api-reference/v2/endpoint/subgraph): everything connected to one item, walked breadth-first


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