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.
aggregation | composite | |
|---|---|---|
| Use for | Charts, number tiles, summary tables | Tables that list documents under groups |
| Metrics | Yes | No (documents are returned) |
| Rows are | One per bucket | One per document |
| Paging | None. Everything in one response | Cursor: pageKey / nextPageKey |
size means | Ignored (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.sizeon 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 }]
}
}
| Property | Meaning |
|---|---|
aggregation.fields | What you usually want. doc_count, each metric by its id, and each group level by its id (the bucket key) |
aggregation.key | The bucket keys joined with -. Two different keys containing - can collide, so do not use it as a join key |
aggregation.depth | Nesting level, starting at 1 |
aggregation.layer | id of the grouping that produced the row |
aggregation.path | The 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:
termskeys are the values.booleanwithmissingAsFalsegives'true'/'false'.datetime-intervalkeys are epoch milliseconds (UTC).datetime-componentkeys are numbers (0-based, see Grouping), ormissing.collect_termsvalues are arrays.- A formula on a keyed
filtersbucket 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_hitsand itsidmust bedocs. Otherwise you get an error (missing stage) or no rows. - The stages before it are the groups. Composite mode supports
terms,datetime-intervalanddatetime-component. It does not supportfilters,geo-region,match_allorbooleanwithmissingAsFalse(Elasticsearch rejects them). Empty-interval options are ignored. sizeis the number of buckets (group combinations) per page.top_hits.options.sizeis the number of documents per bucket (1 to 100).sortorders the group keys, and the documents inside each bucket.fieldsare 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
}
nextPageKeyis an object{ g1: 'Coffee', g2: 'web' }(the last bucket). Pass it back unchanged aspageKey.- Only sequential paging works (no jumping to page 5).
rows.lengthcounts documents, not buckets. Stop whennextPageKeyis missing. Expect one final request that returns no rows.filteredDocCountcounts documents.
Document lists
Without aggs:
await source.aggregate({
size: 500,
fields: ['orderId', 'orderedAt', 'total'],
sort: [{ orderedAt: 'desc' }, { 'orderId.keyword': 'asc' }],
pageKey
})
rowsare{ _id, ...fields }.nextPageKeyis an array (the sort values of the last document). Pass it aspageKeyfor the next page. It needs an explicit, stablesort(add a unique tie-breaker).- Alternatively use
fromandsizefor offset paging, up tofrom + size <= 10,000.
Counts in the response
| Property | Meaning |
|---|---|
totalDocCount.value | Documents in the whole source. Not filtered |
filteredDocCount | Documents 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.