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

> How HydraDB retrieves the right context for each query — Knowledge, Memories, and the context graph, all behind a single /query endpoint.

Query turns stored context into the *right* context for a specific query. One endpoint  -  `POST /query`  -  queries [Knowledge](/essentials/v2/knowledge) (documents and app sources), [Memories](/essentials/v2/memories) (user preferences, conversation history, inferred content), or both. Three signals drive relevance: dense-vector similarity, BM25 keyword matching, and [context-graph](/essentials/v2/context-graphs) traversal. The parameters below control all of it.

For the full request and response schema, see [Query - API Reference](/api-reference/v2/endpoint/query-overview).

***

## 1. Use-case recipes

Pick the row that matches your goal and use the parameters as a starting point:

| I want to…              | `type`        | `query_by` | `mode`       | Notes                                                                                                                                                         |
| ----------------------- | ------------- | ---------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Document Q\&A / RAG     | `"knowledge"` | `"hybrid"` | `"thinking"` | Set `graph_context: true` for a richer context graph as part of the API response                                                                              |
| Exact keyword match     | `"knowledge"` | `"text"`   | -            | Optionally set `operator: "and"` or `"or"` to control BM25 term matching                                                                                      |
| Personalized response   | `"memory"`    | `"hybrid"` | `"thinking"` |                                                                                                                                                               |
| Personalized + grounded | `"all"`       | `"hybrid"` | `"thinking"` | One call merges both stores                                                                                                                                   |
| Query over apps         | `"knowledge"` | `"hybrid"` | `"thinking"` | Set `query_apps: true` to enable the app-aware retrieval lane (IDs, actors, thread & parent traversal) while still querying the full selected knowledge scope |

***

## 2. Parameter reference

[Follow this for when to use `database` and `collection`](./multi-tenant#2-when-to-use-each)

The `database` field was formerly `tenant_id` and `collection` was formerly `sub_tenant_id`; the old names remain accepted as deprecated aliases.

### Scope

| Parameter     | Type / values                                                             | Purpose                                                                                                                                                                                                                                               |
| ------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `collections` | `string[]` or `{ [collection]: positive number (max one decimal place) }` | Preferred query-time scope selector. Use a single-item list for one user/workspace, a longer list to fan out with equal normalized weights, or an object to provide relative ranking weights with at most one decimal place. Maximum 100 collections. |
| `collection`  | string                                                                    | Single-scope query selector; also used at ingest. Send one collection ID to scope the query to it.                                                                                                                                                    |

### Graph

| Parameter                  | Type / values | Purpose                                                                                                                                                                                                                                                                          |
| -------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `graph_context`            | boolean       | When `true` (default), includes the entity/relation graph slice in the response. Pair with `mode: "thinking"` for richer multi-hop traversals. See [Context Graphs](/essentials/v2/context-graphs). Set to `false` to drop it when you only need ranked chunks. Default: `true`. |
| `query_forceful_relations` | boolean       | Whether to fetch author-declared related sources (see [`relations` on ingest](/api-reference/v2/endpoint/ingest-context)) into `additional_context`. **Only takes effect in** `mode: "thinking"`**.** Default: `true`.                                                           |

### Shaping results

| Parameter            | Type / values     | Purpose                                                                                                                                                                                                                                                                                                                                                             |
| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_results`        | integer           | Maximum chunks to return. Default `10`; maximum `50`. Start with `10`, reduce for tight context windows, increase only when you rerank or summarize downstream.                                                                                                                                                                                                     |
| `recency_bias`       | float `0.0`–`1.0` | Boost for newer content. Default: `0.0` (no boost).                                                                                                                                                                                                                                                                                                                 |
| `query_apps`         | boolean           | Set `true` to enable the app-aware retrieval lane alongside normal retrieval (reconstructed threads, parent/child traversal, exact ID/actor lookups). This improves app-source query but does not restrict the query to only app sources; HydraDB still queries the full selected knowledge scope. See [App Sources](/essentials/v2/app-sources). Default: `false`. |
| `additional_context` | string            | Request-time hint to guide retrieval (e.g., "user is on the billing page"). This is different from the response `additional_context`, which carries forceful-relation results. Default: `null`.                                                                                                                                                                     |
| `metadata_filters`   | object            | Deterministic narrowing before ranking. See [Metadata](/essentials/v2/metadata). Default: `null`.                                                                                                                                                                                                                                                                   |

***

## 3. Tuning heuristics

Most of the time the defaults are right. When they aren't, here's where to start:

* `mode`  -  If omitted, defaults to `"auto"`: it scores the query before retrieval and routes to `"fast"` or `"thinking"` (defaulting to `"thinking"` when the signal is inconclusive), and overrides `graph_context` to match whichever it picks. Pick `"fast"` or `"thinking"` explicitly instead when you know your traffic shape and want a deterministic pipeline.
* `alpha`  -  Start at `0.8`. Lower toward `0.3–0.5` when the query contains literal tokens (error codes, SKUs, product names). Raise toward `0.9` for conceptual questions. Use `"auto"` when query shape varies across calls.
* `max_results`  -  Start at `10`. Drop to `5` for tight context windows; raise to `20` if you rerank downstream.
* `additional_context`  -  Use it when the query alone is ambiguous. Keep it short and factual.
* `graph_context`  -  Set to `true` when answers benefit from entity relationships (multi-hop questions, "how does X relate to Y"). Pair with `mode: "thinking"`  -  in `"fast"` mode the graph slice is shallow.
* `query_apps`  -  Set to `true` when querying ingested app data (Slack, Gmail, Confluence, Jira, Salesforce) to activate exact ID and actor lookups, same-thread expansion, and parent/child hierarchy traversal. This adds better app-aware retrieval on top of the normal knowledge query; it does not filter out non-app knowledge. Pair with `mode: "thinking"`.

***

## 4. Minimal working example

The canonical personalized-answer flow takes a single call: `POST /query` with `type: "all"` returns merged knowledge and per-user memory in one ranked result set.

### Setup

```bash theme={"dark"}
# Set your key as an environment variable - used in every request below
export HYDRA_DB_API_KEY="your_api_key"
# All requests: -H "Authorization: Bearer $HYDRA_DB_API_KEY" -H "API-Version: 2"
```

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

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

```python theme={"dark"}
import os
from hydra_db import HydraDB

client = HydraDB(token=os.environ["HYDRA_DB_API_KEY"])
```

### One call  -  Knowledge and Memories together

```bash 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",
    "collection": "user_john_123",
    "query": "How do I reset my password?",
    "type": "all",
    "query_by": "hybrid",
    "mode": "thinking",
    "max_results": 8,
    "graph_context": true
  }'
```

```typescript theme={"dark"}
const result = await client.query({
  database: "acme_corp",
  collection: "user_john_123",
  query: "How do I reset my password?",
  type: "all",
  queryBy: "hybrid",
  mode: "thinking",
  maxResults: 8,
  graphContext: true,
});
```

```python theme={"dark"}
result = client.query(
    database="acme_corp",
    collection="user_john_123",
    query="How do I reset my password?",
    type="all",
    query_by="hybrid",
    mode="thinking",
    max_results=8,
    graph_context=True,
)
```

### Merge into the LLM prompt

The response is a single `RetrievalResult` containing `chunks[]`, `sources[]`, and  -  when applicable  -  `graph_context` and `additional_context`. Chunks from Knowledge and Memories are already interleaved and ranked by relevance, so no manual merging is required. Pass the result through the helper in [How to Use API Results](/essentials/v2/api-results) to turn it into a context string for your prompt:

```typescript theme={"dark"}
const context = buildContextString(result);

const completion = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [
    {
      role: "system",
      content: "Answer using only the provided context. Match the user's preferred style.",
    },
    {
      role: "user",
      content: `${context}\n\nQuestion: How do I reset my password?`,
    },
  ],
});
```

If you need to query several users, teams, or workspaces at once, pass `collections`. A list gives every scope equal normalized weight; an object applies relative ranking weights with at most one decimal place before the final merged ranking. When `max_results` is set, it caps the final merged response across all selected collections:

```json theme={"dark"}
{
  "database": "acme_corp",
  "collections": {
    "workspace_42": 2,
    "user_john_123": 1
  },
  "query": "What context matters for this renewal?",
  "type": "all"
}
```

If you need to keep Knowledge and Memories formatted differently in the prompt, call `/query` twice in parallel with `type: "knowledge"` and `type: "memory"`, then merge client-side.

### Production checklist

* **Default to** `type: "all"` for personalized answers  -  one call instead of two, scoped with `collections`.
* **Set per-call timeouts.** Generous for `thinking` (3–5 s), tight for `fast` (≤500 ms). For `mode: "auto"`, size the timeout for the `thinking` case  -  it can resolve to either pipeline and defaults toward `thinking` when the routing signal is inconclusive.
* **Enable `query_apps: true`** when querying app sources to activate app-aware retrieval and thread/relation traversal.
* **Pass** `additional_context` with known session state (page, feature, role). It sharpens retrieval without extra calls.

***

## 5. Common mistakes

| Symptom                                                                      | Cause                                                                                                                                  | Fix                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Empty `query_paths` / `chunk_relations`                                      | `graph_context` not set, or no relations exist for the result set                                                                      | Set `graph_context: true`. Empty arrays are normal when there's nothing to return  -  see [Context Graphs](/essentials/v2/context-graphs).                                                                           |
| Recent uploads don't appear in results                                       | Indexing not finished                                                                                                                  | Poll `GET /context/status?ids=...&database=...`  -  chunks are invisible until processing reaches at least `graph_creation`.                                                                                         |
| `metadata_filters` doesn't narrow results                                    | Filter key is in the wrong namespace, the value doesn't match exactly, or the hot top-level field was not declared with `enable_match` | Top-level keys match `metadata`; free-form per-document fields must be nested under `additional_metadata`. Declare hot filter keys in `database_metadata_schema` with `enable_match: true` before production ingest. |
| Memories missing from a `type: "knowledge"` query                            | Wrong store selected                                                                                                                   | Use `type: "memory"` or `type: "all"`.                                                                                                                                                                               |
| Recency doesn't seem to matter                                               | `recency_bias` defaults to `0`                                                                                                         | Set it explicitly between `0.1` and `1.0`.                                                                                                                                                                           |
| `operator: "phrase"` ignored                                                 | `query_by` not set to `"text"`                                                                                                         | `operator` only applies to BM25 text query  -  switch `query_by` to `"text"`.                                                                                                                                        |
| `query_forceful_relations` ignored                                           | Request uses `mode: "fast"`                                                                                                            | Forceful-relation context is fetched only in `mode: "thinking"`.                                                                                                                                                     |
| `graph_context` value ignored                                                | Request uses `mode: "auto"` (or `mode` was omitted)                                                                                    | `auto` overrides `graph_context` to match whichever pipeline it routes to; set `graph_context` explicitly only under `mode: "fast"` or `"thinking"`.                                                                 |
| Expected a deterministic `fast`/`thinking` pipeline, got auto-routed instead | `mode` was omitted                                                                                                                     | Omitting `mode` now defaults to `"auto"`  -  set `mode` explicitly to `"fast"` or `"thinking"` if you don't want automatic routing.                                                                                  |

***

## 6. Advanced patterns

**Hybrid + text in two parallel calls.** When a query mixes a literal token (error code, SKU, function name) with natural-language intent, run `query_by: "hybrid"` and `query_by: "text"` in parallel, dedupe by chunk ID, and treat text hits as a "must include" floor.

**Recall-then-rerank.** Ask for more chunks than you actually need (`max_results: 20`) and apply your own reranker  -  recency windows, compliance filters, business rules  -  before picking the final top-k for the prompt.

**Cache the prompt context.** If the same query repeats inside a session, cache the `RetrievalResult` keyed by `(database, collection, query, type, query_by)`. Recall is fast, but skipping it entirely is faster.

***

## Related

* [Knowledge](/essentials/v2/knowledge)  -  shared document context
* [Memories](/essentials/v2/memories)  -  user-scoped dynamic context
* [Metadata](/essentials/v2/metadata)  -  designing filterable fields
* [Context Graphs](/essentials/v2/context-graphs)  -  how graph traversal enriches recall
* [How to Use API Results](/essentials/v2/api-results)  -  turning `RetrievalResult` into an LLM prompt
* [Query - API Reference](/api-reference/v2/endpoint/query)  -  full parameter and response schema
