Skip to main content

Modes, response rows and paging

Which mode​

The Insights app picks the mode automatically: with metrics it uses aggregation, without metrics it uses composite. Do the same.

aggregationcomposite
Use forCharts, number tiles, summary tablesTables that list documents under groups
MetricsYesNo (documents are returned)
Rows areOne per bucketOne per document
PagingNone. Everything in one responseCursor: pageKey / nextPageKey
size meansIgnored (bucket count comes from options.size of each group)Buckets (groups) per page

Without aggs you get a plain document list (see the last section).

Aggregation mode​

{
aggMode: 'aggregation',
aggs: [
{
id: 'cat', field: 'category.keyword', aggregation: 'terms', options: { size: 10 },
aggs: [{ id: 'rev', field: 'total', aggregation: 'sum' }]
}
]
}
  • All buckets come back in one response. There is no paging. Control the number of buckets with options.size on each grouping.
  • Every group needs a unique id.

Response rows​

Each row is a bucket:

{
"_id": "Coffee",
"aggregation": {
"key": "Coffee",
"fields": { "doc_count": 30, "rev": 1234.5, "cat": "Coffee" },
"layer": "cat",
"depth": 1,
"path": [{ "field": "cat", "key": "Coffee", "doc_count": 30 }]
}
}
PropertyMeaning
aggregation.fieldsWhat you usually want. doc_count, each metric by its id, and each group level by its id (the bucket key)
aggregation.keyThe bucket keys joined with -. Two different keys containing - can collide, so do not use it as a join key
aggregation.depthNesting level, starting at 1
aggregation.layerid of the grouping that produced the row
aggregation.pathThe chain of buckets leading to the row, each with field, key and doc_count

With several grouping levels you get a row for every level. With two groups (category, then country), a row at depth: 2 per category/country pair, plus a row at depth: 1 per category (its summary). Keep only what you need:

const leaves = result.rows.filter(row => row.aggregation.depth === groupCount)

Key types:

  • terms keys are the values. boolean with missingAsFalse gives 'true'/'false'.
  • datetime-interval keys are epoch milliseconds (UTC).
  • datetime-component keys are numbers (0-based, see Grouping), or missing.
  • collect_terms values are arrays.
  • A formula on a keyed filters bucket produces one extra row { _id: '__global__', aggregation: { key: '', fields: { doc_count, <id>: value }, depth: 1 } }.

Pure metric (no grouping)​

With a single match_all stage, the response has exactly one row:

{
"_id": "all",
"aggregation": {
"key": "__all__",
"fields": { "total": 123.4, "__all__": "__all__" },
"layer": "__all__",
"depth": 1,
"path": [{ "field": "__all__", "key": "__all__", "doc_count": 150 }]
}
}

The number of matching documents is path[0].doc_count here. There is no doc_count in fields for this case.

Composite mode​

{
size: 100,
aggMode: 'composite',
fields: ['category', 'channel', 'total'],
sort: [{ 'category.keyword': 'asc' }],
aggs: [
{ id: 'g1', field: 'category.keyword', aggregation: 'terms', options: { includeMissing: true } },
{ id: 'g2', field: 'channel.keyword', aggregation: 'terms' },
{ id: 'docs', aggregation: 'top_hits', options: { size: 10 } }
]
}
  • The last stage must be top_hits and its id must be docs. Otherwise you get an error (missing stage) or no rows.
  • The stages before it are the groups. Composite mode supports terms, datetime-interval and datetime-component. It does not support filters, geo-region, match_all or boolean with missingAsFalse (Elasticsearch rejects them). Empty-interval options are ignored.
  • size is the number of buckets (group combinations) per page. top_hits.options.size is the number of documents per bucket (1 to 100).
  • sort orders the group keys, and the documents inside each bucket.
  • fields are the returned document fields.

Rows are documents, with an aggregation block describing the bucket:

{
"category": "Coffee", "channel": "web", "total": 24.9,
"_id": "8d1f…",
"aggregation": {
"key": "Coffee-web",
"bucketKey": { "g1": "Coffee", "g2": "web" },
"fields": { "doc_count": 4, "g1": "Coffee", "g2": "web" },
"path": [{ "field": "composite", "key": { "g1": "Coffee", "g2": "web" }, "doc_count": 4 }]
}
}

Paging​

const readAll = async source => {
const rows = []
let pageKey

do {
const { status, result } = await source.aggregate({ ...request, pageKey })
if (status !== 200) throw new Error(`aggregate failed: ${status}`)

rows.push(...result.rows)
pageKey = result.nextPageKey
} while (pageKey)

return rows
}
  • nextPageKey is an object { g1: 'Coffee', g2: 'web' } (the last bucket). Pass it back unchanged as pageKey.
  • Only sequential paging works (no jumping to page 5).
  • rows.length counts documents, not buckets. Stop when nextPageKey is missing. Expect one final request that returns no rows.
  • filteredDocCount counts documents.

Document lists​

Without aggs:

await source.aggregate({
size: 500,
fields: ['orderId', 'orderedAt', 'total'],
sort: [{ orderedAt: 'desc' }, { 'orderId.keyword': 'asc' }],
pageKey
})
  • rows are { _id, ...fields }.
  • nextPageKey is an array (the sort values of the last document). Pass it as pageKey for the next page. It needs an explicit, stable sort (add a unique tie-breaker).
  • Alternatively use from and size for offset paging, up to from + size <= 10,000.

Counts in the response​

PropertyMeaning
totalDocCount.valueDocuments in the whole source. Not filtered
filteredDocCountDocuments matching filter (documents, not groups). Missing without a filter. Capped: above 10,000 it is { value: 10000, relation: 'gte' }

For "how many groups" count the rows in aggregation mode. For "how many documents in total" use totalDocCount without a filter, and filteredDocCount with one.