Skip to main content

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 partShapeBecomes
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 hitsnumbersize 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​

  1. Read the field definitions of the source (Source(name).get()), so you know the exact names to use for each field.
  2. Mode: aggregation if there is at least one metric, otherwise composite.
  3. Aggs:
    • With groupings: each grouping becomes a stage, with its metrics attached to it as aggs. In composite mode add the docs stage (top_hits) at the end.
    • Without groupings but with metrics: a single match_all stage holding all metrics.
  4. Field names: replace every grouping and metric field with its exact-match form (.keyword for text). Skip groupings and metrics whose field is not in the source.
  5. Filter: turn each filter item into clauses (see Filters) and put them into one bool with must and must_not. Skip items with unknown fields or empty values.
  6. Sort: turn the sort model into sort clauses (see Sorting).
  7. Size: 10000 for charts and maps, the page size for tables (100 by default).
  8. Send it to aggregate. Read row.aggregation.fields for 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 appField of the saved document
Group by panelgrouping model
Metrics panelmetrics model
Filter panelfilter model
Sortsort model
The sourcesource 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.