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

# Count objects with search

> Use groupBy on v3 search to count a kind's objects by one field, instead of listing them.

`search` can answer "how many, by what?" without returning rows. Add `groupBy`,
the name of one field, and `search` returns each value of that field with the
number of objects that carry it.

```json theme={null}
{ "kind": "inventory_source", "groupBy": "status" }
```

The response is the same page object `search` returns for the kind, with counts
in place of `results`:

```json theme={null}
{
  "objects": {
    "outcome": "page_inventory_source",
    "kind": "inventory_source",
    "groupBy": "status",
    "total": 6,
    "groups": [
      { "value": "ACTIVE", "count": 3 },
      { "value": "PENDING", "count": 2 },
      { "value": "DISABLED", "count": 1 }
    ],
    "truncated": false
  }
}
```

The tool result's text carries the same counts for hosts that read only text.

## Request

| Field | Meaning |
| - | - |
| `groupBy` | One field the kind can be grouped by. Requires `kind`. It composes with that kind's other filters and `query`, so a count covers exactly the objects the same search would list. |
| `limit` | Caps the number of groups returned, 1 to 50. The default is 50. |
| `cursor` | Not accepted with `groupBy`. A grouped count is one response. |
| `sources` | If sent, must be only `objects`. A grouped count never searches the docs. |

## Response

| Field | Meaning |
| - | - |
| `kind`, `groupBy` | The kind counted and the field grouped by. |
| `total` | The number of objects that match the search, filters applied. |
| `groups` | One entry per distinct value, ordered by `count` descending and then `value` ascending. `value` is `null` for objects with no value for the field, which sort after named values with the same count. |
| `truncated` | `true` when more distinct values exist than `limit` returned. |
| `otherCount` | Present only when `truncated`: the number of objects in the values not returned. Never present when `overlapping`. |
| `overlapping` | Present, and `true`, only for a field an object can have several values of (a media partner's `channel` and `region`). The counts then overlap. |

`sum(groups.count) + otherCount` equals `total`, except when `overlapping` is
`true`. Then an object is counted under every value it has, the counts add up to
more than `total`, and you must not add them up.

A count uses the same account, permissions and data source as the list it
summarises. It never returns rows. `total` is the number of objects that match
the search with its filters applied, not the number the account holds. A plain
`search` of `inventory_source` reports the same number as its `total`, so the
two always agree. Earlier previews also returned `matched` on that plain search;
it is gone, because `total` now carries that meaning.

## Which kinds can be counted

| Kind | `groupBy` fields | Accounts |
| - | - | - |
| `ask` | `askType` (`support`, `product`, `supply`, `integration`, `commercial`), `askState` (`open`, `closed`) | Buyer, Seller |
| `creative` | `advertiserId` | Buyer |
| `event_source` | `advertiserId` | Buyer |
| `inventory_source` | `status` (`PENDING`, `ACTIVE`, `DISABLED`) | Seller |
| `seller` | `selected` (`true`, `false`), `partnerKind` (`platform`, `media`, `null`), `channel`, `region` (these two overlap) | Buyer |

Other kinds do not support `groupBy` yet. The listed `tools/list` schema for
your account is authoritative: accounts that cannot count any kind do not see
the field. Source health is not counted, because it is read per source and not
from the list.

`askType` and `askState` are the two things `filter.askType` and
`filter.askState` already narrow asks by, and they compose with each other and
with `query`:

```json theme={null}
{ "kind": "ask", "groupBy": "askState", "filter": { "askType": "support" } }
```

Asks are read from several places that can each be unavailable, and each read
covers a bounded window. A list tells you which places were unavailable. A count
has no field to say that, so it refuses instead of returning a number that could
be short: `SERVICE_UNAVAILABLE` when a place could not be read (retry), and
`UNSUPPORTED_FEATURE` when a place returned as many asks as one read covers
(narrow the search with `query`, `filter.askType` or `filter.askState`).

### Counting media partners

A Buyer account counts `kind: "seller"` by `selected`, `partnerKind`, `channel`
or `region`, in one database query that reads the same filters, `query` and
status as the list. `total` is the `total` a plain seller search reports. The
counts for `selected` and `partnerKind` add up to it under every filter.

The counts for `channel` and `region` **overlap**, because a media partner sells
in several channels and countries and is counted under each. They add up to more
than `total`, and the response says so with `overlapping: true`: do not add them
up. Each count equals the `total` of the same search filtered by that value, and
a media partner that names no channel (or country) is counted under every one,
as the filter returns it. See
[Channel and region counts overlap](https://docs.apostra.com/v3/media-partner-availability.md#channel-and-region-counts-overlap). `runsOn`, `language`, `topic` and `offers` return
`UNSUPPORTED_FEATURE` until Apostra holds the creator data behind them, and a
count that needs one advertiser's partner status (`filter.partnerStatus` with
`filter.advertiserId`) returns `UNSUPPORTED_FEATURE` too, because that status is
read media partner by media partner and a count of it would be short. The
details are in
[Find media partners with search](https://docs.apostra.com/v3/media-partner-availability.md#find-media-partners-with-search).

### Counting creatives and event sources across the account

A plain `search` of `creative` or `event_source` lists one advertiser at a time:
it needs `filter.advertiserId` (or, for `creative`, `filter.campaignId`). A
grouped count by `advertiserId` needs neither. Without `filter.advertiserId` it
counts every active advertiser you can access, in one call, so "how many
creatives do we have?" or "how many conversion event sources are set up?" takes
one request instead of one search per advertiser:

```json theme={null}
{ "kind": "creative", "groupBy": "advertiserId" }
```

```json theme={null}
{
  "objects": {
    "kind": "creative",
    "groupBy": "advertiserId",
    "total": 7,
    "groups": [
      { "value": "12495", "count": 5 },
      { "value": "8855", "count": 2 }
    ],
    "truncated": false
  }
}
```

`total` is the account-wide count, and each group is one advertiser's share. An
advertiser with none of the kind has no group. To show advertiser names, search
`kind: "advertiser"`; the count carries only ids. The count covers the same
advertisers a plain search would let you open one by one, so a buyer agent counts
only the advertisers it can read. Archived advertisers are not counted.

The kind's other filters still apply. For `creative` that is `query`,
`formatKind`, `assetType`, `role`, `libraryRole`, `source`, `promoted`,
`labels`, `statuses` and `isArchived`, so active creatives are counted unless
you ask for archived ones. `filter.collectionIds` needs `filter.advertiserId`,
because collections belong to one advertiser. For `event_source` it is `query`.
Send `filter.advertiserId` to count one advertiser.

A creative count covers advertisers, not campaigns: `groupBy` with
`filter.campaignId` returns `VALIDATION_ERROR`. To count one campaign's
creatives, search it without `groupBy` and read `total`.

## Errors

| Condition | Code |
| - | - |
| The kind does not support grouped counts, including a kind read by fanning out across sellers or other sources that can each fail, unless its count refuses when a source is short (`ask`) | `UNSUPPORTED_FEATURE`, naming the kind |
| An `ask` count where a source could not be read | `SERVICE_UNAVAILABLE` |
| An `ask` count where a source returned as many asks as one read covers | `UNSUPPORTED_FEATURE` |
| The field is not one the kind can be grouped by | `VALIDATION_ERROR`, listing the groupable fields |
| A `creative` count with `filter.campaignId`, or with `filter.collectionIds` and no `filter.advertiserId` | `VALIDATION_ERROR` |
| An account-wide `event_source` count where an advertiser's access could not be checked | `SERVICE_UNAVAILABLE` (retry) |
| `groupBy` without `kind`, with `cursor`, with `limit` above 50, or with `sources` other than `objects` | `VALIDATION_ERROR` |
| An Apostra staff read that names a `storefrontId` | `UNSUPPORTED_FEATURE` |

`VALIDATION_ERROR` is the code every v3 input refusal carries on the wire.
Correct the request and call again. See [Errors](https://docs.apostra.com/v3/errors.md) for the full
envelope.

Grouping by more than one field, and grouping by time period, are not part of
this contract.

## Kinds with no field to count by

A kind declares a `groupBy` field only when it already filters on that field, so
a count and the list it summarises always agree. These kinds filter by a text
`query` (and, for `conversation`, a start time) and nothing else, and neither a
query nor a time range is a value to count by, so they declare none and
`groupBy` for them returns `UNSUPPORTED_FEATURE`:

| Kind | Why it declares no field |
| - | - |
| `agent` | Your organization's agents are narrowed by `query` only. A Seller Account's `agent` search lists partner sales agents page by page, which is a different read from the organization's own agents. |
| `conversation` | Your Apostra assistant conversations are narrowed by a text query and a start time only. |
| `skill` | Skills are narrowed by `query` only. A query that matches no skill still returns the skills that apply to your account, so a count of the rows returned would not be the count of matches. |

Ask for a list instead, and read `total` for the number of matches.


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