Query data
aggregate reads documents from a source, with filters, sorting, paging and aggregations.
This page is the quick tour. Every filter operator, grouping type, metric and response shape the Insights app uses is documented in the Query reference, with recipes for the common charts.
const orders = sdk.asAdmin().Insights().Source('Orders')
const { status, result } = await orders.aggregate({ size: 5 })
console.log(result.rows)
console.log(result.totalDocCount) // { value: 60, relation: 'eq' }
Response
| Property | Meaning |
|---|---|
rows | The documents ({ _id, ...fields }), or aggregation rows |
nextPageKey | Cursor for the next page. Undefined when there are no more |
totalDocCount | { value, relation }: documents in the source |
filteredDocCount | Documents matching the filter (only if a filter was set) |
fieldTypes | Requested with includeFieldTypes: true |
Choose fields
await orders.aggregate({
size: 20,
fields: ['orderId', 'orderedAt', 'total', 'status']
})
Filter
filter is an array of Elasticsearch query clauses. All must match.
await orders.aggregate({
size: 50,
filter: [
{ term: { 'status.keyword': 'paid' } },
{ range: { total: { gte: 50 } } },
{ range: { orderedAt: { gte: '2026-08-15', lt: '2026-09-01' } } }
]
})
filter and sort must be arrays. Passing an object throws sdk/aggregate-filter-must-be-array or sdk/aggregate-sort-must-be-array.
Frequently needed clauses:
| Goal | Clause |
|---|---|
| Exact text match | { term: { 'status.keyword': 'paid' } } (.keyword for text fields) |
| One of several | { terms: { 'country.keyword': ['DE', 'AT'] } } |
| Number or date range | { range: { total: { gte: 10, lte: 100 } } } |
| Field exists | { exists: { field: 'paymentMethod' } } |
| Text search | { match: { product: 'espresso' } } |
| Not | { bool: { must_not: [{ term: { 'status.keyword': 'cancelled' } }] } } |
| Near a point | { geo_distance: { distance: '10km', location: { lat: 53.55, lon: 9.99 } } } |
Sort
await orders.aggregate({
size: 10,
sort: [{ total: 'desc' }, { 'orderId.keyword': 'asc' }]
})
Page through everything
Use the cursor. Pass the previous nextPageKey as pageKey.
const readAll = async source => {
const all = []
let pageKey
do {
const { status, result } = await source.aggregate({
size: 500,
sort: [{ orderedAt: 'asc' }, { 'orderId.keyword': 'asc' }],
pageKey
})
if (status !== 200) throw new Error(`aggregate failed: ${status}`)
all.push(...result.rows)
pageKey = result.rows.length === 500 ? result.nextPageKey : undefined
} while (pageKey)
return all
}
Give the sort a unique tiebreaker (like orderId.keyword) so pages are stable.
Aggregate
With aggs and aggMode, aggregate computes groupings and metrics on the server. aggs is a list of stages. Bucket stages (terms, datetime-interval, …) can hold child stages in their own aggs.
// Revenue and order count per category
const { result } = await orders.aggregate({
aggMode: 'aggregation',
aggs: [
{
id: 'category',
aggregation: 'terms',
field: 'category.keyword',
aggs: [
{ id: 'revenue', aggregation: 'sum', field: 'total' },
{ id: 'orders', aggregation: 'value_count', field: 'orderId.keyword' }
]
}
]
})
for (const row of result.rows) {
const { category, revenue, orders } = row.aggregation.fields
console.log(category, revenue, orders)
}
Each row is { _id, aggregation: { key, fields, layer, depth, path } }. fields contains the group keys by stage id and the metric values.
| Kind | aggregation values |
|---|---|
| Grouping | terms, boolean, datetime-component, datetime-interval, geo-region, missing, filters, match_all |
| Metrics | value_count, cardinality, cardinality_precise, sum, avg, min, max, formular, collect_terms |
Always send aggMode together with aggs.
The stages are the same ones the Insights app uses for its charts. See Grouping, Metrics and From a chart to code.
Raw data
Every source keeps the raw documents as sent, next to the transformed ones. raw: true reads the raw index.
await orders.aggregate({ size: 5, raw: true })