From a chart to code
A chart or table in the Insights app is a saved configuration. The request it sends is derived from that configuration in a fixed way. This page shows the mapping, so you can build the same request in your own code, and gives you a helper that does it.
The saved configuration
A chart or table stores five things about its query:
| Saved part | Shape | Becomes |
|---|---|---|
| Grouping model | [{ id, field, aggregation, options }] | aggs (the stages) |
| Metrics model | [{ id, field?, aggregation, options }] | aggs[].aggs (metrics on every stage) |
| Filter model | { items: [{ id, field, operator, value }] } | filter |
| Sort model | [{ field, sort: 'asc' | 'desc' }] | sort |
| Top hits | number | size of the docs stage in composite mode |
Everything else in a chart document (chart type, colours, axes, legend, titles) is visual and has no influence on the query. Chart elements refer to the grouping and metric ids, which are the same ids that end up in the response rows. That is how the app reads row.aggregation.fields[id] to draw the chart.
The compile steps
- Read the field definitions of the source (
Source(name).get()), so you know the exact names to use for each field. - Mode:
aggregationif there is at least one metric, otherwisecomposite. - Aggs:
- With groupings: each grouping becomes a stage, with its metrics attached to it as
aggs. In composite mode add thedocsstage (top_hits) at the end. - Without groupings but with metrics: a single
match_allstage holding all metrics.
- With groupings: each grouping becomes a stage, with its metrics attached to it as
- Field names: replace every grouping and metric
fieldwith its exact-match form (.keywordfor text). Skip groupings and metrics whose field is not in the source. - Filter: turn each filter item into clauses (see Filters) and put them into one
boolwithmustandmust_not. Skip items with unknown fields or empty values. - Sort: turn the sort model into sort clauses (see Sorting).
- Size:
10000for charts and maps, the page size for tables (100 by default). - Send it to
aggregate. Readrow.aggregation.fieldsfor the values.
Ready-made helper
The steps above are implemented in a small, dependency-free module:
import sdk from '@scenid/cloud-sdk'
import { buildAggregateRequest } from './insights-query.mjs'
const orders = sdk.asAdmin().Insights().Source('Orders')
// 1. field definitions
const { result: source } = await orders.get()
// 2. the configuration, in the shape the Insights app stores it
const request = buildAggregateRequest({
fieldTypes: source.fieldTypes,
grouping: [{ id: 'category', field: 'category', aggregation: 'terms', options: { size: 10 } }],
metrics: [{ id: 'revenue', field: 'total', aggregation: 'sum' }],
filters: [
{ field: 'status', operator: 'is', value: ['paid'] },
{ field: 'orderedAt', operator: 'dateTimeRange', value: { interval: 'month', offset: -1 } }
],
sort: [{ field: 'category', sort: 'asc' }]
})
// 3. send it
const { result } = await orders.aggregate(request)
const series = result.rows.map(row => row.aggregation.fields)
request is the plain body described in this reference, so you can log or store it, and send it over REST as well:
{
"size": 10000,
"aggMode": "aggregation",
"aggs": [{
"id": "category", "field": "category.keyword", "aggregation": "terms", "options": { "size": 10 },
"aggs": [{ "id": "revenue", "field": "total", "aggregation": "sum" }]
}],
"filter": [{ "bool": {
"must": [
{ "terms": { "status.keyword": ["paid"] } },
{ "range": { "orderedAt": { "gte": "now-1M/M", "lte": "now-1M/M" } } }
],
"must_not": []
} }],
"sort": [{ "category.keyword": "asc" }]
}
The helper also exports the pieces separately: buildFilter, buildSort, buildAggs, filterItemToClauses, keywordField, and leafRows(rows, groupCount) which returns the values of the rows at the deepest level.
It supports the operators the Insights app offers (see Filters). Relative date ranges use Elasticsearch date math (UTC) instead of browser time, and the quarter interval is not supported (send timestamps instead).
Reproduce a chart exactly
The most reliable way to get a working request for a specific chart is to build the chart in the Insights app and take its grouping, metrics, filters and sort as the input above. The saved chart document holds them under the query part of the document:
| In the app | Field of the saved document |
|---|---|
| Group by panel | grouping model |
| Metrics panel | metrics model |
| Filter panel | filter model |
| Sort | sort model |
| The source | source name |
Dashboard filters
The filter widget of a dashboard adds its items to the filter model of every chart on the dashboard before the request is built:
const combined = [...chartFilters, ...dashboardFilters]
buildAggregateRequest({ /* … */ filters: combined })
Items whose field does not exist in the chart's source are skipped automatically.
Live charts
The app keeps a chart "live" by sending the same request again every 60 seconds by default. Do the same with a timer if you build a live display. There is no push mechanism.
Charts on customers
For the customers-entities source use the same steps with data.-prefixed fields, and add a filter on entityType to restrict to companies or people. See Customers as a source.