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

# Query

> Unified retrieval over knowledge, memories, or both.

export const Field = ({name, type, required, recommended}) => {
  const label = required ? 'required' : recommended ? 'recommended' : null;
  const typeLabel = typeof type === 'string' ? type : null;
  const ariaParts = [name, typeLabel && `${typeLabel}`, label].filter(Boolean);
  return <span aria-label={ariaParts.join(', ')} className={label ? 'field-wrap has-field-tip' : 'field-wrap'} style={{
    position: 'relative',
    cursor: label ? 'default' : undefined
  }} tabIndex={label ? 0 : undefined}>
      <span className="field-name-row">
        <code>{name}</code>
        {required && <span className="field-req"> *</span>}
        {recommended && <span className="field-rec"> ●</span>}
      </span>
      {type && <span className="field-type">{type}</span>}
      {label && <span className="field-tip" role="tooltip">
          {label}
        </span>}
    </span>;
};

The single retrieval endpoint for everything. Use it any time you need to feed an LLM with grounded context, surface user preferences, or fetch chunks ranked by relevance.

Three independent dimensions control behavior:

* **`type`** picks **what** to query: `"knowledge"`, `"memory"`, or `"all"` (both, merged and re-ranked together).
* **`query_by`** picks **how** to match: `"hybrid"` (semantic + BM25, the default) or `"text"` (BM25 only  -  pair with `operator`).
* **`mode`** picks **how** to rank results: `"fast"` (single-pass, low-latency), `"thinking"` (expands query, reranks, and can include forceful-relation context), or `"auto"` (scores the query and routes to `"fast"` or `"thinking"` automatically, defaulting to `"thinking"` when the signal is inconclusive  -  **the default if `mode` is omitted**).

Read more about choosing the perfect mode for your use case [here](/api-reference/v2/endpoint/query-overview#recommended-configurations).

<Note>
  `database` and `collection` are the current field names (formerly `tenant_id` and `sub_tenant_id`). The old names remain accepted as deprecated aliases for full backward compatibility.
</Note>

<RequestExample>
  ```python Python SDK theme={"dark"}
  result = client.query(
      database="acme_corp",
      collection="user_alex",
      query="What is our refund policy, and how should I explain it to this user?",

      # What to query: "knowledge", "memory", or "all".
      type="all",

      # How to match: "hybrid" (default) or "text" (BM25).
      query_by="hybrid",

      # "thinking" improves quality; use "fast" for lowest latency.
      mode="thinking",

      # Ranking and response controls.
      max_results=10,
      alpha="auto",
      recency_bias=0.2,
      graph_context=True,

      # Pull author-declared related sources into additional_context.
      # Only applies when mode="thinking".
      query_forceful_relations=True,

      # Top-level keys match metadata; additional_metadata is per-source.
      metadata_filters={
          "department": "support",
          "additional_metadata": {
              "source": "policy",
          },
      },

      # Short factual hint; not a hard filter.
      additional_context="User is asking from the billing help center.",
  )
  ```

  ```typescript TypeScript SDK theme={"dark"}
  const result = await client.query({
    database: "acme_corp",
    collection: "user_alex",
    query: "What is our refund policy, and how should I explain it to this user?",

    // What to query: "knowledge", "memory", or "all".
    type: "all",

    // How to match: "hybrid" (default) or "text" (BM25).
    queryBy: "hybrid",

    // "thinking" improves quality; use "fast" for lowest latency.
    mode: "thinking",

    // Ranking and response controls.
    maxResults: 10,
    alpha: "auto",
    recencyBias: 0.2,
    graphContext: true,

    // Pull author-declared related sources into additional_context.
    // Only applies when mode: "thinking".
    queryForcefulRelations: true,

    // Top-level keys match metadata; additional_metadata is per-source.
    metadataFilters: {
      department: "support",
      additional_metadata: {
        source: "policy",
      },
    },

    // Short factual hint; not a hard filter.
    additionalContext: "User is asking from the billing help center.",
  });
  ```

  ```bash cURL theme={"dark"}
  curl -X POST 'https://api.hydradb.com/query' \
    -H "Authorization: Bearer <your_api_key>" \
    -H "API-Version: 2" \
    -H "Content-Type: application/json" \
    -d '{
      "database": "acme_corp",
      "collection": "user_alex",
      "query": "What is our refund policy, and how should I explain it to this user?",
      "type": "all",
      "query_by": "hybrid",
      "mode": "thinking",
      "max_results": 10,
      "alpha": "auto",
      "recency_bias": 0.2,
      "graph_context": true,
      "query_forceful_relations": true,
      "metadata_filters": {
        "department": "support",
        "additional_metadata": {
          "source": "policy"
        }
      },
      "additional_context": "User is asking from the billing help center."
    }'
  ```
</RequestExample>

### Querying multiple collections

Use `collections` when one query should fan out across multiple user, workspace, or team scopes. The field accepts either a list or a weighted object:

```json Equal weighting theme={"dark"}
{
  "database": "acme_corp",
  "collections": ["workspace_42", "user_alex"],
  "query": "What renewal risks should I know about?",
  "type": "all"
}
```

```json Weighted ranking theme={"dark"}
{
  "database": "acme_corp",
  "collections": {
    "workspace_42": 2,
    "user_alex": 1
  },
  "query": "What renewal risks should I know about?",
  "type": "all"
}
```

A list gives every collection equal normalized weight. An object treats values as positive relative ranking weights with at most one decimal place and normalizes them server-side. You can send at most 100 collections. When `max_results` is omitted, HydraDB uses up to 10 results per collection, capped at 1000 fanout candidates before the final ranked response is shaped. When `max_results` is set, it is the final global response cap across the merged fanout result set.

> **Caching tip:** `collections` list order is not semantically significant for fanout selection. Sort list values before constructing cache keys; for weighted objects, sort keys and keep weights at the documented one-decimal precision so equivalent calls share the same cache entry.

### Transforming the response into LLM context

Use `build_string` / `buildString` from the SDK. It takes any `POST /query` result and returns a formatted plain string.

<CodeGroup>
  ```python Python SDK theme={"dark"}
  from hydra_db import HydraDB
  from hydra_db.helpers import build_string

  client = HydraDB(token="YOUR_API_KEY")

  result = client.query(
      database="your-database",
      collection="your-collection",
      query="How does authentication work?",
      type="knowledge",
      query_by="hybrid",
      max_results=5,
      mode="fast",
      graph_context=True,
  )

  context = build_string(result)
  ```

  ```typescript TypeScript SDK theme={"dark"}
  import { HydraDBClient, buildString } from "@hydradb/sdk";

  const client = new HydraDBClient({ token: process.env.HYDRA_DB_API_KEY });

  const result = await client.query({
    database: "your-database",
    collection: "your-collection",
    query: "How does authentication work?",
    type: "knowledge",
    queryBy: "hybrid",
    maxResults: 5,
    mode: "fast",
    graphContext: true,
  });

  const context = buildString(result);
  ```
</CodeGroup>

## Common use-cases and their configurations

<AccordionGroup>
  <Accordion title="1. Knowledge RAG - answer from shared documents">
    <CodeGroup>
      ```bash cURL theme={"dark"}
      curl -X POST 'https://api.hydradb.com/query' \
        -H "Authorization: Bearer <your_api_key>" \
        -H "API-Version: 2" \
        -H "Content-Type: application/json" \
        -d '{
          "database": "acme_corp",
          "query": "What is our refund policy?",
          "type": "knowledge",
          "query_by": "hybrid",
          "mode": "thinking",
          "max_results": 10,
          "graph_context": true
        }'
      ```

      ```typescript TypeScript SDK theme={"dark"}
      const result = await client.query({
        database: "acme_corp",
        query: "What is our refund policy?",
        type: "knowledge",
        queryBy: "hybrid",
        mode: "thinking",
        maxResults: 10,
        graphContext: true,
      });
      ```

      ```python Python SDK theme={"dark"}
      result = client.query(
          database="acme_corp",
          query="What is our refund policy?",
          type="knowledge",
          query_by="hybrid",
          mode="thinking",
          max_results=10,
          graph_context=True,
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="2. Personalized answer - combine knowledge with user memories">
    <CodeGroup>
      ```bash cURL theme={"dark"}
      curl -X POST 'https://api.hydradb.com/query' \
        -H "Authorization: Bearer <your_api_key>" \
        -H "API-Version: 2" \
        -H "Content-Type: application/json" \
        -d '{
          "database": "acme_corp",
          "collection": "user_alex",
          "query": "What is our refund policy, and how should I explain it to this user?",
          "type": "all",
          "query_by": "hybrid",
          "mode": "thinking"
        }'
      ```

      ```typescript TypeScript SDK theme={"dark"}
      const result = await client.query({
        database: "acme_corp",
        collection: "user_alex",
        query: "What is our refund policy, and how should I explain it to this user?",
        type: "all",
        queryBy: "hybrid",
        mode: "thinking",
      });
      ```

      ```python Python SDK theme={"dark"}
      result = client.query(
          database="acme_corp",
          collection="user_alex",
          query="What is our refund policy, and how should I explain it to this user?",
          type="all",
          query_by="hybrid",
          mode="thinking",
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="3. Retrieve user preferences - query only user memories">
    <CodeGroup>
      ```bash cURL theme={"dark"}
      curl -X POST 'https://api.hydradb.com/query' \
        -H "Authorization: Bearer <your_api_key>" \
        -H "API-Version: 2" \
        -H "Content-Type: application/json" \
        -d '{
          "database": "acme_corp",
          "collection": "user_alex",
          "query": "Does the user have any specific preferences for tone or response length?",
          "type": "memory",
          "query_by": "hybrid",
          "query_apps": true
        }'
      ```

      ```typescript TypeScript SDK theme={"dark"}
      const result = await client.query({
        database: "acme_corp",
        collection: "user_alex",
        query: "Does the user have any specific preferences for tone or response length?",
        type: "memory",
        queryBy: "hybrid",
        queryApps: true,
      });
      ```

      ```python Python SDK theme={"dark"}
      result = client.query(
          database="acme_corp",
          collection="user_alex",
          query="Does the user have any specific preferences for tone or response length?",
          type="memory",
          query_by="hybrid",
          query_apps=True,
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="4. Exact phrase lookup - BM25 for legal terms, SKUs, or IDs">
    <CodeGroup>
      ```bash cURL theme={"dark"}
      curl -X POST 'https://api.hydradb.com/query' \
        -H "Authorization: Bearer <your_api_key>" \
        -H "API-Version: 2" \
        -H "Content-Type: application/json" \
        -d '{
          "database": "acme_corp",
          "query": "GDPR Article 17",
          "type": "knowledge",
          "query_by": "text",
          "operator": "phrase"
        }'
      ```

      ```typescript TypeScript SDK theme={"dark"}
      const result = await client.query({
        database: "acme_corp",
        query: "GDPR Article 17",
        type: "knowledge",
        queryBy: "text",
        operator: "phrase",
      });
      ```

      ```python Python SDK theme={"dark"}
      result = client.query(
          database="acme_corp",
          query="GDPR Article 17",
          type="knowledge",
          query_by="text",
          operator="phrase",
      )
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="5. Let HydraDB decide - auto-route between fast and thinking">
    <CodeGroup>
      ```bash cURL theme={"dark"}
      curl -X POST 'https://api.hydradb.com/query' \
        -H "Authorization: Bearer <your_api_key>" \
        -H "API-Version: 2" \
        -H "Content-Type: application/json" \
        -d '{
          "database": "acme_corp",
          "query": "How does the Q2 partnership between Acme and Globex affect our SLA with Initech?",
          "type": "knowledge",
          "query_by": "hybrid",
          "mode": "auto"
        }'
      ```

      ```typescript TypeScript SDK theme={"dark"}
      const result = await client.query({
        database: "acme_corp",
        query: "How does the Q2 partnership between Acme and Globex affect our SLA with Initech?",
        type: "knowledge",
        queryBy: "hybrid",
        mode: "auto",
      });
      ```

      ```python Python SDK theme={"dark"}
      result = client.query(
          database="acme_corp",
          query="How does the Q2 partnership between Acme and Globex affect our SLA with Initech?",
          type="knowledge",
          query_by="hybrid",
          mode="auto",
      )
      ```
    </CodeGroup>

    HydraDB scores the query before retrieval and routes it to `"fast"` or `"thinking"`  -  a query naming several distinct entities like this one is likely to route to `"thinking"`. Use `"auto"` for traffic where query complexity varies call-to-call and you don't want to hand-pick per request. This is also the default: an omitted `mode` field behaves exactly like `mode: "auto"`. Set `mode` to `"fast"` or `"thinking"` explicitly if you want a deterministic pipeline instead.
  </Accordion>
</AccordionGroup>

## Request body

| Name                                                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <Field name="database" type="string" required />                                            | Owning database. Formerly `tenant_id`; the `tenant_id` alias is still accepted (deprecated).                                                                                                                                                                                                                                                                                                               |
| <Field name="collection" type="string or null" />                                           | Single collection scope. Required for per-user memory queries. Formerly `sub_tenant_id`; the `sub_tenant_id` alias is still accepted (deprecated). (default=default collection)                                                                                                                                                                                                                            |
| <Field name="collections" type="string[] or object" />                                      | Multi-collection scope. Send a list of collection IDs for equal weighting, or an object mapping collection ID to a positive relative weight (at most one decimal place, e.g. `{"finance": 1.5, "legal": 0.8}`) to bias ranking. Up to 100 collections. Do not combine with `collection`/`sub_tenant_id`. Formerly `sub_tenant_ids`; the `sub_tenant_ids` alias is still accepted (deprecated since 2.0.1). |
| <Field name="query" type="string" required />                                               | Query terms or natural-language question. Cannot be empty.                                                                                                                                                                                                                                                                                                                                                 |
| <Field name="type" type="&#x22;knowledge&#x22; or &#x22;memory&#x22; or &#x22;all&#x22;" /> | What collection to query. `"all"` runs knowledge and memory in parallel and merges by `relevancy_score`. (default=`"knowledge"`)                                                                                                                                                                                                                                                                           |
| <Field name="query_by" type="&#x22;hybrid&#x22; or &#x22;text&#x22;" />                     | Retrieval method. See [Query methods](#decision-matrix). (default=`"hybrid"`)                                                                                                                                                                                                                                                                                                                              |
| <Field name="query_apps" type="boolean" />                                                  | Adds an app-aware retrieval lane for app sources while still querying the full selected knowledge scope. Set `true` for better app-source matching, thread/relation traversal, exact IDs, and actor/provider hints. It does **not** limit query to only app sources. (default=`false`)                                                                                                                     |
| <Field name="operator" type="&#x22;or&#x22; or &#x22;and&#x22; or &#x22;phrase&#x22;" />    | BM25 operator for `query_by: "text"`. Ignored for `hybrid`. (default=`"or"`)                                                                                                                                                                                                                                                                                                                               |
| <Field name="mode" type="&#x22;fast&#x22;, &#x22;thinking&#x22;, or &#x22;auto&#x22;" />    | Retrieval pipeline. Applies to `hybrid` only; ignored for `text`. `"auto"` scores the query before retrieval and resolves it to `"fast"` or `"thinking"`, defaulting to `"thinking"` when the signal is inconclusive; it also overrides whatever `graph_context` you sent to match that resolved mode. (default=`"auto"`)                                                                                  |
| <Field name="max_results" type="integer or null" />                                         | Maximum chunks to return. Default `10`; maximum `50`. Start with `10`, use `5` for tight prompts, and increase only when reranking downstream.                                                                                                                                                                                                                                                             |
| <Field name="alpha" type="float 0.0–1.0 or &#x22;auto&#x22;" />                             | Hybrid weight (`1.0` = pure semantic, `0.0` = pure BM25). Applies to `query_by: "hybrid"` only. (default=`0.8`)                                                                                                                                                                                                                                                                                            |
| <Field name="recency_bias" type="float 0.0–1.0" />                                          | Boost newer content. (default=`0.0`)                                                                                                                                                                                                                                                                                                                                                                       |
| <Field name="graph_context" type="boolean" />                                               | When `true`, includes the entity/relation graph slice in the response under `graph_context`. Set to `false` when you only need ranked chunks. Relations you supplied via [Bring Your Own Graph](/essentials/v2/bring-your-own-graph) appear here identically to extracted ones. (default=`true`)  -  **under `mode: "auto"`, this value is overridden by the resolved mode regardless of what you send.**  |
| <Field name="query_forceful_relations" type="boolean" />                                    | Pull author-declared related sources into `additional_context`. **Only takes effect when `mode` resolves to `"thinking"`**  -  silently ignored in `fast` mode, and under `mode: "auto"` whether it takes effect depends on the automatic routing decision. (default=`true`)                                                                                                                               |
| <Field name="additional_context" type="string or null" />                                   | Request-time hint to guide retrieval (e.g., "user is on the billing page"). This is different from the response `additional_context` map. (default=`null`)                                                                                                                                                                                                                                                 |
| <Field name="metadata_filters" type="object or null" />                                     | Deterministic narrowing before ranking. See [Filters](#decision-matrix). (default=`null`)                                                                                                                                                                                                                                                                                                                  |

<Tip>
  **Tuning heuristics.**

  <ul>
    <li><strong><code>alpha</code></strong>: start at <code>0.8</code>. Lower toward <code>0.3–0.5</code> when the query contains literal tokens (error codes, SKUs, product names). Raise toward <code>0.9</code> for conceptual questions. Use <code>"auto"</code> when query shape varies.</li>
    <li><strong><code>recency\_bias</code></strong>: leave at <code>0</code> for static reference material. Set <code>0.2–0.4</code> for mixed content, <code>0.6–0.8</code> for changelogs, news, or status updates.</li>
    <li><strong><code>max\_results</code></strong>: start at <code>10</code>. Drop to <code>5</code> for tight context windows; raise to <code>20</code> if you rerank downstream.</li>
  </ul>
</Tip>

### Decision matrix

<AccordionGroup>
  <Accordion title="Type selection">
    | Value                     | Queries                                                | Best for                                                                |
    | ------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------- |
    | `"knowledge"` *(default)* | Knowledge documents, files, and app sources            | Document Q\&A, RAG context.                                             |
    | `"query_apps=true"`       | Full selected knowledge scope plus app-aware retrieval | App-specific Q\&A that should still query non-app knowledge documents.  |
    | `"memory"`                | User memories                                          | Personalization and user preferences.                                   |
    | `"all"`                   | Both, merged in one ranked result set                  | Personalized answers grounded in both shared and user-specific context. |
  </Accordion>

  <Accordion title="Query methods">
    | Method                 | Pipeline                     | Best for                                                             |
    | ---------------------- | ---------------------------- | -------------------------------------------------------------------- |
    | `"hybrid"` *(default)* | Dense vectors + BM25 keyword | General-purpose retrieval and RAG.                                   |
    | `"text"`               | BM25 only                    | Exact terms, compliance lookups, phrase query. Pair with `operator`. |
  </Accordion>

  <Accordion title="Modes">
    For `query_by: "hybrid"`:

    | Mode                                      | Behavior                                                                                                                                                                                             | When to use                                                                         |
    | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
    | `"fast"`                                  | Single query pass                                                                                                                                                                                    | Real-time chat, autocomplete, simple lookups.                                       |
    | `"thinking"`                              | Multi-query expansion + reranking + forceful-relation context                                                                                                                                        | Complex queries, customer-facing answers, anything where quality matters.           |
    | `"auto"` *(default if `mode` is omitted)* | Scores the query before retrieval and routes to `"fast"` or `"thinking"`; defaults to `"thinking"` when the signal is inconclusive. Also overrides `graph_context` to match whichever mode it picks. | Mixed or unpredictable query traffic where you don't want to hand-pick per request. |

    `"auto"`'s resolved pipeline isn't reported back in the response, so budget latency as thinking-level in the worst case. Omitting `mode` behaves exactly like `mode: "auto"` - set it explicitly to `"fast"` or `"thinking"` if you want a deterministic pipeline instead.
  </Accordion>

  <Accordion title="Filters">
    `metadata_filters` are hard exact-match constraints applied before ranking and re-checked after hydration. The shape combines two filter scopes:

    ```json theme={"dark"}
    {
      "metadata_filters": {
        "department": "engineering",
        "region": "us-east",
        "additional_metadata": {
          "source": "account_plan",
          "author": "alex"
        }
      }
    }
    ```

    | Where                                       | What it matches                                                                                                                                                           |
    | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | **Top-level keys** (`department`, `region`) | The source's schema-backed `metadata`. Keys must be declared in the database's `database_metadata_schema` with `enable_match: true`, otherwise they are silently ignored. |
    | **Nested under `additional_metadata`**      | The source's free-form per-document fields. No schema declaration required. `document_metadata` is accepted as a legacy alias.                                            |

    Multiple filters are ANDed. Range, contains, fuzzy, and OR operators are not supported in user-provided `metadata_filters`; run multiple queries or post-process client-side for those cases.
  </Accordion>
</AccordionGroup>

<ResponseExample>
  ```json Success theme={"dark"}
  {
    "success": true,
    "data": {
      "chunks": [
        {
          "chunk_uuid": "policy_main_chunk_3",
          "id": "policy_main",
          "chunk_content": "Refunds are issued within 30 days...",
          "source_type": "pdf",
          "source_title": "Compliance Policy",
          "source_upload_time": "2026-05-12T08:14:00Z",
          "source_last_updated_time": "2026-05-12T08:14:00Z",
          "layout": "{\"offsets\":{\"document_level_start_index\":1024},\"page\":3}",
          "relevancy_score": 0.91,
          "extra_context_ids": ["pref-tone"],
          "metadata": { "department": "legal" },
          "additional_metadata": { "author": "Legal Team" }
        }
      ],
      "sources": [
        {
          "id": "policy_main",
          "title": "Compliance Policy",
          "type": "pdf",
          "description": "",
          "url": "",
          "timestamp": "2026-05-12T08:14:00Z",
          "metadata": { "department": "legal" },
          "additional_metadata": { "author": "Legal Team" },
          "app_kind": null,
          "app_provider": null,
          "app_external_id": null
        }
      ],
      "graph_context": {
        "query_paths": [
          {
            "triplets": [
              {
                "source": {
                  "name": "Compliance Policy",
                  "type": "DOCUMENT",
                  "namespace": "default",
                  "entity_id": "entity_compliance_policy",
                  "identifier": "https://api.hydradb.com/docs/compliance_policy"
                },
                "relation": {
                  "canonical_predicate": "GOVERNS",
                  "raw_predicate": "governs and regulates",
                  "context": "The compliance policy governs the refund processing timeline of 30 days.",
                  "confidence": 0.95,
                  "temporal_details": null,
                  "timestamp": 1778573640.0,
                  "relationship_id": "rel_governs_refunds",
                  "chunk_id": "policy_main_chunk_3",
                  "source_entity_id": "entity_compliance_policy",
                  "target_entity_id": "entity_refund_processing"
                },
                "target": {
                  "name": "Refund Processing",
                  "type": "PROCESS",
                  "namespace": "default",
                  "entity_id": "entity_refund_processing",
                  "identifier": null
                }
              }
            ],
            "relevancy_score": 0.89,
            "combined_context": "The Compliance Policy governs the Refund Processing, which regulates refunds.",
            "group_id": null,
            "source_chunk_ids": ["policy_main_chunk_3"]
          }
        ],
        "chunk_relations": [
          {
            "triplets": [
              {
                "source": {
                  "name": "Refund Processing",
                  "type": "PROCESS",
                  "namespace": "default",
                  "entity_id": "entity_refund_processing",
                  "identifier": null
                },
                "relation": {
                  "canonical_predicate": "MANAGED_BY",
                  "raw_predicate": "is managed by",
                  "context": "Refund processing is managed by the Finance Department.",
                  "confidence": 0.9,
                  "temporal_details": "Q2 2026 onwards",
                  "timestamp": 1778573640.0,
                  "relationship_id": "rel_managed_by_finance",
                  "chunk_id": "policy_main_chunk_3",
                  "source_entity_id": "entity_refund_processing",
                  "target_entity_id": "entity_finance_dept"
                },
                "target": {
                  "name": "Finance Department",
                  "type": "ORGANIZATION",
                  "namespace": "default",
                  "entity_id": "entity_finance_dept",
                  "identifier": "finance@hydradb.com"
                }
              }
            ],
            "relevancy_score": 0.82,
            "combined_context": "Refund Processing is managed by the Finance Department.",
            "group_id": "p_0",
            "source_chunk_ids": ["policy_main_chunk_3"]
          }
        ],
        "chunk_id_to_group_ids": {
          "policy_main_chunk_3": ["p_0"]
        }
      },
      "additional_context": {
        "pref-tone": {
          "chunk_uuid": "pref-tone",
          "id": "mem_user_alex_tone",
          "chunk_content": "Prefers concise answers.",
          "source_type": "memory",
          "source_title": "User preferences",
          "source_upload_time": "2026-05-12T08:14:00Z",
          "source_last_updated_time": "2026-05-12T08:14:00Z"
        }
      }
    },
    "error": null,
    "meta": {
      "request_id": "9d13aef4-02f4-4e73-8c62-4c2601d04f9d",
      "latency_ms": 12.3
    }
  }
  ```

  ```json Zero results theme={"dark"}
  {
    "success": true,
    "data": {
      "chunks": [],
      "sources": [],
      "graph_context": {
        "query_paths": [],
        "chunk_relations": [],
        "chunk_id_to_group_ids": {}
      },
      "additional_context": {}
    },
    "error": null,
    "meta": {
      "request_id": "9d13aef4-02f4-4e73-8c62-4c2601d04f9d",
      "latency_ms": 12.3
    }
  }
  ```

  ```json Failure theme={"dark"}
  {
    "success": false,
    "data": null,
    "error": {
      "code": "INVALID_PARAMETERS",
      "message": "query must not be empty"
    },
    "meta": {
      "request_id": "9d13aef4-02f4-4e73-8c62-4c2601d04f9d",
      "latency_ms": 4.8
    }
  }
  ```
</ResponseExample>

A zero-result query returns empty arrays/maps rather than an error, as shown in the **Zero results** tab.

## Behavior notes

<Info>
  **Default Behaviors**

  * **`mode` defaults to `"auto"`.** Omitting `mode` entirely behaves exactly like `mode: "auto"`  -  set it explicitly to `"fast"` or `"thinking"` if you want a deterministic pipeline.
  * **`graph_context` is on by default.** Set it to `false` if you only need ranked chunks and want to drop the graph slice from the response.
  * **`recency_bias` is off by default.** Defaults to `0.0`  -  no recency boost is applied unless you set it.
</Info>

<Warning>
  **Important Considerations & Common Mistakes**

  * **`query_forceful_relations` requires `mode` to resolve to `"thinking"`.** In `fast` mode the flag is silently ignored. The server does not error or warn  -  your `additional_context` will simply be empty. Under `mode: "auto"` this depends on that request's routing decision, not on what you asked for.
  * **`mode: "auto"` overrides `graph_context`.** Whatever you send for `graph_context` is replaced to match the resolved mode  -  `true` if auto escalates to `thinking`, `false` if it resolves to `fast`. This also applies when `mode` is omitted, since it defaults to `"auto"`. Set `graph_context` explicitly only when calling `"fast"` or `"thinking"` directly.
  * **Want a deterministic pipeline instead of automatic routing?** Set `mode` explicitly to `"fast"` or `"thinking"`  -  an omitted `mode` field now defaults to `"auto"`, not `"fast"`.
  * **Relation `timestamp` is a Unix epoch float here.** In the `graph_context` slice returned by `/query` - and in the passthrough relations returned by [List Documents](/api-reference/v2/endpoint/list-documents) with `include_fields: ["relations"]` - each relation's `timestamp` is a Unix epoch value in seconds (a float, e.g. `1778573640.0`). The dedicated [Context Relations](/api-reference/v2/endpoint/source-relations) endpoint returns the same field as an ISO-8601 string instead. Normalize before comparing relation timestamps across endpoints.
  * **Use the right metadata namespace.** Top-level `metadata_filters` keys match `metadata`; free-form per-document fields must be nested under `additional_metadata` (`document_metadata` is only a legacy alias). Declare hot top-level filter fields in `database_metadata_schema` with `enable_match: true`.
  * **Common mistakes.** Check [Ingestion Status](/api-reference/v2/endpoint/source-status) for recently ingested documents before querying. If you omit `collection`, HydraDB queries the default collection; use [List Collections](/api-reference/v2/endpoint/list-sub-tenants) to discover available IDs.
</Warning>

## Errors

Common codes: `400 INVALID_PARAMETERS` (empty `query`), `404 DATABASE_NOT_FOUND`, `422 VALIDATION_ERROR`, `500 INTERNAL_ERROR`. See [Error Responses](/api-reference/v2/error-responses) for the full list.

<div className="api-before-related-resources" />

<Tip>
  **Related Resources**

  * **Setup first:** [Ingest Context](/api-reference/v2/endpoint/ingest-context) - content must be indexed
  * **Confirm indexing:** [Ingestion Status](/api-reference/v2/endpoint/source-status) - wait for `completed` (or `graph_creation`)
  * **Graph follow-up:** [Context Relations](/api-reference/v2/endpoint/source-relations) - inspect relationships in detail
  * **Concepts:** [Usage → Query](/essentials/v2/query)
  * **Concepts:** [Concepts → Semantic Search](/essentials/v2/semantic-search)
  * **Concepts:** [Concepts → Context Graphs](/essentials/v2/context-graphs)
  * **Response handling:** [Usage → How to Use API Results](/essentials/v2/api-results)
  * **Read more:** [Query - Overview](/api-reference/v2/endpoint/query-overview)
</Tip>


## OpenAPI

````yaml api-reference/v2/openapi.json POST /query
openapi: 3.1.0
info:
  contact:
    email: support@hydradb.com
    name: HydraDB Support
  description: >-
    HydraDB Application API — knowledge ingestion, search, and memory
    management.
  license:
    name: Proprietary
  title: HydraDB Application API
  version: 0.1.0
servers:
  - description: Production server
    url: https://api.hydradb.com
security: []
externalDocs:
  description: ''
  url: ''
paths:
  /query:
    post:
      tags:
        - query
      summary: Unified query
      description: >-
        Unified query endpoint that dispatches across type
        (knowledge/memory/all) and query_by (hybrid/text). Prefer sub_tenant_ids
        for sub-tenant scoping; legacy sub_tenant_id is deprecated for /query
        and cannot be sent together with sub_tenant_ids.
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/search.QueryRequest'
        description: Unified query request
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/handler.Envelope-search_V2RetrievalResult'
          description: OK
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/handler.ErrorResponse'
          description: Bad Request
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/handler.ErrorResponse'
          description: Not Found
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/handler.ErrorResponse'
          description: Internal Server Error
      security:
        - BearerAuth: []
components:
  schemas:
    search.QueryRequest:
      properties:
        additional_context:
          description: >-
            Optional context string prepended to the query to improve retrieval
            relevance.
          example: The user is a senior engineer onboarding to the platform.
          type: string
        alpha:
          description: >-
            Weighting balance between dense and sparse retrieval in hybrid mode.
            `"auto"` lets HydraDB choose; a number from 0 (full BM25) to 1 (full
            dense) sets it explicitly.
        collection:
          description: >-
            Collection scope. Defaults to the default collection when omitted.
            Formerly `sub_tenant_id`; the `sub_tenant_id` alias is still
            accepted (deprecated).
          example: team_docs
          type: string
        collections:
          description: >-
            Preferred /query scope selector. Send either a list of collection
            IDs for equal normalized weighting, or an object mapping collection
            ID to a positive relative ranking weight with at most one decimal
            place. Do not send together with the deprecated sub_tenant_ids or
            sub_tenant_id.
          example:
            - team_docs
            - engineering
          oneOf:
            - example:
                - finance
                - legal
              items:
                type: string
              maxItems: 100
              minItems: 1
              type: array
            - additionalProperties:
                exclusiveMinimum: 0
                multipleOf: 0.1
                type: number
              example:
                finance: 1.5
                legal: 0.8
              maxProperties: 100
              minProperties: 1
              type: object
          x-preferred: true
        database:
          description: >-
            Database is the canonical v2 name for the tenant scope. TenantID is
            its

            deprecated alias and remains fully accepted. The TenantAliases
            middleware

            reconciles the two before binding, so TenantID is always populated
            and the

            handler reads it; Database/Collection are carried only for
            docs/OpenAPI.
          example: acme_corp
          type: string
        graph_context:
          description: >-
            Whether to include graph context in the response. Defaults to true
            for /query when omitted.
          example: true
          type: boolean
        graph_vector_prune:
          description: >-
            GraphVectorPrune switches the graph-connected-chunks lane from
            "fetch

            graph-selected chunks and let the fusion reranker sort them out" to
            "fetch

            a wider graph-selected candidate pool, then rank that pool by Milvus
            vector

            similarity, fully replacing the final chunk list." Works in either
            fast or

            thinking mode. Default false preserves existing behavior. Also gated

            server-side by a repo-level config flag (SearchService's

            graphVectorPruneEnabled) — if that flag is off, this is forced to
            false

            regardless of what the request sets, so a deployment can disable the

            mechanism without any client-side change.
          example: true
          type: boolean
        graph_vector_prune_spacy_entities:
          description: >-
            GraphVectorPruneSpacyEntities: when GraphVectorPrune is also set,
            swaps the

            graph lane's entity-extraction source from the default LLM-based
            extractor

            to a local spaCy subprocess (faster, no network round trip, but a

            narrower/mismatched entity vocabulary versus the graph's own
            LLM-extracted

            node names). No-op if GraphVectorPrune is false (including when
            forced

            false by the server-level flag) or no spaCy extractor was configured
            at

            startup.
          example: true
          type: boolean
        ids:
          description: >-
            IDs optionally scopes retrieval to specific source ids. The v2 wire
            field is

            `ids` (matching /context/list); empty means search the whole corpus.
            Applied

            as a Milvus `source_id in [...]` pre-filter that is preserved across
            the

            metadata zero-result retry, so a source-scoped search that matches
            nothing

            returns nothing rather than silently widening to the whole corpus.
          example:
            - HydraDoc1234
            - HydraDoc4567
          items:
            type: string
          type: array
          uniqueItems: false
        max_results:
          description: Maximum number of chunks to return.
          example: 10
          type: integer
        metadata_filters:
          $ref: '#/components/schemas/search.MetadataFilters'
        mode:
          $ref: '#/components/schemas/search.RecallMode'
          example: thinking
        num_related_chunks:
          description: >-
            Number of adjacent chunks to pull alongside each matched chunk for
            additional context.
          example: 3
          type: integer
        operator:
          $ref: '#/components/schemas/search.Operator'
          example: and
        query:
          description: Natural-language search query.
          example: Which mode does the user prefer?
          type: string
        query_apps:
          description: >-
            Whether to include app-aware knowledge retrieval. Applies to
            knowledge hybrid queries.
          example: true
          type: boolean
        query_by:
          $ref: '#/components/schemas/search.QueryBy'
          description: Retrieval method to use for the query.
          example: hybrid
        query_forceful_relations:
          description: >-
            Whether to force relation expansion for graph-aware query retrieval.
            Defaults to true when omitted.
          example: true
          type: boolean
        recency_bias:
          description: >-
            Recency boost applied to ranking. 0 disables it; higher values
            favour more recent sources.
          example: 0.2
          type: number
        sub_tenant_id:
          deprecated: true
          description: >-
            Deprecated for /query (since 2.0.1). Use collection for a single
            scope or collections for multiple. Backwards-compatible and will be
            removed in a future version. Do not send together with a multi-scope
            selector.
          example: sub_tenant_4567
          type: string
          x-deprecated-since: 2.0.1
        sub_tenant_ids:
          deprecated: true
          description: >-
            Deprecated for /query (since 2.0.1). Use collections instead; it
            accepts the same list or weighted-object shape. Backwards-compatible
            and will be removed in a future version. Do not send together with
            collections.
          example:
            - sub_tenant_4567
            - sub_tenant_8901
          oneOf:
            - example:
                - finance
                - legal
              items:
                type: string
              maxItems: 100
              minItems: 1
              type: array
            - additionalProperties:
                exclusiveMinimum: 0
                multipleOf: 0.1
                type: number
              example:
                finance: 1.5
                legal: 0.8
              maxProperties: 100
              minProperties: 1
              type: object
          x-deprecated: 'true'
          x-deprecated-since: 2.0.1
        tenant_id:
          deprecated: true
          description: 'deprecated: use database'
          example: tenant_1234
          type: string
          x-deprecated: 'true'
        type:
          $ref: '#/components/schemas/search.SourceType'
          description: 'Corpus to query: knowledge, memory, or all.'
      type: object
    handler.Envelope-search_V2RetrievalResult:
      properties:
        data:
          $ref: '#/components/schemas/search.V2RetrievalResult'
          example:
            additional_context: The user is a senior engineer onboarding to the platform.
            chunks:
              - additional_metadata:
                  author: ada
                  doc_version: 3
                chunk_content: >-
                  HydraDB supports hybrid retrieval across knowledge and
                  memories.
                chunk_uuid: a1b2c3d4-e5f6-7890-1234-567890abcdef
                extra_context_ids:
                  - HydraEmbeddings123_2
                  - HydraEmbeddings123_3
                id: HydraDoc1234
                layout: text
                metadata:
                  department: finance
                  priority: 7
                relevancy_score: 0.87
                source_last_updated_time: '2026-07-02T12:30:00Z'
                source_title: Project Phoenix Overview
                source_type: file
                source_upload_time: '2026-07-02T10:00:00Z'
                sub_tenant_id: sub_tenant_4567
            graph_context:
              chunk_id_to_group_ids:
                HydraEmbeddings123_0:
                  - grp_1234
              chunk_relations:
                - combined_context: >-
                    Acme Corp deploys HydraDB in production for context
                    retrieval.
                  group_id: grp_1234
                  relevancy_score: 0.87
                  source_chunk_ids:
                    - HydraEmbeddings123_0
                    - HydraEmbeddings123_1
                  triplets:
                    - relation:
                        confidence: 0.92
                        predicate: works_at
                      source:
                        entity_id: entity_1a2b
                        name: Ada
                        type: person
                      target:
                        entity_id: entity_3c4d
                        name: Acme Corp
                        type: organization
              query_paths:
                - combined_context: >-
                    Acme Corp deploys HydraDB in production for context
                    retrieval.
                  group_id: grp_1234
                  relevancy_score: 0.87
                  source_chunk_ids:
                    - HydraEmbeddings123_0
                    - HydraEmbeddings123_1
                  triplets:
                    - relation:
                        confidence: 0.92
                        predicate: works_at
                      source:
                        entity_id: entity_1a2b
                        name: Ada
                        type: person
                      target:
                        entity_id: entity_3c4d
                        name: Acme Corp
                        type: organization
              synthesis_context: 'Related entities: Acme Corp, HydraDB, production deployment.'
            sources:
              - additional_metadata:
                  author: ada
                  doc_version: 3
                app_external_id: C0123456789
                app_kind: slack
                app_provider: slack
                description: Internal overview of the Project Phoenix rollout.
                id: HydraDoc1234
                metadata:
                  department: finance
                  priority: 7
                sub_tenant_id: sub_tenant_4567
                timestamp: '2026-07-02T10:00:00Z'
                title: Project Phoenix Overview
                type: knowledge
                url: https://docs.hydradb.com/phoenix
        error:
          $ref: '#/components/schemas/handler.apiError'
          description: Error message, empty string on success.
          example:
            code: DATABASE_NOT_FOUND
            message: Database not found
        meta:
          $ref: '#/components/schemas/handler.responseMeta'
          example:
            collection: team_docs
            database: acme_corp
            latency_ms: 12.3
            request_id: 9d13aef4-02f4-4e73-8c62-4c2601d04f9d
            source_type: file
            sub_tenant_id: sub_tenant_4567
            tenant_id: tenant_1234
        success:
          description: Whether the request succeeded.
          example: true
          type: boolean
      type: object
    handler.ErrorResponse:
      properties:
        detail:
          $ref: '#/components/schemas/handler.ErrorDetail'
          description: Structured error detail with code, message, and deprecation hints.
          example:
            deprecated: true
            deprecated_field: tenant_id
            error_code: VALIDATION_ERROR
            message: Request validation failed
            preferred_field: database
            success: true
      type: object
    search.MetadataFilters:
      additionalProperties: {}
      description: >-
        Filters results by source metadata. Top-level keys target tenant
        metadata (for example department, priority, active, or tags). Nested
        additional_metadata keys target document metadata. Values are
        exact-match scalars or arrays for set-equality/list-style filters.
      example:
        active: true
        additional_metadata:
          author: ada
        department: finance
        priority: 7
        tags:
          - alpha
          - beta
      type: object
    search.RecallMode:
      enum:
        - fast
        - thinking
        - auto
      type: string
      x-enum-varnames:
        - RecallModeFast
        - RecallModeThinking
        - RecallModeAuto
    search.Operator:
      enum:
        - or
        - and
        - phrase
      type: string
      x-enum-varnames:
        - OperatorOr
        - OperatorAnd
        - OperatorPhrase
    search.QueryBy:
      enum:
        - hybrid
        - text
      type: string
      x-enum-varnames:
        - QueryByHybrid
        - QueryByText
    search.SourceType:
      description: >-
        Source is the wire field `type` (Python QueryRequest.source has
        alias="type").

        SourceLegacy accepts the pre-rename `source` key (Python
        populate_by_name=True

        keeps the field name valid on input); resolveSourceAlias folds it into
        Source.
      enum:
        - knowledge
        - memory
        - all
      type: string
      x-enum-varnames:
        - SourceKnowledge
        - SourceMemory
        - SourceAll
    search.V2RetrievalResult:
      properties:
        additional_context:
          additionalProperties:
            $ref: '#/components/schemas/search.V2Chunk'
          description: >-
            Map of chunk ID to chunk content for sources declared as related by
            the author (query_forceful_relations).
          example: The user is a senior engineer onboarding to the platform.
          type: object
        chunks:
          description: Retrieved and ranked chunks from the knowledge store or memories.
          example:
            - additional_metadata:
                author: ada
                doc_version: 3
              chunk_content: HydraDB supports hybrid retrieval across knowledge and memories.
              chunk_uuid: a1b2c3d4-e5f6-7890-1234-567890abcdef
              extra_context_ids:
                - HydraEmbeddings123_2
                - HydraEmbeddings123_3
              id: HydraDoc1234
              layout: text
              metadata:
                department: finance
                priority: 7
              relevancy_score: 0.87
              source_last_updated_time: '2026-07-02T12:30:00Z'
              source_title: Project Phoenix Overview
              source_type: file
              source_upload_time: '2026-07-02T10:00:00Z'
              sub_tenant_id: sub_tenant_4567
          items:
            $ref: '#/components/schemas/search.V2Chunk'
          type: array
          uniqueItems: false
        graph_context:
          $ref: '#/components/schemas/search.GraphContext'
          example:
            chunk_id_to_group_ids:
              HydraEmbeddings123_0:
                - grp_1234
            chunk_relations:
              - combined_context: Acme Corp deploys HydraDB in production for context retrieval.
                group_id: grp_1234
                relevancy_score: 0.87
                source_chunk_ids:
                  - HydraEmbeddings123_0
                  - HydraEmbeddings123_1
                triplets:
                  - relation:
                      confidence: 0.92
                      predicate: works_at
                    source:
                      entity_id: entity_1a2b
                      name: Ada
                      type: person
                    target:
                      entity_id: entity_3c4d
                      name: Acme Corp
                      type: organization
            query_paths:
              - combined_context: Acme Corp deploys HydraDB in production for context retrieval.
                group_id: grp_1234
                relevancy_score: 0.87
                source_chunk_ids:
                  - HydraEmbeddings123_0
                  - HydraEmbeddings123_1
                triplets:
                  - relation:
                      confidence: 0.92
                      predicate: works_at
                    source:
                      entity_id: entity_1a2b
                      name: Ada
                      type: person
                    target:
                      entity_id: entity_3c4d
                      name: Acme Corp
                      type: organization
            synthesis_context: 'Related entities: Acme Corp, HydraDB, production deployment.'
        sources:
          description: Deduplicated source-level metadata for all returned chunks.
          example:
            - additional_metadata:
                author: ada
                doc_version: 3
              app_external_id: C0123456789
              app_kind: slack
              app_provider: slack
              description: Internal overview of the Project Phoenix rollout.
              id: HydraDoc1234
              metadata:
                department: finance
                priority: 7
              sub_tenant_id: sub_tenant_4567
              timestamp: '2026-07-02T10:00:00Z'
              title: Project Phoenix Overview
              type: knowledge
              url: https://docs.hydradb.com/phoenix
          items:
            $ref: '#/components/schemas/search.SourceInfo'
          type: array
          uniqueItems: false
      type: object
    handler.apiError:
      properties:
        code:
          description: Machine-readable error code (e.g. `DATABASE_NOT_FOUND`).
          example: DATABASE_NOT_FOUND
          type: string
        message:
          description: Human-readable description of the error.
          example: Database not found
          type: string
      type: object
    handler.responseMeta:
      properties:
        collection:
          description: >-
            Collection scope. Defaults to the default collection when omitted.
            Formerly `sub_tenant_id`; the `sub_tenant_id` alias is still
            accepted (deprecated).
          example: team_docs
          type: string
        database:
          description: >-
            Owning database. Formerly `tenant_id`; the `tenant_id` alias is
            still accepted (deprecated).
          example: acme_corp
          type: string
        deprecation:
          description: >-
            Deprecation lists any migration nudges that apply to this request —
            the

            caller used a legacy /tenants route, a legacy
            tenant_id/sub_tenant_id field,

            or the deprecated sub_tenant_ids selector. It is a non-breaking
            signal (the

            status code is unchanged); omitempty keeps it absent for
            fully-migrated

            requests. A list so independent deprecations coexist without
            clobbering.
          items:
            $ref: '#/components/schemas/handler.deprecationNotice'
          type: array
          uniqueItems: false
        latency_ms:
          description: Server-side processing time in milliseconds.
          example: 12.3
          type: number
        request_id:
          description: Unique identifier for this request, useful for support and tracing.
          example: 9d13aef4-02f4-4e73-8c62-4c2601d04f9d
          type: string
        source_type:
          description: Type of the parent source (e.g. `file`, `slack`, `notion`).
          example: file
          type: string
        sub_tenant_id:
          deprecated: true
          example: sub_tenant_4567
          type: string
          x-deprecated: 'true'
        tenant_id:
          deprecated: true
          example: tenant_1234
          type: string
          x-deprecated: 'true'
      type: object
    handler.ErrorDetail:
      properties:
        deprecated:
          description: Whether this response concerns a deprecated field or route.
          example: true
          type: boolean
        deprecated_field:
          description: The deprecated field name.
          example: tenant_id
          type: string
        error_code:
          description: Machine-readable error classification code.
          example: VALIDATION_ERROR
          type: string
        message:
          description: Human-readable description of the error.
          example: Request validation failed
          type: string
        preferred_field:
          description: The canonical replacement for the deprecated field.
          example: database
          type: string
        success:
          description: Always false for error responses.
          example: true
          type: boolean
      type: object
    search.V2Chunk:
      properties:
        additional_metadata:
          additionalProperties: {}
          description: >-
            Pydantic aliases (see VectorStoreChunk):
            document_metadata→additional_metadata,

            tenant_metadata→metadata. FastAPI serializes by_alias, so the wire
            uses the aliases.
          example:
            author: ada
            doc_version: 3
          type: object
        chunk_content:
          description: Text content of this chunk.
          example: HydraDB supports hybrid retrieval across knowledge and memories.
          type: string
        chunk_uuid:
          description: Unique identifier for this individual chunk.
          example: a1b2c3d4-e5f6-7890-1234-567890abcdef
          type: string
        extra_context_ids:
          description: IDs of adjacent chunks pulled in as surrounding context.
          example:
            - HydraEmbeddings123_2
            - HydraEmbeddings123_3
          items:
            type: string
          type: array
          uniqueItems: false
        id:
          description: Unique identifier for this resource.
          example: HydraDoc1234
          type: string
        layout:
          description: >-
            Layout classification for this chunk (e.g. `text`, `table`,
            `image`).
          example: text
          type: string
        metadata:
          additionalProperties: {}
          description: Schema-backed tenant metadata attached to the source.
          example:
            department: finance
            priority: 7
          type: object
        relevancy_score:
          description: Relevance score for this item against the query.
          example: 0.87
          type: number
        source_last_updated_time:
          description: RFC3339 timestamp when the source was last modified.
          example: '2026-07-02T12:30:00Z'
          type: string
        source_title:
          description: Title of the parent source document.
          example: Project Phoenix Overview
          type: string
        source_type:
          description: Type of the parent source (e.g. `file`, `slack`, `notion`).
          example: file
          type: string
        source_upload_time:
          description: RFC3339 timestamp when the source was ingested.
          example: '2026-07-02T10:00:00Z'
          type: string
        sub_tenant_id:
          description: Collection this chunk belongs to.
          example: sub_tenant_4567
          type: string
      type: object
    search.GraphContext:
      description: |-
        GraphContext is omitted entirely when graph_context is disabled on the
        request (pointer + omitempty), so the response carries no graph slice
        instead of an empty-but-present object.
      properties:
        chunk_id_to_group_ids:
          additionalProperties:
            items:
              type: string
            type: array
          description: Mapping from chunk ID to the relation group IDs it participates in.
          example:
            HydraEmbeddings123_0:
              - grp_1234
          type: object
        chunk_relations:
          description: Scored relation paths relevant to the query, grouped by chunk.
          example:
            - combined_context: Acme Corp deploys HydraDB in production for context retrieval.
              group_id: grp_1234
              relevancy_score: 0.87
              source_chunk_ids:
                - HydraEmbeddings123_0
                - HydraEmbeddings123_1
              triplets:
                - relation:
                    confidence: 0.92
                    predicate: works_at
                  source:
                    entity_id: entity_1a2b
                    name: Ada
                    type: person
                  target:
                    entity_id: entity_3c4d
                    name: Acme Corp
                    type: organization
          items:
            $ref: '#/components/schemas/search.ScoredPathResponse'
          type: array
          uniqueItems: false
        query_paths:
          description: Scored relation paths ranked by relevance to the query.
          example:
            - combined_context: Acme Corp deploys HydraDB in production for context retrieval.
              group_id: grp_1234
              relevancy_score: 0.87
              source_chunk_ids:
                - HydraEmbeddings123_0
                - HydraEmbeddings123_1
              triplets:
                - relation:
                    confidence: 0.92
                    predicate: works_at
                  source:
                    entity_id: entity_1a2b
                    name: Ada
                    type: person
                  target:
                    entity_id: entity_3c4d
                    name: Acme Corp
                    type: organization
          items:
            $ref: '#/components/schemas/search.ScoredPathResponse'
          type: array
          uniqueItems: false
        synthesis_context:
          description: >-
            LLM-synthesized summary of the most relevant graph entities and
            relationships.
          example: 'Related entities: Acme Corp, HydraDB, production deployment.'
          type: string
      type: object
    search.SourceInfo:
      properties:
        additional_metadata:
          additionalProperties: {}
          description: Per-document free-form metadata.
          example:
            author: ada
            doc_version: 3
          type: object
        app_external_id:
          description: >-
            Provider-assigned identifier for this source (e.g. Slack channel
            ID).
          example: C0123456789
          type: string
        app_kind:
          description: >-
            App-source fields (populated when the source comes from an app
            integration).

            Default null on the wire when absent.
          example: slack
          type: string
        app_provider:
          description: Provider name for app-sourced items (e.g. `slack`, `github`).
          example: slack
          type: string
        description:
          description: Human-readable description of the source.
          example: Internal overview of the Project Phoenix rollout.
          type: string
        id:
          description: Unique identifier for this resource.
          example: HydraDoc1234
          type: string
        metadata:
          additionalProperties: {}
          description: >-
            Pydantic aliases (see VectorStoreChunk). Source metadata defaults to
            {} on

            the wire (Python default_factory=dict), unlike chunk metadata which
            is null.
          example:
            department: finance
            priority: 7
          type: object
        sub_tenant_id:
          description: Collection this source belongs to.
          example: sub_tenant_4567
          type: string
        timestamp:
          description: RFC3339 timestamp associated with this item.
          example: '2026-07-02T10:00:00Z'
          type: string
        title:
          description: Title or name of the source.
          example: Project Phoenix Overview
          type: string
        type:
          description: Source content category (e.g. `knowledge`, `memory`).
          example: knowledge
          type: string
        url:
          description: URL to the original source, if available.
          example: https://docs.hydradb.com/phoenix
          type: string
      type: object
    handler.deprecationNotice:
      properties:
        deprecated:
          description: Whether this response concerns a deprecated field or route.
          example: true
          type: boolean
        deprecated_field:
          description: The deprecated field name.
          example: tenant_id
          type: string
        deprecated_since:
          description: API version when the field was deprecated.
          example: 2.0.1
          type: string
        message:
          description: Migration guidance message.
          example: tenant_id is deprecated; use database instead.
          type: string
        preferred_field:
          description: The canonical replacement for the deprecated field.
          example: database
          type: string
      type: object
    search.ScoredPathResponse:
      properties:
        combined_context:
          description: Merged text from all chunk passages in this relation path.
          example: Acme Corp deploys HydraDB in production for context retrieval.
          type: string
        group_id:
          description: Unique identifier for this relation group.
          example: grp_1234
          type: string
        relevancy_score:
          description: Relevance score for this item against the query.
          example: 0.87
          type: number
        source_chunk_ids:
          description: IDs of the chunks that contribute to this relation path.
          example:
            - HydraEmbeddings123_0
            - HydraEmbeddings123_1
          items:
            type: string
          type: array
          uniqueItems: false
        triplets:
          description: Knowledge-graph triplets that make up this relation path.
          example:
            - relation:
                confidence: 0.92
                predicate: works_at
              source:
                entity_id: entity_1a2b
                name: Ada
                type: person
              target:
                entity_id: entity_3c4d
                name: Acme Corp
                type: organization
          items:
            $ref: '#/components/schemas/search.PathTriplet'
          type: array
          uniqueItems: false
      type: object
    search.PathTriplet:
      properties:
        relation:
          additionalProperties: {}
          description: Relation properties including predicate and confidence score.
          example:
            confidence: 0.92
            predicate: works_at
          type: object
        source:
          additionalProperties: {}
          description: Source entity of the relationship.
          example:
            entity_id: entity_1a2b
            name: Ada
            type: person
          type: object
        target:
          additionalProperties: {}
          description: Target entity of the relationship.
          example:
            entity_id: entity_3c4d
            name: Acme Corp
            type: organization
          type: object
      type: object
  securitySchemes:
    BearerAuth:
      bearerFormat: API key
      description: 'API key sent as a Bearer token: "Bearer prefix.secret"'
      scheme: bearer
      type: http

````