> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hydradb.com/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 is a structured map of relationships between stored pieces of context in your database.

It represents those relationships as **triplets**: `source → relation → target`. Each triplet is a directional connection between two pieces of context, with `source`, `relation`, and `target` returned as structured objects - not plain strings.

Context graphs augment retrieval. They do not replace it.

***

## 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 helps your LLM reason about questions that require connecting information across multiple chunks or sources. Similarity query returns relevant content; the context graph surfaces how that content 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 traverses the graph to discover relevant relationships between retrieved context.
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, graph fields may be empty.

***

## 5. Key concepts

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

Example: `billing_policy → governs → failed_payment_handling`

**`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.

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>

A response with graph context looks like:

```json 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"] }
  }
}
```

When no relevant relationships are found, graph fields may be empty.

***

## 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

**Setting `graph_context: false` and then expecting the graph slice.** Graph context is on by default - only set the flag to `false` if you explicitly don't want graph data.

**Assuming the graph replaces retrieval.** It doesn't. `chunks` is still the primary result; the graph enriches it with relationships. Use both.

**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.

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

**Expecting relationships that don't exist.** If the retrieved chunks don't share entities or declared relations, the graph fields will be empty. That's not an error - it's the absence of structure for that query.

***

## Related

* [Query](/essentials/v2/query) - how chunks and graph context are retrieved together
* [Bring Your Own Graph](/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
* [Full Query API Reference](/api-reference/v2/endpoint/query-overview) - full graph response schema
