# Filter and Paginate Results

Source: https://docs.formance.com/v4.0/modules/ledger/querying/filters-and-pagination

Stack: v4.0

Apply filters on the server when an application needs a subset of accounts, transactions, logs, or audit entries. Each filter is validated against its target, so a valid transaction field can still be rejected by an account query.

The HTTP examples use the `LEDGER_URL`, `LEDGER_NAME`, and `CURL_AUTH` variables defined in [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data). They also use `jq` for executable pagination checks. The token needs the read scope for the selected target; see [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

## Choose a filter representation

Every filtered list route takes one `filter` query parameter:

| Route                               | Filter target                                        |
| ----------------------------------- | ---------------------------------------------------- |
| `GET /v3/{ledgerName}/accounts`     | Accounts                                             |
| `GET /v3/{ledgerName}/volumes`      | Accounts: the aggregate covers the matching accounts |
| `GET /v3/{ledgerName}/transactions` | Transactions                                         |
| `GET /v3/{ledgerName}/logs`         | Logs                                                 |
| `GET /v3/_/audit-entries`           | Audit, textual form only                             |

The value is either a textual expression or a structured JSON expression tree. The ledger reads the first non-whitespace character to tell them apart: `{` starts a structured filter, anything else is parsed as text. Both forms compile to the same filter, so a matching pair returns the same rows. URL-encode the complete `filter` value in both cases.

Use the textual form for commands and filters that people review:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter=metadata[status] == "active" and address ^= "users:"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

Use the structured form when an application already builds a JSON expression tree:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'filter={"$and":[{"$match":{"metadata[status]":"active"}},{"$match":{"address":"users:"}}]}' \
  "$LEDGER_URL/v3/$LEDGER_NAME/accounts"
```

These two specific examples select active accounts whose addresses start with `users:`. In structured JSON, a trailing colon in an address value marks a prefix match.

Do not translate filters mechanically between the two formats. A structured transaction `reference` condition is an exact match, not a prefix or substring one. The main representation differences are:

| Capability                                                                | Textual form                            | Structured JSON                                               |
| ------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------- |
| Audit fields                                                              | Supported                               | Not supported                                                 |
| Transaction `reference`, `reverted`, `id`, `insertedAt`, and `revertedAt` | Not supported                           | Supported                                                     |
| Log `logId`                                                               | Not supported                           | Supported                                                     |
| `in`                                                                      | Supported                               | Not supported; `$in` is rejected                              |
| Address prefix                                                            | Explicit `^=` operator, any byte prefix | An address value ending in `:`; `"users:c"` is an exact match |
| Numeric metadata equality                                                 | `== 10`                                 | Combine `$gte: 10` and `$lte: 10`                             |

## Build expressions

| Intent                    | Textual form                           | Structured form                                                              |
| ------------------------- | -------------------------------------- | ---------------------------------------------------------------------------- |
| Equal                     | `metadata[status] == "active"`         | `{"$match":{"metadata[status]":"active"}}`                                   |
| Not equal                 | `metadata[status] != "blocked"`        | `{"$not":{"$match":{"metadata[status]":"blocked"}}}`                         |
| One of several values     | `metadata[tier] in ("gold", "silver")` | `$or` of `$match` conditions                                                 |
| Prefix                    | `address ^= "users:"`                  | `{"$match":{"address":"users:"}}`                                            |
| Greater than or equal     | `metadata[score] >= 10`                | `{"$gte":{"metadata[score]":10}}`                                            |
| Closed range              | `metadata[score] between 10 and 20`    | `{"$and":[{"$gte":{"metadata[score]":10}},{"$lte":{"metadata[score]":20}}]}` |
| Metadata exists           | `metadata[customerId] exists`          | `{"$exists":{"metadata":"customerId"}}`                                      |
| Account has held an asset | `has asset USD/2`                      | `{"$exists":{"asset":"USD/2"}}`                                              |
| All conditions            | `a and b`                              | `{"$and":[a,b]}`                                                             |
| Any condition             | `a or b`                               | `{"$or":[a,b]}`                                                              |
| Negation                  | `not a`                                | `{"$not":a}`                                                                 |

An `$and` or `$or` array must contain at least one expression. Each structured node must contain exactly one `$` operator. The structured form also has `$gt` and `$lt` for exclusive bounds.

In the textual form, a bare key or value must start with a letter or `_` and contain only letters, digits, and `_`. Quote anything else, such as a value with a space, `-`, `:`, `.`, or `/`, or one that starts with a digit: `metadata["x-request-id"]`, `address == "users:alice"`, or `metadata[method] == "2fa"`.

The textual form reads a value that looks like an integer or `true`/`false` as that type, even when quoted: `metadata[code] == "15"` is an integer condition. On a key declared as `string`, it fails with `FILTER_COMPILATION_ERROR`. To match such a string, use the structured form: `{"$match":{"metadata[code]":"15"}}`. A negated condition, `!=` included, also matches rows that do not carry the key at all: `metadata[status] != "blocked"` returns accounts with no `status` metadata.

### Combine conditions

The textual operators bind in the order `not`, then `and`, then `or`. Use parentheses whenever a filter mixes `and` and `or`. The following filters differ only in their parentheses:

```text
(metadata[tier] == "gold" or metadata[tier] == "silver") and not metadata[status] == "blocked"
metadata[tier] == "gold" or metadata[tier] == "silver" and not metadata[status] == "blocked"
```

The first returns gold and silver accounts that are not blocked. The second reads as `gold or (silver and not blocked)`, so it also returns blocked gold accounts. The structured form has no precedence: the nesting of `$and`, `$or`, and `$not` is the grouping.

The examples below use one set of identifiers: accounts under `users:` carry `status` and `tier` metadata, and transactions carry `channel` and `region` metadata. Each pair returns the same rows.

#### Both of two metadata conditions

Card transactions recorded in the EU:

Textual

```text
metadata[channel] == "card" and metadata[region] == "eu"
```

Structured JSON

```json
{"$and":[{"$match":{"metadata[channel]":"card"}},{"$match":{"metadata[region]":"eu"}}]}
```

#### Either of two metadata conditions

Transactions paid by SEPA transfer, or recorded in the US:

Textual

```text
metadata[channel] == "sepa" or metadata[region] == "us"
```

Structured JSON

```json
{"$or":[{"$match":{"metadata[channel]":"sepa"}},{"$match":{"metadata[region]":"us"}}]}
```

#### Accounts under a prefix with a metadata condition

Gold-tier accounts under `users:`:

Textual

```text
address ^= "users:" and metadata[tier] == "gold"
```

Structured JSON

```json
{"$and":[{"$match":{"address":"users:"}},{"$match":{"metadata[tier]":"gold"}}]}
```

URL-encoded on the accounts route, the two forms are:

```text
GET /v3/{ledgerName}/accounts?filter=address%20%5E%3D%20%22users%3A%22%20and%20metadata%5Btier%5D%20%3D%3D%20%22gold%22
GET /v3/{ledgerName}/accounts?filter=%7B%22%24and%22%3A%5B%7B%22%24match%22%3A%7B%22address%22%3A%22users%3A%22%7D%7D%2C%7B%22%24match%22%3A%7B%22metadata%5Btier%5D%22%3A%22gold%22%7D%7D%5D%7D
```

`curl --get --data-urlencode` produces this encoding for you.

#### Either of two conditions, excluding a third

Gold or silver accounts that are not blocked:

Textual

```text
(metadata[tier] == "gold" or metadata[tier] == "silver") and not metadata[status] == "blocked"
```

Structured JSON

```json
{"$and":[{"$or":[{"$match":{"metadata[tier]":"gold"}},{"$match":{"metadata[tier]":"silver"}}]},{"$not":{"$match":{"metadata[status]":"blocked"}}}]}
```

#### Transactions in a date range, by metadata

Card transactions with an effective date in March 2026. Date bounds accept RFC 3339 timestamps. Use an exclusive upper bound at the start of the next month so that timestamps with fractional seconds late on March 31 are included:

Textual

```text
timestamp >= "2026-03-01T00:00:00Z" and timestamp < "2026-04-01T00:00:00Z" and metadata[channel] == "card"
```

Structured JSON

```json
{"$and":[{"$gte":{"timestamp":"2026-03-01T00:00:00Z"}},{"$lt":{"timestamp":"2026-04-01T00:00:00Z"}},{"$match":{"metadata[channel]":"card"}}]}
```

#### Source and destination

Transactions funded from `world` that credit an account under `users:`:

Textual

```text
source == "world" and destination ^= "users:"
```

Structured JSON

```json
{"$and":[{"$match":{"source":"world"}},{"$match":{"destination":"users:"}}]}
```

Posting conditions match across the whole transaction, not within one posting. A transaction with the postings `world` → `orders:42:pending` and `orders:42:pending` → `users:alice` matches `source == "world" and destination == "users:alice"`, although no single posting satisfies both. Use `address` to match an account in either role.

### Combine a filter with other parameters

The transactions and logs routes also accept `startDate` and `endDate`, which take RFC 3339 timestamps. The ledger always combines those parameters with `filter` using AND:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'startDate=2026-04-01T00:00:00Z' \
  --data-urlencode 'filter=metadata[channel] == "card"' \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

This returns card transactions dated on or after 1 April 2026. A separate parameter can only narrow the result. To express "this date range or that metadata value", put both conditions in one `filter` with `or`. The same applies to `not`: it only exists inside a filter expression.

## Match the filter to its target

| Target               | Common fields                                                                                                        | Index requirement                                           |
| -------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| Accounts and volumes | `address`                                                                                                            | No opt-in index for address matching                        |
| Accounts and volumes | `metadata[key]`                                                                                                      | Declared metadata type and ready metadata index             |
| Accounts and volumes | `has asset BASE/PRECISION`                                                                                           | Ready account-asset index                                   |
| Transactions         | `id`, `reverted`                                                                                                     | No opt-in index                                             |
| Transactions         | `reference`                                                                                                          | Structured `$match` exact match and a ready reference index |
| Transactions         | `timestamp`, `insertedAt`, `revertedAt`                                                                              | Matching date index                                         |
| Transactions         | `address`, `source`, `destination`                                                                                   | Matching transaction-address index                          |
| Transactions         | `metadata[key]`                                                                                                      | Declared metadata type and ready metadata index             |
| Logs                 | `logId`, `ledger`                                                                                                    | No opt-in index                                             |
| Logs                 | `date`                                                                                                               | Ready log-date index                                        |
| Audit                | `seq`, `proposal_id`, `log_seq`, `timestamp`, `outcome`, `ledger`, `caller_subject`, `order_type`, `idempotency_key` | Audit indexes maintained by Ledger                          |

Built-in transaction, log, and audit date fields accept RFC 3339 timestamps or Unix microseconds. Dates before `1970-01-01T00:00:00Z` are rejected because those built-in indexes use an unsigned representation. A metadata key declared as `datetime` uses signed Unix microseconds in filter bounds, including dates before the epoch.

Numeric built-in fields such as transaction `id` and the date fields are range-only in structured JSON. Use `$gt`, `$gte`, `$lt`, or `$lte` rather than `$match`. Send unsigned 64-bit values as decimal strings when they can exceed JavaScript's safe integer range.

Audit conditions support `and` and `or` but not `not`, and use bare field names such as `outcome` and `ledger` rather than an `audit[...]` prefix. The string fields `outcome`, `ledger`, `caller_subject`, `order_type`, and `idempotency_key` accept `==` and `in`, and `idempotency_key` also accepts `^=`. The numeric and date fields `seq`, `proposal_id`, `log_seq`, and `timestamp` accept `==`, `>`, `>=`, `<`, `<=`, and `between`, but not `in`.

The account asset condition means that the account has held the asset cell at least once. It does not assert that the current balance is non-zero.

Each condition that needs an index names a specific one. Create it with `POST /v3/{ledgerName}/indexes` and the canonical ID below. A metadata index also needs the key's type declared first with `PUT /v3/{ledgerName}/metadata-schema/{targetType}/{key}`:

| Condition                                          | Index ID                                                                         |
| -------------------------------------------------- | -------------------------------------------------------------------------------- |
| Account or transaction `metadata[key]`             | `metadata:TARGET_TYPE_ACCOUNT:<key>` or `metadata:TARGET_TYPE_TRANSACTION:<key>` |
| `has asset`                                        | `account_builtin:ACCT_BUILTIN_INDEX_ASSET`                                       |
| Transaction `reference`                            | `tx_builtin:TX_BUILTIN_INDEX_REFERENCE`                                          |
| Transaction `timestamp`, and `startDate`/`endDate` | `tx_builtin:TX_BUILTIN_INDEX_TIMESTAMP`                                          |
| Transaction `insertedAt`                           | `tx_builtin:TX_BUILTIN_INDEX_INSERTED_AT`                                        |
| Transaction `revertedAt`                           | `tx_builtin:TX_BUILTIN_INDEX_REVERTED_AT`                                        |
| Transaction `address`                              | `tx_builtin:TX_BUILTIN_INDEX_ADDRESS`                                            |
| Transaction `source`                               | `tx_builtin:TX_BUILTIN_INDEX_SOURCE_ADDRESS`                                     |
| Transaction `destination`                          | `tx_builtin:TX_BUILTIN_INDEX_DESTINATION_ADDRESS`                                |
| Log `date`                                         | `log_builtin:LOG_BUILTIN_INDEX_DATE`                                             |

Without the index, the ledger rejects the query instead of scanning:

```json
{"errorCode":"INDEX_NOT_FOUND","errorMessage":"index not found: index=\"metadata[\\\"status\\\"] on accounts\""}
```

The response status is `400`. Create only the indexes required by known queries, then wait for them to become available on every serving replica. See [Create and Manage Indexes](https://docs.formance.com/v4.0/modules/ledger/querying/indexes).

To translate filters written for an earlier ledger version, see [Translate filters](https://docs.formance.com/v4.0/modules/ledger/migration/update-clients#translate-filters).

## Paginate HTTP reads

These HTTP list routes take `pageSize`, `cursor`, and `reverse`, and page through their rows in a fixed order:

| Route                | Ordered by            | Default order | `reverse=true`       |
| -------------------- | --------------------- | ------------- | -------------------- |
| Ledgers (`GET /v3/`) | Ledger name           | Ascending     | Descending           |
| Accounts             | Account address       | Alphabetical  | Reverse alphabetical |
| Transactions         | Transaction ID        | Newest first  | Oldest first         |
| Ledger logs          | Ledger-local log ID   | Oldest first  | Newest first         |
| Numscripts           | Numscript name        | Ascending     | Descending           |
| Audit entries        | Global audit sequence | Oldest first  | Newest first         |
| Signing keys         | Key ID                | Ascending     | Descending           |

The other list routes, such as prepared queries, account types, Numscript versions, event sinks, and indexes, do not take these parameters.

When `pageSize` is omitted or set to `0`, the server uses 100 rows. The maximum is 1,000 rows per request: a larger value is clamped to 1,000, not rejected. This applies to ledgers, numscripts, and signing keys too: a client that expects every row in one response must follow the page tokens.

Each response carries the page and the tokens of its neighbors. Summarized with `jq '{rows: (.data | length), next, previous, hasMore}'`, a page from the middle of a newest-first transaction walk reads:

```json
{
  "rows": 100,
  "next": "eyJrZXkiOiIyMSJ9",
  "previous": "eyJrZXkiOiIxMjAiLCJiYWNrIjp0cnVlfQ",
  "hasMore": true
}
```

| Field      | Meaning                                                            |
| ---------- | ------------------------------------------------------------------ |
| `data`     | The rows of this page, in the requested order                      |
| `next`     | Token of the following page; omitted when no row follows this page |
| `previous` | Token of the preceding page; omitted on the first page             |
| `hasMore`  | `true` exactly when `next` is present                              |

To move to an adjacent page, send its token unchanged as the `cursor` query parameter. Rows come back in the requested order whichever way you move:

```bash
: "${NEXT_CURSOR:?set this to the next token from the preceding page}"

curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'pageSize=100' \
  --data-urlencode "cursor=$NEXT_CURSOR" \
  "$LEDGER_URL/v3/$LEDGER_NAME/transactions"
```

The composed setup does not set `-u`, so without that guard an unset `NEXT_CURSOR` sends `cursor=` and silently returns the first page instead of resuming.

The following loop performs a complete oldest-first traversal of transactions involving an account below `users:`. It keeps the filter and order unchanged and stops when a page has no `next` token. Create the transaction-address index before using this filter.

```bash
FILTER='address ^= "users:"'
REVERSE=true
PAGE_SIZE=100
CURSOR=""

while true; do
  curl_args=(
    curl --fail-with-body --silent --show-error --get
    "${CURL_AUTH[@]}"
    --data-urlencode "filter=$FILTER"
    --data-urlencode "reverse=$REVERSE"
    --data-urlencode "pageSize=$PAGE_SIZE"
  )

  if [ -n "$CURSOR" ]; then
    curl_args+=(--data-urlencode "cursor=$CURSOR")
  fi

  curl_args+=("$LEDGER_URL/v3/$LEDGER_NAME/transactions")
  PAGE="$("${curl_args[@]}")"

  jq -c '.data[]' <<<"$PAGE"
  CURSOR="$(jq -r '.next // empty' <<<"$PAGE")"

  if [ -z "$CURSOR" ]; then
    break
  fi
done
```

End the traversal on `hasMore` or a missing `next`, not on a short page. To walk backward, send `previous` instead; the first page has no `previous`.

A token is relative to the requested order and filter. Send the same `filter` and `reverse` on every page of a walk. A token also names a position on one route only: a transaction token does not resume an account list, and a ledger-local log position does not resume the bucket-wide audit trail. The server does not detect a token from another route. A token with a decimal key, such as a log token, decodes on every decimal-keyed route and resumes the transaction list or the audit trail at a meaningless position. The routes keyed by name or address (ledgers, accounts, Numscripts, and signing keys) accept any key. Only a malformed token, or a key of the wrong type, such as an account address sent to the transaction list, is rejected with `400` and `INVALID_REQUEST`.

Clients normally store and return tokens unchanged, but the format is public. A token is base64url, without padding, of `{"key": <position>, "back": <bool>}`, where the key is the row position in text form, such as a decimal transaction ID or an account address. `{"key": K}` serves the rows strictly after `K`, `{"key": K, "back": true}` serves the page that ends strictly before `K`, and `{"back": true}` (`eyJiYWNrIjp0cnVlfQ`) serves the last page. The `PageToken` schema in the API reference lists the key for each route.

The routes do not accept `after`. Ledger 3.0 ignores it and returns the first page.

## Paginate gRPC reads

The gRPC list RPCs return the same page tokens in the `x-next-cursor` and `x-previous-cursor` trailers, and accept one back in the `cursor` list option. `ledgerctl` prints a hint for each adjacent page:

```bash
ledgerctl accounts list \
  --ledger "$LEDGER_NAME" \
  --filter 'address ^= "users:"' \
  --reverse \
  --page-size 100 \
  --json

ledgerctl accounts list \
  --ledger "$LEDGER_NAME" \
  --filter 'address ^= "users:"' \
  --reverse \
  --page-size 100 \
  --cursor '<token-from-the-previous-page>' \
  --json
```

Pass a token printed by `ledgerctl` back unchanged, whether it came from the next-page or the previous-page hint. Repeat the same filter and `--reverse` choice on every call. With structured output, `ledgerctl` writes the hints to standard error as `previous_cursor=<token>` and `next_cursor=<token>` lines, so standard output remains valid JSON or YAML. A hint is omitted when there is no such page.

`ledgerctl accounts list --all` and `ledgerctl transactions list --all` follow every next-page token. The log and audit commands do not provide `--all`; consume their emitted tokens explicitly. `ledgerctl logs list --ledger "$LEDGER_NAME" --reverse` lists a ledger's logs newest first. Omitting `--page-size` selects the default page size and does not request every page.

## Keep a multi-page reconciliation stable

A live traversal can overlap new writes. Each page reads a new snapshot: a new row inserted before the current cursor can be omitted, while other changes can produce duplicates. Deduplication handles duplicates but cannot recover an omitted row.

Use live pagination only for best-effort interfaces, or give an incremental worker its own tested watermark-and-overlap protocol. It is not sufficient when the traversal must be complete or when several pages and queries must describe one fixed ledger state.

For a reconciliation:

1. create a query checkpoint;
2. retry a checkpoint-scoped probe until it succeeds on the node serving the reads;
3. pass the same checkpoint ID to every gRPC read;
4. finish every page before deleting the checkpoint.

The direct HTTP list routes do not expose checkpoint reads. Follow [Choose Read Consistency and Use Checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints) and use gRPC or `ledgerctl` for this workflow.

## Diagnose rejected or empty queries

A filter that does not parse, or that uses a condition not valid on the route's target, returns `400` with `INVALID_REQUEST`. The message names the problem:

```json
{"errorCode":"INVALID_REQUEST","errorMessage":"invalid filter: compiling filter: condition \"ledger\" is not valid on accounts queries"}
```

A value that does not match the declared metadata type, such as the string `"15"` for an `int64` key in a structured `$match`, returns `400` with `FILTER_COMPILATION_ERROR` and the message `filter compilation error`. gRPC callers receive `INVALID_ARGUMENT` with the reason `FILTER_COMPILATION_ERROR` when a condition is not valid on its target.

| Result                                | Check                                                                                                                                                                   |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` with `INVALID_REQUEST`          | Confirm the syntax, target, and field name. A field may exist in only one representation. Range bounds on a `datetime` metadata key are Unix microseconds, not RFC 3339 |
| `400` with `FILTER_COMPILATION_ERROR` | Send the value as the declared type, such as a number rather than a string for a numeric key. For a numeric-looking value on a `string` key, use a structured `$match`  |
| `400` with `INDEX_NOT_FOUND`          | Declare the metadata type or create the required built-in index                                                                                                         |
| HTTP `503` with `INDEX_BUILDING`      | Wait for the local index version to become ready; retry with bounded backoff rather than a tight loop                                                                   |
| Empty page after a recent write       | Check the read freshness, ledger name, cursor direction, and filter                                                                                                     |
| Unexpected account prefix matches     | Remember that prefixes compare raw bytes: `accounts:1` also matches `accounts:10`                                                                                       |
| A query parameter has no effect       | `prefix=`, `reference=`, and `after=` are ignored. Move the condition into `filter`, and paginate with `cursor`                                                         |

Continue with [Choose Read Consistency and Use Checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints) when a paginated read must span one fixed view of the ledger.
