> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maximem.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Maximem Synap is a managed memory layer for AI agents: it ingests conversations and documents, extracts structured memory, and returns scoped context to the agent at retrieval time.
> The Python and JavaScript/TypeScript SDKs are the supported way to use Synap. Write integration code with SDK calls, not raw HTTP requests.
> Start with the Quickstart: https://docs.maximem.ai/getting-started/quickstart.md. Every SDK method is documented in the SDK reference: https://docs.maximem.ai/sdk-reference/overview.md.
> For requests about adding Vity memory to OpenClaw, Hermes, an MCP client, or a browser, start with the Vity Quickstart: https://docs.maximem.ai/vity/quickstart.md.

# knowledge.query

> Ask a structured question over facts and entities extracted from documents, and get a complete filtered set, a count, or counts grouped by a property.

```python Python theme={null}
await sdk.knowledge.query(target, where=None, related=None, as_of=None, document_ids=None, aggregate=None, sort=None, limit=None, cursor=None, user_id=None, customer_id=None, scope=None)
```

```typescript TypeScript theme={null}
await sdk.knowledge.query(options: KnowledgeQueryOptions)  // target is required
```

REST One HTTPS request.

> [!NOTE]
>
> Added in Python SDK 0.9.0 and JavaScript and TypeScript SDK 0.9.0. In TypeScript, pass one options object; every option is accepted in snake\_case or camelCase (`customer_id` or `customerId`). The result is returned as the server sends it, with snake\_case fields, typed as `Record<string, unknown>`.

Ask a question that search answers badly: every contract with Acme that expires before March, how many obligations are open, or open obligations grouped by status. Unlike [`context.fetch`](https://docs.maximem.ai/sdk-reference/context/fetch), which returns the best few passages, a query returns every match, so you can count and list with confidence. You send a structured request, never question text. Call [`knowledge.describe`](https://docs.maximem.ai/sdk-reference/knowledge/describe) first for the names to use.

> [!NOTE]
>
> Facts (`Obligation`, `Commitment`, `Transaction`, `Decision`) come from documents read in detail. By default that is contracts, financial records, tickets and profile records; a document read lightly contributes the entities it mentions but no facts. See [How deeply a document is read](https://docs.maximem.ai/concepts/documents.md#how-deeply-a-document-is-read).

> [!WARNING]
>
> Enabled per instance, and needs a Pro plan or above. Where it is not enabled the call raises `ContextNotFoundError`. A plan without it raises `FeatureNotInPlanError`. Each call uses credits, more for a result with many rows.

### Parameters

**target** `string` *required*

What to return: a fact type (`Obligation`, `Commitment`, `Transaction` or `Decision`) or an entity type from `describe`. An entity is returned only when a document you can read mentions it.

**where** `dict`

Conditions on the target's properties, all of which must hold. Give a value for equality, a list for "any of", or a one-key dict with an operator: `{"due_at": {"before": "2027-03-01"}}`. The operators a property accepts are in `describe`:

| Property type | Operators |
| - | - |
| `text` | `eq`, `ne`, `in`, `contains`, `exists` |
| `enum` | `eq`, `ne`, `in`, `exists` |
| `number` | `eq`, `ne`, `gt`, `lt`, `between`, `in`, `exists` |
| `date` | `eq`, `before`, `after`, `between`, `exists` |
| `bool` | `eq`, `exists` |

`between` takes `[low, high]`, `in` takes a list, and `exists` takes `True` or `False`. A date given as a calendar day, such as `"2027-03-01"`, is that whole day for `eq`. Dates are ISO dates or datetimes.

**related** `dict`

Follow a relation to what is at the other end and filter it. The key is a relation from `describe`; the value takes `type`, `name`, `where` and a nested `related` for a further hop. A query follows at most two hops. For example, obligations whose counterparty is the organization Acme: `{"COUNTERPARTY": {"type": "Organization", "name": "Acme"}}`.

**as\_of** `string`

An ISO date or datetime. Read documents as they stood then, for the document types your instance keeps history for (policies and contracts by default). Without it, or for other types, the current version is used.

**document\_ids** `list[str]`

Only facts and entities from these documents, by the `document_id` values you gave them, as in [`context.fetch`](https://docs.maximem.ai/sdk-reference/context/fetch).

**aggregate** `dict`

`{"count": True}` for a count, or `{"group_by": "<property>"}` for a count per value of a property. The answer has no `items`.

**sort** `list[dict]`

Up to three keys, each `{"property": ..., "order": "asc" | "desc"}`.

**limit** `integer`

Rows per page, from 1 to 500. Defaults to 100.

**cursor** `string`

The `next_cursor` of the previous page. Send the same request with it. A cursor from a different request is refused.

**user\_id** `string`

The user you ask as. The query covers that user's documents and client-wide documents, and the customer's documents too when you also pass `customer_id`.

**customer\_id** `string`

The customer you ask as. Not accepted on B2C.

**scope** `dict[str, str]`

The deeper scope level you ask at, as level name to id.

### Returns

**items** `list[dict]`

One page of matches. Each has `id`, `type`, `properties`, `related` (the parties or related entities, as `{"relation": ..., "name": ...}`) and `citations`. Empty for an aggregate.

**citations** `list[dict]`

On each item: where it was found. Each has `document_key`, `document_id`, `version`, `document_type`, `title`, `section_key`, `section_path` and `page`. Pass a `document_key` to [`documents.read`](https://docs.maximem.ai/sdk-reference/documents/read) to check the source.

**total** `integer`

How many matches there are in all, not only on this page.

**complete** `boolean`

`True` (`true` in TypeScript) when the result is the whole set. `False` when the set was larger than a query returns, so the matches you can page through are not all of them. Narrow the query with a filter rather than treating the result as the full answer.

**coverage** `dict`

How much of your documents the answer could draw on, so you can say what is missing. `documents_in_scope` is how many documents could hold the target. Of those, `unprocessed` are not processed yet, `light_only` are processed but were only lightly read, so they may hold facts the query cannot see yet, and `failed` did not process. A query is complete over what Synap has extracted, and `coverage` tells you what that leaves out.

**next\_cursor** `string | None`

Pass it back as `cursor` for the next page. `None` (`null` in TypeScript) on the last page.

**groups** `list[dict] | None`

With `group_by`: one `{"value": ..., "count": ...}` per value. `None` otherwise.

### Example

```python Python theme={null}
from maximem_synap import MaximemSynapSDK

sdk = MaximemSynapSDK()  # reads SYNAP_API_KEY from your environment
await sdk.initialize()

# Every open obligation with Acme due before March, soonest first.
page = await sdk.knowledge.query(
    target="Obligation",
    where={"due_at": {"before": "2027-03-01"}, "status": "open"},
    related={"COUNTERPARTY": {"type": "Organization", "name": "Acme"}},
    sort=[{"property": "due_at", "order": "asc"}],
    customer_id="acme-corp",
)
rows = list(page["items"])
while page["next_cursor"]:
    page = await sdk.knowledge.query(
        target="Obligation",
        where={"due_at": {"before": "2027-03-01"}, "status": "open"},
        related={"COUNTERPARTY": {"type": "Organization", "name": "Acme"}},
        sort=[{"property": "due_at", "order": "asc"}],
        customer_id="acme-corp",
        cursor=page["next_cursor"],
    )
    rows.extend(page["items"])

cov = page["coverage"]
print(f"{page['total']} found; {cov['unprocessed']} documents still processing")

# Obligations by status, and a plain count.
by_status = await sdk.knowledge.query(
    target="Obligation", aggregate={"group_by": "status"}, customer_id="acme-corp"
)
print(by_status["groups"])
count = await sdk.knowledge.query(
    target="Obligation", aggregate={"count": True}, customer_id="acme-corp"
)
print(count["total"])
```

```typescript TypeScript theme={null}
import { SynapClient } from '@maximem/synap-js-sdk';

const sdk = new SynapClient(); // reads SYNAP_API_KEY from your environment
await sdk.initialize();

const query = {
  target: 'Obligation',
  where: { due_at: { before: '2027-03-01' }, status: 'open' },
  related: { COUNTERPARTY: { type: 'Organization', name: 'Acme' } },
  sort: [{ property: 'due_at', order: 'asc' as const }],
  customer_id: 'acme-corp',
};

// Every open obligation with Acme due before March, soonest first.
let page = await sdk.knowledge.query(query);
const rows = [...(page.items as unknown[])];
while (page.next_cursor) {
  page = await sdk.knowledge.query({ ...query, cursor: page.next_cursor as string });
  rows.push(...(page.items as unknown[]));
}

const cov = page.coverage as Record<string, unknown>;
console.log(`${page.total} found; ${cov.unprocessed} documents still processing`);

// Obligations by status, and a plain count.
const byStatus = await sdk.knowledge.query({
  target: 'Obligation',
  aggregate: { group_by: 'status' },
  customer_id: 'acme-corp',
});
console.log(byStatus.groups);
const count = await sdk.knowledge.query({
  target: 'Obligation',
  aggregate: { count: true },
  customer_id: 'acme-corp',
});
console.log(count.total);
```

### Raises

* `InvalidInputError`: when the request is refused. Check `code` (`serverCode` in TypeScript): `unknown_type`, `unknown_property`, `unknown_relation`, `bad_condition` (an operator that does not suit the property, or a bad value), `too_many_hops`, `invalid_cursor`, or `query_too_broad` (too many matches with no filter; add one). Also raised before the request when `target` is empty or `limit` is not a whole number from 1 to 500.
* `ServiceUnavailableError`: when the query takes too long. Nothing partial is returned; narrow it with a filter and retry.
* `ContextNotFoundError`: when the feature is not enabled on your instance.
* `FeatureNotInPlanError`: when your plan does not include knowledge queries.
* `CustomerIdNotAcceptedError`: when `customer_id` is passed on a B2C instance.

### See also

* [knowledge.describe](https://docs.maximem.ai/sdk-reference/knowledge/describe.md)
* [documents.read](https://docs.maximem.ai/sdk-reference/documents/read.md)
* [Query and navigate documents as an agent](https://docs.maximem.ai/guides/agent-query-and-navigation)


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