Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install kibana-dashboards@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin kibana-dashboards v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install kibana-dashboards

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/kibana-dashboards/

Extract the ZIP to .github/skills/ in your repo. The folder name must match kibana-dashboards for Copilot to auto-discover it.

Skill Files (9)

SKILL.md 29.4 KB
---
name: kibana-dashboards
description: >
  Create and manage Kibana Dashboards and Lens visualizations. Use when you need to
  define dashboards and visualizations declaratively, version control them, automate
  their deployment, or improve layout, sections, controls, or chart design.
metadata:
  author: elastic
  version: 0.4.0
  universal: true
compatibility: Kibana 9.4 or later (Dashboards and Visualizations APIs) with matching
  Elasticsearch, self-managed, Elastic Cloud Hosted, or Elastic Cloud Serverless.
  Requires the `elastic` CLI ≥ 0.4 with `stack kb` support (dedicated `dashboards`
  and `visualizations` commands).
---

# Kibana Dashboards and Lens Visualizations

Create, update, and delete Kibana dashboards and standalone Lens visualizations using the Kibana 9.4+ Dashboards and
Visualizations APIs. Produce minimal, diffable JSON bodies; prefer inline panel definitions over library references;
choose the correct dataset type (data view vs ES|QL) before writing metrics or chart layers; and follow the design
guidance in [Dashboard Design Guidelines](references/dashboard-design.md) and
[Chart Design Guidelines](references/chart-design.md) so the result reads like a well-made Kibana dashboard, not a
schema dump.

<!-- begin-partial: preamble -->

## Environment Configuration

This skill executes Elasticsearch operations through the `elastic` CLI. If the
[`elastic` CLI](https://github.com/elastic/cli#configuration) is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.

This skill references operations in HTTP-shorthand form (e.g., `GET /`, `GET /_cat/indices`, `GET /{index}/_mapping`,
`GET /{index}/_settings/index.mode`, `POST /_query`). The [Operations](#operations) table at the end of this document
maps each shorthand to the equivalent `elastic` CLI command — always use the CLI rather than calling the HTTP API
directly.

<!-- end-partial: preamble -->

## Prerequisites

**Version requirement:** Kibana 9.4+ (Dashboards and Visualizations APIs).

**ES|QL placement:**

- Standalone library charts: `PUT kbn:/api/visualizations/{id}` with `data_source.type: "esql"`.
- ES|QL panels embedded in a dashboard: inline `vis` panel `config` with `data_source.type: "esql"` via
  `PUT kbn:/api/dashboards/{id}`.
- Do not use `data_source.type: "data_view_reference"` or index-pattern aggregations when the user explicitly requests
  ES|QL — the persisted Lens state must use a text-based ES|QL datasource (`textBased` / `esql`), not a data-view count
  operation.

## Process

1. **Verify Kibana connectivity.** Call `GET kbn:/api/status`. If the call fails, stop and surface the error — do not
   guess endpoints or credentials. Read `version.number` to confirm the cluster meets the 9.4+ requirement, and keep the
   version in mind: a few settings are marked 9.5+ or 9.6+ in [Design essentials](#design-essentials) and have a
   fallback for older clusters. Never refuse a dashboard on 9.4 because of them.

2. **Classify the task.** Decide whether the user needs a **dashboard** (collection of panels, optional time range), a
   **standalone Lens visualization** (library item referenced by id or used alone), or **both**. Determine whether a
   deterministic saved-object id was supplied — when given, use upsert (`PUT`) with that id rather than `POST` (which
   auto-generates ids).

3. **Choose the dataset type before building metrics or layers.**

   | User intent                                      | Dataset                                                                    | Metric / axis pattern                                                                                                                    |
   | ------------------------------------------------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
   | Simple count or aggregation on a saved data view | `data_source.type: "data_view_reference"` with `ref_id`                    | `metrics: [{ type: "primary", operation: "count" }]` (or other aggregation operations)                                                   |
   | Ad-hoc index pattern                             | `data_source.type: "data_view_spec"` with `index_pattern` and `time_field` | Same aggregation `operation` fields                                                                                                      |
   | ES\|QL query (explicit or complex logic)         | `data_source.type: "esql"` with `query`                                    | `metrics: [{ type: "primary", column: "<alias>" }]` or layer axes `{ column: "<alias>" }` — **never** `operation: "count"` on the metric |

   Write the aggregation in the ES|QL query (`STATS count = COUNT()`), then reference the resulting column by name.

   **Write the ES|QL with the `elasticsearch-esql` skill.** It covers schema discovery, time series data streams (`TS`,
   `RATE` for counters, `METRICS_INFO`), and query execution. Two dashboard-specific points on top of it:
   - Run every panel query before saving it, substituting fixed expressions such as `NOW() - 7 days` for `?_tstart` and
     `?_tend`, which only Kibana can supply.
   - Check the data's time span (`STATS MIN(@timestamp), MAX(@timestamp)`). Without a saved `time_range`, Kibana opens
     the dashboard on the last 15 minutes, so a dashboard over older or historical data renders empty panels. Tell the
     user which range shows data, or ask whether to persist one.

4. **Design before you write.** Read [Dashboard Design Guidelines](references/dashboard-design.md) and
   [Chart Design Guidelines](references/chart-design.md) and decide the composition, the chart type and grid size of
   each panel, the per-chart presentation settings, and the exact `grid` coordinates. The rules most often missed are
   summarized in [Design essentials](#design-essentials) below. Choices you do not make deliberately fall back to those
   defaults; they are not optional polish.

5. **Build a dashboard body when creating or updating dashboards.** The request body is flat — `title`, `panels`, and
   optional `description`, `time_range`, and `pinned_panels` at the root. Do not wrap in `{ data: ... }` on write.
   Required fields:
   - `title` — exact string the user requested; otherwise a title derived from what the panels measure. Never empty.
   - `description` — set on every new dashboard.
   - `panels` — array of panels and sections; use `[]` when the user asks for an empty dashboard (do not omit the key or
     invent panels).
   - `time_range` — when the user specifies a default time filter, set `{ "from": "<expr>", "to": "<expr>" }` (for
     example `{ "from": "now-7d", "to": "now" }`). Supplying `time_range` persists the dashboard time filter on open
     (equivalent to enabling time restore in the UI). Do not invent a range the user did not ask for.
   - `pinned_panels` — the controls chosen in the design step (see the Controls section of the design guidelines).

   **Upsert with a deterministic id:**

   ```json
   {
     "title": "Sales Overview",
     "panels": [],
     "time_range": { "from": "now-7d", "to": "now" }
   }
   ```

   Call `PUT kbn:/api/dashboards/eval-sales-overview` with the body above when the user supplies that id.

   **Inline ES|QL metric panel example** (inside `panels`):

   ```json
   {
     "type": "vis",
     "id": "total-requests",
     "grid": { "x": 0, "y": 0, "w": 12, "h": 5 },
     "config": {
       "type": "metric",
       "data_source": {
         "type": "esql",
         "query": "FROM logs* | STATS `Total requests` = COUNT()"
       },
       "metrics": [{ "type": "primary", "column": "Total requests" }]
     }
   }
   ```

   The metric has no `title` because its label already names it, and it is a quarter-width, 5-row panel — both are
   design defaults, not stylistic choices. Prefer inline `config` properties over `config.ref_id` for portable
   dashboards. Read [Dashboard API Reference](references/dashboard-api-reference.md) for panel types and copy workflows.

6. **Build a standalone Lens visualization when the user asks for a library chart.** Use the Visualizations API. Upsert
   with `PUT kbn:/api/visualizations/{id}` when an id is supplied; otherwise `POST kbn:/api/visualizations` and report
   the generated id from the response.

   **ES|QL metric (total count from logs):**

   ```json
   {
     "type": "metric",
     "title": "Total Requests",
     "data_source": {
       "type": "esql",
       "query": "FROM logs* | STATS count = COUNT()"
     },
     "metrics": [{ "type": "primary", "column": "count" }]
   }
   ```

   Call `PUT kbn:/api/visualizations/eval-total-requests` when that id is required. The API persists a Lens saved object
   whose datasource state uses ES|QL (`textBased` / `esql`), not an index-pattern aggregation.

   Read [Lens API Reference](references/lens-api-reference.md) and
   [Chart Types Reference](references/chart-types-reference.md) for xy, gauge, heatmap, and other chart schemas, and
   apply the same [Chart Design Guidelines](references/chart-design.md) as for dashboard panels.

7. **Edit existing objects in place.** `PUT` replaces the whole document, so `GET` first, change only what was asked,
   and send everything else back unchanged — panel `id`s, queries, filters, controls, and `time_range` included.

8. **Execute and confirm.** Perform the write with `PUT kbn:/api/dashboards/{id}` or `PUT kbn:/api/visualizations/{id}`
   (or `POST` when no id is supplied). Confirm with `GET kbn:/api/dashboards/{id}` or
   `GET kbn:/api/visualizations/{id}`. Report the id and title back to the user — do not claim success without a
   successful read-back.

   A successful read-back proves the object persisted, not that it renders. The API normalizes the body and fills in
   defaults. Compare the returned config against what you sent and look for values you did not intend, for example
   `legend.visibility: "hidden"` on a multi-series chart.

9. **List, export, or delete when requested.** Call `GET kbn:/api/dashboards` or `GET kbn:/api/visualizations` to
   discover existing objects. Call `DELETE kbn:/api/dashboards/{id}` or `DELETE kbn:/api/visualizations/{id}` to remove
   objects. For bulk export or import of saved objects, call `POST kbn:/api/saved_objects/_export` or
   `POST kbn:/api/saved_objects/_import`.

## Design essentials

The full rules live in the references; these are the ones most often missed. They apply to every dashboard and
visualization you write.

**Version-gated settings.** Everything else in this skill works on Kibana 9.4. These three need a newer Kibana; below
that version use the fallback instead of the setting.

| Setting                                                   | Needs | Fallback on older clusters                                                   |
| --------------------------------------------------------- | ----- | ---------------------------------------------------------------------------- |
| `options_list_control` with `values_source: "esql"`       | 9.5   | `data_view_id` and `field_name`; create a data view if none covers the index |
| `background_chart: { type: "trend" }` on an ES\|QL metric | 9.5   | Omit `background_chart`; the metric shows the value only                     |
| `styling: { areas: { fill: "gradient" } }`                | 9.6   | Omit `styling.areas`; areas render with a solid fill                         |

**Dashboard** ([Dashboard Design Guidelines](references/dashboard-design.md))

- Order panels summary metrics → trends → breakdowns. Let the fields drive the panel count; every panel needs a purpose.
- Non-empty `title` and a `description` on every new dashboard, derived from what the queries measure.
- Sections (`{ title, collapsed, grid: { y }, panels }` entries in `panels`) for roughly 6+ visualization panels, each
  holding only panels matching its purpose. 3–5 options-list controls in `pinned_panels` on new dashboards; on an
  all-ES|QL dashboard, source their values from an ES|QL query (`values_source: "esql"`, 9.5+) instead of a data view.
- 48-column grid, 20–24 rows above the fold, 8–12 panels in that band. Sizes by chart type:

  | Panel                     | `w`                                 | `h`   |
  | ------------------------- | ----------------------------------- | ----- |
  | Metric                    | 6, 8, or 12                         | 5–6   |
  | Gauge                     | 12                                  | 8     |
  | XY, heatmap, tag cloud    | 24 (48 for the primary time series) | 10    |
  | Treemap / waffle / mosaic | 24                                  | 10    |
  | Pie / donut               | 12                                  | 10    |
  | Markdown                  | 24–48                               | 4–9   |
  | Data table                | 24–48                               | 12–16 |

  Never make a metric or gauge full-width. Use `w` values that divide 48. Fill rows left to right; a new row's `y` is
  the previous row's `y + max(h)`; panels in a row share `h`; `x + w ≤ 48`. Kibana compacts panels upward, so blank rows
  do not survive — separate groups with sections. Section panels use section-relative coordinates and a section occupies
  one outer row.

**Charts** ([Chart Design Guidelines](references/chart-design.md))

- Pick the chart type from the selection list; tag clouds only for short strings, pies for fewer than about 7 slices.
- No panel title on metric, gauge, tag cloud, and waffle charts; elsewhere a self-explanatory title and no axis titles
  (`title: { visible: false }` on both axes). Never repeat information across title, axes, and labels.
- Natural units via `format`: percent, bytes, bits, duration whenever the column reveals one; plain counts unformatted.
- XY: set `legend: { position: "bottom", layout: { type: "list" }, visibility: "visible" }` on every chart with a
  `breakdown_by` or more than one `y` column, and `visibility: "hidden"` on single-series charts. Use
  `layout: { type: "grid" }` only when the legend carries statistics. The API defaults `visibility` to `hidden` and
  `layout` to `grid`; it does not count the series. Areas (gradient fill) only up to three series, lines above that.
  Line charts take the `elastic_line_optimized` palette on `breakdown_by.color`. Use `scale: "temporal"` for time axes,
  and legend statistics only when asked for avg/min/max "in the legend" (a presentation setting, not an ES|QL
  aggregation).
- Metric: trend background or secondary metric when the query supports it; color the value, never the background, and
  only for bounded metrics (percentages, error rates) with 3 status bands. Never set `apply_color_to` without `color`,
  and never combine a background chart with color: Lens then colors the background, not the value.
- Gauge: never invent `min`/`max`/`goal`; default to four equal percentage bands.
- Heatmap, pie, partition charts, xy series: default palettes unless the user asks. Tables color values as badges only.
- Color only where it carries meaning, always from the [Kibana Palette Catalog](references/color-palettes.md), never
  invented hex values or legacy palettes; the same category keeps one color across all charts.
- On edits, preserve explicit user choices and existing thresholds; defaults are preferences, not proof a setting is
  wrong.

## ES|QL patterns

**Time series bucket** (dashboard time picker injects `?_tstart` / `?_tend`):

```esql
FROM logs*
| WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart
| STATS count = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)
```

See [Chart Types Reference](references/chart-types-reference.md) for axis and layer details.

**Time series data stream (TSDS) xy chart.** `TS` queries accept the same `BUCKET` pattern, so the chart binds the time
axis the same way:

```esql
TS metrics-otel-default
| WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart AND attributes.device != "lo"
| STATS `Throughput` = SUM(RATE(metrics.system.network.io)) BY BUCKET(@timestamp, 75, ?_tstart, ?_tend), attributes.direction
```

**Metric with trend background.** The API copies the query into a hidden trendline layer and adds its own time bucket.
On a `TS` source do not add `BUCKET` yourself and do not `KEEP` after `STATS`; on a `FROM` source keep the `?_tstart` /
`?_tend` filter, or no trendline is built. Derive values inside `STATS`:

```esql
TS metrics-otel-default
| WHERE attributes.state == "idle"
| STATS `CPU busy` = 1 - AVG(metrics.system.cpu.utilization)
```

**Static reference values** — use `EVAL` in the query, then reference the column:

```esql
FROM logs* | STATS count = COUNT() | EVAL goal = 15000
```

## Examples

Two complete dashboard bodies live under [assets/](assets/). Both use every version-gated setting, so they need Kibana
9.6 as written; on 9.5 drop `styling.areas`, and on 9.4 also replace the ES|QL-sourced controls and the trend background
with their fallbacks.

- `dashboard-esql.json` — an ES|QL dashboard over the Kibana sample web logs that follows the design guidance: three
  sections, formatted metrics with a trend background and status coloring, a primary time series with legend statistics,
  breakdown bars, a table, and options-list controls whose values come from ES|QL queries.
- `dashboard-data-view.json` — the same dashboard shape built on the sample logs data view with aggregation operations
  instead of ES|QL: sections, data-view controls, a primary time series with legend statistics, a heatmap, horizontal
  bars, and a ranked table with labeled and formatted columns.

Single-chart schema examples for every chart type are in [Chart Types Reference](references/chart-types-reference.md).

## Guidelines

1. **Minimal payloads, complete presentation** — omit derivable metadata and schema defaults, but always set the
   presentation settings the design guidance calls for (formats, hidden axis titles, legend position and visibility,
   gradient areas, metric coloring, gauge bands), subject to the version-gated table in
   [Design essentials](#design-essentials). The API does not add these for you.
2. **Read references before complex charts** — metric and xy schemas differ between data view and ES|QL; consult
   [Chart Types Reference](references/chart-types-reference.md) before generating partition or table charts.

## Common issues

| Error                                             | Likely cause                                                                        | Fix                                                                                                           |
| ------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 404 on GET after PUT                              | Wrong id or space                                                                   | Confirm id and retry `GET kbn:/api/dashboards/{id}`                                                           |
| 400 validation                                    | ES\|QL column mismatch                                                              | Align `metrics[].column` / layer `column` with `STATS` aliases in the query                                   |
| ES\|QL panel saved as data view                   | Wrong dataset type                                                                  | Use `data_source.type: "esql"`, not `data_view_reference`                                                     |
| Empty dashboard missing time filter               | Omitted `time_range`                                                                | Include `{ "from": "now-7d", "to": "now" }` when a default range is required                                  |
| XY chart failure                                  | Missing layer `data_source`                                                         | Put `data_source` inside each layer, not only at the root                                                     |
| Metric value rendered green                       | `apply_color_to` without `color`                                                    | Omit both, or add a `color` config alongside `apply_color_to: "value"`                                        |
| Metric tile is a solid colored block              | `background_chart` combined with `color` steps                                      | Lens colors the background when a trend or bar is present; drop either the background chart or the color      |
| Metric panel: "expected at most one time tbucket" | Trend background on a `TS` query that groups by `BUCKET(@timestamp, ...)`           | Remove the `BUCKET`; the API appends `TBUCKET(75)` itself (an existing `TBUCKET` is kept)                     |
| Trend metric shows no trend line                  | `FROM` query without `?_tstart` / `?_tend`, or `TS` query with `KEEP` after `STATS` | Add the time filter, or drop the `KEEP`; see the Metric rules in Chart Design Guidelines                      |
| Multi-series xy chart shows no legend             | `legend.visibility` omitted, so the API set it to `hidden`                          | Set `legend: { position: "bottom", visibility: "visible" }` on charts with a breakdown or several `y` columns |
| 400 on color config                               | Categorical mapping on a numeric column, or `steps` on a keyword column             | Match the coloring mode to the column type; see Chart Design Guidelines                                       |
| 400 on `steps`                                    | Non-continuous ranges or missing `gte`/`lt`                                         | Every step except the first needs `gte`, every step except the last needs `lt`, the last uses `lte`           |
| 400 on `format.duration`                          | Unit name such as `milliseconds`                                                    | Use the short unit codes `ps`, `ns`, `us`, `ms`, `s`, `min`, `h`, `d`, `w`, `mo`, `y`; `to` accepts `auto`    |
| Control fails validation                          | Missing `data_view_id`                                                              | Look the data view up with `GET kbn:/api/data_views`, create one, or source the options from ES\|QL instead   |
| Panels overlap or leave gaps                      | Coordinates not recomputed                                                          | Reflow with the positioning rules in the Dashboard Design Guidelines                                          |

## Operations

As of CLI v0.4.0 the Dashboards and Visualizations APIs have dedicated `elastic kb dashboards` and
`elastic kb visualizations` command groups. `elastic kb` is shorthand for `elastic stack kb`. Write commands take the
JSON body from `--input-file '<path.json>'` or `--body '<json>'`. `upsert-*` takes the id on `--id` and creates or
replaces the object. `delete-*` requires `--yes`. Every command accepts `--dry-run`, which validates flags and JSON
syntax only. It does not validate the panel schema. To author several objects at once, build a saved-object NDJSON file
and import it with `post-saved-objects-import`. Read it back with `post-saved-objects-export`. If the CLI rejects a
command name from this table, run `elastic stack kb <group> --help` and use the listed name.

| HTTP API (shorthand)                                                                              | `elastic` CLI command                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `GET kbn:/api/status`                                                                             | `elastic kb system get-status`                                                                                                                                                                                                                               |
| `POST kbn:/api/saved_objects/_import`                                                             | `elastic kb saved-objects post-saved-objects-import --file '<path.ndjson>' --overwrite`                                                                                                                                                                      |
| `POST kbn:/api/saved_objects/_export`                                                             | `elastic kb saved-objects post-saved-objects-export --objects '[{"type":"<type>","id":"<id>"}]'` (returns a JSON array, not NDJSON)                                                                                                                          |
| `GET kbn:/api/dashboards`                                                                         | `elastic kb dashboards search-dashboards`                                                                                                                                                                                                                    |
| `GET kbn:/api/dashboards/{id}`                                                                    | `elastic kb dashboards get-dashboard --id '<id>'`                                                                                                                                                                                                            |
| `PUT kbn:/api/dashboards/{id}`                                                                    | `elastic kb dashboards upsert-dashboard --id '<id>' --input-file '<path.json>'`                                                                                                                                                                              |
| `POST kbn:/api/dashboards` (no id)                                                                | `elastic kb dashboards create-dashboard --input-file '<path.json>'`                                                                                                                                                                                          |
| `DELETE kbn:/api/dashboards/{id}`                                                                 | `elastic kb dashboards delete-dashboard --id '<id>' --yes`                                                                                                                                                                                                   |
| `GET kbn:/api/visualizations`                                                                     | `elastic kb visualizations search-visualizations`                                                                                                                                                                                                            |
| `GET kbn:/api/visualizations/{id}`                                                                | `elastic kb visualizations get-visualization --id '<id>'`                                                                                                                                                                                                    |
| `PUT kbn:/api/visualizations/{id}`                                                                | `elastic kb visualizations upsert-visualization --id '<id>' --input-file '<path.json>'`                                                                                                                                                                      |
| `POST kbn:/api/visualizations` (no id)                                                            | `elastic kb visualizations create-visualization --input-file '<path.json>'`                                                                                                                                                                                  |
| `DELETE kbn:/api/visualizations/{id}`                                                             | `elastic kb visualizations delete-visualization --id '<id>' --yes`                                                                                                                                                                                           |
| `GET kbn:/api/data_views`                                                                         | `elastic kb data-views get-all-data-views-default` (to find a `data_view_id` for controls)                                                                                                                                                                   |
| `POST kbn:/api/data_views/data_view`                                                              | `elastic kb data-views create-data-view-default --input-file '<path.json>'`                                                                                                                                                                                  |
| `GET /_cat/indices`, `GET /{index}/_mapping`, `GET /{index}/_settings/index.mode`, `POST /_query` | `elastic es cat indices --index '<pattern>'`, `elastic es indices get-mapping --index '<index>'`, `elastic es indices get-settings --index '<index>' --name index.mode`, `elastic es esql query --format tsv --query "<esql>" [--filter '<query dsl json>']` |
assets/
dashboard-data-view.json 13.6 KB
{
  "title": "Web traffic overview (data view)",
  "description": "Request volume, response sizes, and client reach from the Kibana sample web logs, broken down by response code, host, and destination country. Every panel uses aggregation operations on the kibana_sample_data_logs data view, and the controls filter on its fields.",
  "time_range": {
    "from": "now-30d",
    "to": "now"
  },
  "pinned_panels": [
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": true,
      "config": {
        "title": "Response code",
        "data_view_id": "90943e30-9a47-11e8-b64d-95841ca0b247",
        "field_name": "response.keyword"
      }
    },
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": true,
      "config": {
        "title": "Operating system",
        "data_view_id": "90943e30-9a47-11e8-b64d-95841ca0b247",
        "field_name": "machine.os.keyword"
      }
    },
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": true,
      "config": {
        "title": "Destination country",
        "data_view_id": "90943e30-9a47-11e8-b64d-95841ca0b247",
        "field_name": "geo.dest"
      }
    }
  ],
  "panels": [
    {
      "title": "Key metrics",
      "collapsed": false,
      "grid": {
        "y": 0
      },
      "panels": [
        {
          "type": "vis",
          "id": "total-requests",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metrics": [
              {
                "type": "primary",
                "operation": "count",
                "label": "Requests"
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "avg-bytes",
          "grid": {
            "x": 12,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metrics": [
              {
                "type": "primary",
                "operation": "average",
                "field": "bytes",
                "label": "Average response size",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "max-bytes",
          "grid": {
            "x": 24,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metrics": [
              {
                "type": "primary",
                "operation": "max",
                "field": "bytes",
                "label": "Largest response",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "unique-ips",
          "grid": {
            "x": 36,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metrics": [
              {
                "type": "primary",
                "operation": "unique_count",
                "field": "clientip",
                "label": "Unique clients"
              }
            ]
          }
        }
      ]
    },
    {
      "title": "Trends",
      "collapsed": false,
      "grid": {
        "y": 1
      },
      "panels": [
        {
          "type": "vis",
          "id": "requests-over-time",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 48,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests over time",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "visible",
              "statistics": ["avg", "min", "max"],
              "layout": {
                "type": "grid"
              }
            },
            "styling": {
              "areas": {
                "fill": "gradient"
              }
            },
            "layers": [
              {
                "type": "area",
                "data_source": {
                  "type": "data_view_reference",
                  "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
                },
                "x": {
                  "operation": "date_histogram",
                  "field": "@timestamp"
                },
                "y": [
                  {
                    "operation": "count",
                    "label": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "bytes-over-time",
          "grid": {
            "x": 0,
            "y": 10,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Bytes transferred over time",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "styling": {
              "areas": {
                "fill": "gradient"
              }
            },
            "layers": [
              {
                "type": "area",
                "data_source": {
                  "type": "data_view_reference",
                  "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
                },
                "x": {
                  "operation": "date_histogram",
                  "field": "@timestamp"
                },
                "y": [
                  {
                    "operation": "sum",
                    "field": "bytes",
                    "label": "Bytes",
                    "format": {
                      "type": "bytes",
                      "decimals": 1
                    }
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "response-codes-over-time",
          "grid": {
            "x": 24,
            "y": 10,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "heatmap",
            "title": "Requests by response code over time",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metric": {
              "operation": "count"
            },
            "x": {
              "operation": "date_histogram",
              "field": "@timestamp"
            },
            "y": {
              "operation": "terms",
              "fields": ["response.keyword"],
              "limit": 10
            }
          }
        }
      ]
    },
    {
      "title": "Breakdowns",
      "collapsed": false,
      "grid": {
        "y": 2
      },
      "panels": [
        {
          "type": "vis",
          "id": "response-codes",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests by response code",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar_horizontal",
                "data_source": {
                  "type": "data_view_reference",
                  "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
                },
                "x": {
                  "operation": "terms",
                  "fields": ["response.keyword"],
                  "limit": 10
                },
                "y": [
                  {
                    "operation": "count",
                    "label": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "top-hosts",
          "grid": {
            "x": 24,
            "y": 0,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests by host",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar_horizontal",
                "data_source": {
                  "type": "data_view_reference",
                  "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
                },
                "x": {
                  "operation": "terms",
                  "fields": ["host.keyword"],
                  "limit": 10
                },
                "y": [
                  {
                    "operation": "count",
                    "label": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "traffic-by-country",
          "grid": {
            "x": 0,
            "y": 10,
            "w": 48,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Bytes transferred by destination country",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar",
                "data_source": {
                  "type": "data_view_reference",
                  "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
                },
                "x": {
                  "operation": "terms",
                  "fields": ["geo.dest"],
                  "limit": 10
                },
                "y": [
                  {
                    "operation": "sum",
                    "field": "bytes",
                    "label": "Bytes",
                    "format": {
                      "type": "bytes",
                      "decimals": 1
                    }
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "top-urls-table",
          "grid": {
            "x": 0,
            "y": 20,
            "w": 48,
            "h": 12
          },
          "config": {
            "type": "data_table",
            "title": "Top URLs by request count",
            "data_source": {
              "type": "data_view_reference",
              "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
            },
            "metrics": [
              {
                "operation": "count",
                "label": "Requests"
              },
              {
                "operation": "sum",
                "field": "bytes",
                "label": "Bytes",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              },
              {
                "operation": "average",
                "field": "bytes",
                "label": "Average response size",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              }
            ],
            "rows": [
              {
                "operation": "terms",
                "fields": ["url.keyword"],
                "limit": 15,
                "rank_by": {
                  "type": "metric",
                  "metric_index": 0,
                  "direction": "desc"
                }
              }
            ]
          }
        }
      ]
    }
  ]
}
dashboard-esql.json 14.2 KB
{
  "title": "Web traffic overview",
  "description": "Request volume, error rate, and transferred bytes from the Kibana sample web logs (kibana_sample_data_logs), broken down by response code, operating system, and file extension. All panels use ES|QL; controls list their options from ES|QL queries so no data view is required.",
  "time_range": {
    "from": "now-7d",
    "to": "now"
  },
  "pinned_panels": [
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": true,
      "config": {
        "title": "Operating system",
        "values_source": "esql",
        "esql_query": "FROM kibana_sample_data_logs | STATS BY machine.os",
        "selected_options": []
      }
    },
    {
      "type": "options_list_control",
      "width": "medium",
      "grow": true,
      "config": {
        "title": "Response code",
        "values_source": "esql",
        "esql_query": "FROM kibana_sample_data_logs | STATS BY response",
        "selected_options": []
      }
    }
  ],
  "panels": [
    {
      "title": "Key metrics",
      "collapsed": false,
      "grid": {
        "y": 0
      },
      "panels": [
        {
          "type": "vis",
          "id": "requests",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "esql",
              "query": "FROM kibana_sample_data_logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS `Requests` = COUNT()"
            },
            "metrics": [
              {
                "type": "primary",
                "column": "Requests",
                "background_chart": {
                  "type": "trend"
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "error-rate",
          "grid": {
            "x": 12,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "esql",
              "query": "FROM kibana_sample_data_logs | STATS `Error rate` = 100.0 * COUNT(CASE(TO_INTEGER(response) >= 400, 1, null)) / COUNT()"
            },
            "metrics": [
              {
                "type": "primary",
                "column": "Error rate",
                "format": {
                  "type": "number",
                  "decimals": 1,
                  "suffix": "%"
                },
                "apply_color_to": "value",
                "color": {
                  "type": "dynamic",
                  "range": "absolute",
                  "steps": [
                    {
                      "gte": 0,
                      "lt": 5,
                      "color": "#24c292"
                    },
                    {
                      "gte": 5,
                      "lt": 10,
                      "color": "#fcd883"
                    },
                    {
                      "gte": 10,
                      "lte": 100,
                      "color": "#f6726a"
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "avg-bytes",
          "grid": {
            "x": 24,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "esql",
              "query": "FROM kibana_sample_data_logs | STATS `Average response size` = AVG(bytes)"
            },
            "metrics": [
              {
                "type": "primary",
                "column": "Average response size",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "total-bytes",
          "grid": {
            "x": 36,
            "y": 0,
            "w": 12,
            "h": 5
          },
          "config": {
            "type": "metric",
            "data_source": {
              "type": "esql",
              "query": "FROM kibana_sample_data_logs | STATS `Bytes transferred` = SUM(bytes)"
            },
            "metrics": [
              {
                "type": "primary",
                "column": "Bytes transferred",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              }
            ]
          }
        }
      ]
    },
    {
      "title": "Trends",
      "collapsed": false,
      "grid": {
        "y": 1
      },
      "panels": [
        {
          "type": "vis",
          "id": "requests-over-time",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 48,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests over time",
            "axis": {
              "x": {
                "scale": "temporal",
                "domain": {
                  "type": "fit",
                  "rounding": false
                },
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "visible",
              "statistics": ["avg", "min", "max"],
              "layout": {
                "type": "grid"
              }
            },
            "styling": {
              "areas": {
                "fill": "gradient"
              }
            },
            "layers": [
              {
                "type": "area",
                "data_source": {
                  "type": "esql",
                  "query": "FROM kibana_sample_data_logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS `Requests` = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
                },
                "x": {
                  "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)",
                  "label": "@timestamp"
                },
                "y": [
                  {
                    "column": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "requests-by-response-over-time",
          "grid": {
            "x": 0,
            "y": 10,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests by response code over time",
            "axis": {
              "x": {
                "scale": "temporal",
                "domain": {
                  "type": "fit",
                  "rounding": false
                },
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "visible",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar_stacked",
                "data_source": {
                  "type": "esql",
                  "query": "FROM kibana_sample_data_logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS `Requests` = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend), response"
                },
                "x": {
                  "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)",
                  "label": "@timestamp"
                },
                "y": [
                  {
                    "column": "Requests"
                  }
                ],
                "breakdown_by": {
                  "column": "response"
                }
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "bytes-by-os-over-time",
          "grid": {
            "x": 24,
            "y": 10,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Bytes transferred by operating system over time",
            "axis": {
              "x": {
                "scale": "temporal",
                "domain": {
                  "type": "fit",
                  "rounding": false
                },
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "visible",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "line",
                "data_source": {
                  "type": "esql",
                  "query": "FROM kibana_sample_data_logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS `Bytes` = SUM(bytes) BY BUCKET(@timestamp, 75, ?_tstart, ?_tend), machine.os"
                },
                "x": {
                  "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)",
                  "label": "@timestamp"
                },
                "y": [
                  {
                    "column": "Bytes",
                    "format": {
                      "type": "bytes",
                      "decimals": 1
                    }
                  }
                ],
                "breakdown_by": {
                  "column": "machine.os",
                  "color": {
                    "mode": "categorical",
                    "palette": "elastic_line_optimized",
                    "mapping": []
                  }
                }
              }
            ]
          }
        }
      ]
    },
    {
      "title": "Breakdowns",
      "collapsed": false,
      "grid": {
        "y": 2
      },
      "panels": [
        {
          "type": "vis",
          "id": "requests-by-os",
          "grid": {
            "x": 0,
            "y": 0,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests by operating system",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar_horizontal",
                "data_source": {
                  "type": "esql",
                  "query": "FROM kibana_sample_data_logs | STATS `Requests` = COUNT() BY machine.os | SORT `Requests` DESC"
                },
                "x": {
                  "column": "machine.os"
                },
                "y": [
                  {
                    "column": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "requests-by-extension",
          "grid": {
            "x": 24,
            "y": 0,
            "w": 24,
            "h": 10
          },
          "config": {
            "type": "xy",
            "title": "Requests by file extension",
            "axis": {
              "x": {
                "title": {
                  "visible": false
                }
              },
              "y": {
                "title": {
                  "visible": false
                }
              }
            },
            "legend": {
              "position": "bottom",
              "visibility": "hidden",
              "layout": {
                "type": "list"
              }
            },
            "layers": [
              {
                "type": "bar_horizontal",
                "data_source": {
                  "type": "esql",
                  "query": "FROM kibana_sample_data_logs | WHERE extension != \"\" | STATS `Requests` = COUNT() BY extension | SORT `Requests` DESC"
                },
                "x": {
                  "column": "extension"
                },
                "y": [
                  {
                    "column": "Requests"
                  }
                ]
              }
            ]
          }
        },
        {
          "type": "vis",
          "id": "traffic-by-os",
          "grid": {
            "x": 0,
            "y": 10,
            "w": 48,
            "h": 12
          },
          "config": {
            "type": "data_table",
            "title": "Traffic by operating system",
            "data_source": {
              "type": "esql",
              "query": "FROM kibana_sample_data_logs | STATS `Requests` = COUNT(), `Bytes` = SUM(bytes), `Average response size` = AVG(bytes), `Error rate` = 100.0 * COUNT(CASE(TO_INTEGER(response) >= 400, 1, null)) / COUNT() BY machine.os | SORT `Requests` DESC"
            },
            "rows": [
              {
                "column": "machine.os"
              }
            ],
            "metrics": [
              {
                "column": "Requests"
              },
              {
                "column": "Bytes",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              },
              {
                "column": "Average response size",
                "format": {
                  "type": "bytes",
                  "decimals": 1
                }
              },
              {
                "column": "Error rate",
                "format": {
                  "type": "number",
                  "decimals": 1,
                  "suffix": "%"
                },
                "apply_color_to": "badge",
                "color": {
                  "type": "auto"
                }
              }
            ]
          }
        }
      ]
    }
  ]
}
references/
chart-design.md 24.1 KB
# Chart Design Guidelines

What a good chart looks like, and how to express it in the visualization config JSON. These rules apply to every inline
`vis` panel `config` and every standalone visualization body. [Chart Types Reference](chart-types-reference.md)
documents the schema of each chart type; this document tells you which settings to choose. Palette names, ids, and hex
values are in the [Kibana Palette Catalog](color-palettes.md).

Every section has two parts: **Design** (the preference, stated without JSON) and **Config** (how to carry it out). Do
not invent a second design policy in the config: the config only implements the design.

## Choosing a chart type

Choose the type that best fits the user's intent and the nature of the data being visualized:

- `metric` — Displays a single numeric value, KPI, or aggregate statistic (count, sum, average) with an optional trend
  line. Choose for single numbers without ranges or targets.
- `gauge` — Displays a single metric within a range with optional min/max/goal bounds. Choose when showing progress
  toward a goal or performance against thresholds (for example "CPU usage as a gauge", "sales target progress").
- `xy` — Line, bar, or area charts with X and Y axes. Choose for time series, trends, comparisons across series, or
  distributions/histograms (for example "request count over time", "average CPU over time", "sales by region as a bar
  chart"). Avg/min/max _in the legend_ is still xy, not a combination chart.
- `heatmap` — Colors a two-dimensional grid of x/y buckets by metric magnitude. Choose when both axes are buckets
  (categorical or time) and color should convey density or intensity (for example "errors by service and status code",
  "requests by hour of day and day of week").
- `tag_cloud` — Displays terms sized by frequency or value. Choose only when the terms are short strings (tags, status
  codes, country codes, browsers). Do not use for long text such as error messages, URLs, or log lines — use a table
  instead.
- `region_map` — Choropleth map coloring geographic boundaries (country, state, county) by a metric. Choose when the
  data has region identifiers that join to map boundaries and a map view is expected (for example "revenue by state on a
  map").
- `data_table` — Structured table with sortable columns. Choose when precise values, sortable columns, or
  multi-dimensional breakdowns matter more than visual patterns (for example "list top 20 hosts by CPU usage").
- `pie` — Pie or donut showing part-to-whole proportions as slices. Choose for percentage breakdowns with a limited
  number of categories, ideally fewer than 7 (for example "traffic distribution by browser as a donut").
- `treemap` — Nested rectangles where area encodes magnitude. Choose for size comparisons across many categories or
  hierarchical breakdowns (for example "disk usage by folder", "log volume by service and host").
- `waffle` — Grid of small squares where the filled share encodes a proportion. Choose for intuitive single-percentage
  displays that read easier than pie charts (for example "percentage of requests that are errors").
- `mosaic` — Tiled rectangles where area and position encode the joint distribution of two categorical dimensions.
  Choose for cross-tabulations (for example "request methods by status code", "error distribution across services and
  environments").

When a request fits none of these, pick the closest supported type and explain the substitution.

## General rules (all chart types)

### Design

- **Titles:** omit the panel title when the chart already displays the information within itself (metric, gauge, tag
  cloud, and waffle charts show their value and label directly). When a title is needed, make it self-explanatory and
  exhaustive so axis titles become unnecessary. Never duplicate information across the title, axis titles, and metric
  labels.
- **Units:** show values in their natural unit whenever the data has a well-known one — percentages for utilization and
  rates, bytes for storage, memory, and network volume, bits for network throughput, human-readable durations for
  latency and response times. Column names and the request often reveal the unit (for example "cpu", "percent",
  "bytes_in", "disk_used", "latency_ms"); apply it even when nobody asked. Plain counts, rates without a known scale,
  and ambiguous units stay unformatted.
- **Defaults are preferences, not proof that an existing setting is wrong.** A gauge goal, a threshold, or an unusual
  color may be intentional; preserve explicit user choices and meaningful existing settings when editing.

### Config

- **Titles:** omit the `title` field (or set it to `""`) to show no title. For ES|QL metrics, alias the column in the
  query so the metric label is readable (for example ``STATS `Total Requests` = COUNT()``).
- **Number formats** — set `format` on the bound column (`metrics[]`, `y[]`, gauge `metric`, table columns):

  | Data                            | Format                                                                           |
  | ------------------------------- | -------------------------------------------------------------------------------- |
  | CPU / utilization percentages   | `{ "type": "percent", "decimals": 1, "compact": true }` (expects a 0–1 fraction) |
  | Whole-number percentages        | `{ "type": "number", "decimals": 1, "suffix": "%" }` (value already 0–100)       |
  | Bytes                           | `{ "type": "bytes", "decimals": 1 }`                                             |
  | Bits                            | `{ "type": "bits", "decimals": 1 }`                                              |
  | Durations                       | `{ "type": "duration", "from": "<source unit>", "to": "auto" }`                  |
  | Large plain numbers (if needed) | `{ "type": "number", "decimals": 0, "compact": true }`                           |

  The duration `from` unit must match how the field is stored: one of `ps`, `ns`, `us`, `ms`, `s`, `min`, `h`, `d`, `w`,
  `mo`, `y` (for example `"ms"` for `latency_ms`). `to` is `auto`, `auto-approximate`, or one of `ms`, `s`, `min`, `h`,
  `d`, `w`, `mo`, `y` (no sub-millisecond targets). Do NOT apply a format to plain counts or ambiguous units.

## Series statistics versus measures

Two different "average" requests — do not mix them:

- **Measure over time:** "average `<field>` over time" (for example average CPU). The query averages that field with
  `AVG(<field>)` in a single `STATS ... BY <time bucket>`, and the chart binds that column. That is not legend
  statistics.
- **Legend statistics:** "log volume over time, show avg/min/max" or "trend with avg, min, max" when no source field is
  being averaged. Those words are presentation: query only the measure over time (for example the count per bucket), do
  **not** add `AVG`/`MIN`/`MAX` columns or a second `STATS` that collapses the buckets, and instead set
  `legend.statistics` on the xy chart with `legend.visibility: "visible"`.

Supported `legend.statistics` values: `min`, `max`, `avg`, `median`, `range`, `last_value`, `last_non_null_value`,
`first_value`, `first_non_null_value`, `difference`, `difference_percentage`, `count`, `total`, `standard_deviation`,
`variance`, `distinct_count`, `current_and_last_value`. Never invent statistic columns the query does not emit.

```json
"legend": { "position": "bottom", "layout": { "type": "grid" }, "visibility": "visible", "statistics": ["avg", "min", "max"] }
```

## Metric

### Design

- No panel title: the primary metric label already names the panel.
- A single number is fine. When the query results support it and the value benefits from context, add a trend background
  or a secondary metric instead of leaving a lone number on white.
- Show a progress bar only when the value has a meaningful maximum.
- A secondary trend or delta needs no label; label a secondary metric only when it is a distinct named measure.
- Color the value, not the background, and only when it carries meaning. Clearly bounded metrics (percent, ratio,
  CPU/memory/disk utilization, error rate, success rate, SLO compliance) benefit from status bands in the same scale as
  the value; for adverse metrics such as error rate, higher is worse. Unbounded values (raw counts, bytes, durations,
  throughput, rates with unknown scale) stay uncolored.
- A metric is either colored or has a background chart, not both. When a trend or progress bar background is present,
  Lens applies the color to the background instead of the value, so status bands turn the whole tile into a colored
  block. For a bounded metric, prefer the colored value and skip the trend; for an unbounded metric, use the trend and
  no color.

### Config

- Trend backgrounds (`background_chart: { "type": "trend" }` on the primary metric) and secondary metrics (a second
  `metrics[]` entry with `"type": "secondary"`) must bind columns the same ES|QL query returns. Never invent another
  index or field.
- **Trend backgrounds on ES|QL metrics (Kibana 9.5+).** On 9.4 the setting is accepted but no trendline layer is
  generated for ES|QL sources, so omit `background_chart` there. From 9.5 the API builds a hidden `*_trendline` layer by
  copying the query and adding a time bucket to the `STATS ... BY` clause. It needs to know the time field, which it
  reads from the column compared to `?_tstart` / `?_tend` in the query, or assumes `@timestamp` for a `TS` source. Rules
  that follow from this:
  - `FROM` queries must filter on the time field with `?_tstart` / `?_tend`, otherwise no trendline layer is created and
    the metric silently renders without a trend. The API appends `BUCKET(<time field>, 75, ?_tstart, ?_tend)`, or keeps
    an existing `BUCKET(<time field>, ...)` in the `BY` clause, and adds the bucket column to any later `KEEP`.
  - `TS` queries get `TBUCKET(75)` appended to the first `STATS` after `TS`, unless that `STATS` already groups by
    `TBUCKET(...)`, which is kept. A `BUCKET(@timestamp, ...)` is not recognized on a `TS` source, so it ends up next to
    the appended `TBUCKET` and Elasticsearch rejects the query with "expected at most one time tbucket". The API does
    not add the bucket column to a later `KEEP` on `TS` queries, so a `KEEP` after `STATS` drops it and the trend is
    empty.
  - Simplest shape for both sources: `source | WHERE <time filter> ... | STATS <alias> = <agg>` with derived values
    computed inside `STATS`, for example ``STATS `CPU busy` = 1 - AVG(cpu.idle)``, and no `KEEP` afterwards.
- Progress bar: `background_chart: { "type": "bar", "max_value": "<column>" }` on the primary metric, only for
  meaningful progress-to-max.
- For trend/delta secondary metrics, hide the label with `styling.secondary.label.visible: false` and omit `label`.
- Coloring: set `"apply_color_to": "value"` only together with a `color` config; do not color the background unless the
  user asks. When not coloring, omit both `color` and `apply_color_to` — `apply_color_to` without a color makes Lens
  tint the value with a default green.
- Never combine `background_chart` (`trend` or `bar`) with `color` steps or `apply_color_to`. Lens ignores
  `apply_color_to: "value"` when a background chart is present and colors the background instead. Pick one per metric.
- Bounded metrics: explicit 3-band `steps` with thresholds in the same unit and scale as the metric output (percent
  thresholds for percent values, fractions for 0–1 values). Prefer "Status", "Negative", "Positive", or "Temperature"
  when thresholds have semantic meaning; use a status/adverse palette for adverse metrics. Copy the 3-stop preview of
  the chosen palette from the catalog.
- Unbounded values: `color: { "type": "auto" }` or no color.

```json
{
  "type": "metric",
  "data_source": {
    "type": "esql",
    "query": "FROM metrics* | STATS `Error rate` = 100.0 * COUNT(CASE(status >= 500, 1, null)) / COUNT()"
  },
  "metrics": [
    {
      "type": "primary",
      "column": "Error rate",
      "format": { "type": "number", "decimals": 1, "suffix": "%" },
      "apply_color_to": "value",
      "color": {
        "type": "dynamic",
        "range": "absolute",
        "steps": [
          { "gte": 0, "lt": 1, "color": "#24c292" },
          { "gte": 1, "lt": 5, "color": "#fcd883" },
          { "gte": 5, "lte": 100, "color": "#f6726a" }
        ]
      }
    }
  ]
}
```

## Gauge

### Design

- Gauge bounds and goals describe business targets. Never invent, infer, or backfill minimum, maximum, or goal values
  from the data or from units like bytes, requests, or rates; set them only when the user provides them, and keep
  existing ones on edits.
- For new gauges, prefer four equal percentage color bands unless the user specifies different bands. When improving an
  existing dashboard, apply the four equal percentage bands unless the existing bands reflect explicit user thresholds
  or meaningful business ranges. A focused color or palette edit keeps the existing band count, thresholds, and
  percentage or absolute scale.

### Config

- Omit `min`, `max`, and `goal` unless the user supplied them or the existing configuration already has them.
- Default bands: `color: { "type": "dynamic", "range": "percentage", "steps": [...] }` with 4 bands `0 <= value < 25`,
  `25 <= value < 50`, `50 <= value < 75`, `75 <= value <= 100`, colors copied from the 4-stop preview of the chosen
  palette. A palette-only edit changes only step colors: preserve the existing number of steps, threshold boundaries,
  and `range`. Change existing bands only when the instruction requests it; explicit user thresholds take precedence
  over defaults.

```json
"metric": {
  "column": "cpu_pct",
  "format": { "type": "percent", "decimals": 1, "compact": true },
  "color": {
    "type": "dynamic",
    "range": "percentage",
    "steps": [
      { "gte": 0, "lt": 25, "color": "#24c292" },
      { "gte": 25, "lt": 50, "color": "#aee8d2" },
      { "gte": 50, "lt": 75, "color": "#ffc9c2" },
      { "gte": 75, "lte": 100, "color": "#f6726a" }
    ]
  }
}
```

## XY (line, area, bar)

### Design

- No axis titles: the panel title and column labels already convey meaning.
- Area series use a gradient fill, never a solid fill.
- Use areas only for one to three series. With more series, stacked or overlapping fills hide each other; use a line
  chart instead.
- Place the legend outside the plot, at the bottom. Lay it out as a list, except when it carries legend statistics,
  where a grid keeps the numbers aligned in columns. Hide it when it only repeats what is visible (a single series);
  show it when there are several series or when it carries legend statistics.
- Line charts use the "Elastic line optimized" palette, whose colors stay distinguishable as thin strokes. Other chart
  types keep the default palette. Add explicit per-series colors only when the user asks or when the same category must
  keep one color across charts.

### Config

- For horizontal bars, use `type: "bar_horizontal"` with `x` = category column and `y` = metric column. Example: "top OS
  by count as horizontal bar" → `type: "bar_horizontal", x: { column: "OS" }, y: [{ column: "Count" }]`. Do NOT put the
  metric on `x`.
- Hide axis titles with `title: { "visible": false }` on both the x and y axes; do not set axis title text.
- Area series: `styling: { "areas": { "fill": "gradient" } }` (Kibana 9.6+; omit `styling.areas` on older clusters,
  which render a solid fill).
- Legend: `legend: { "position": "bottom", "layout": { "type": "list" } }` with the default outside placement; do not
  set `placement`. Use `"layout": { "type": "grid" }` only when `legend.statistics` is set. The API defaults `layout` to
  `grid`, so set it explicitly on every xy chart. Always set `legend.visibility` explicitly. Use `"visible"` when the
  layer has a `breakdown_by` or more than one `y` column, and always when legend statistics are set. Use `"hidden"` for
  a single series whose name is already in the panel title or on the axis. The API fills an omitted `visibility` with
  `"hidden"`. It does not detect the series count the way the Lens editor does.
- Legend statistics: see [Series statistics versus measures](#series-statistics-versus-measures).
- Time series: always `"scale": "temporal"` on the x axis (see [Chart Types Reference](chart-types-reference.md)).
- Series count: `area` and `area_stacked` layers only when the query yields at most three series (one `y` column times
  the breakdown cardinality). Above that, use `line`.
- Line palette: on `line` layers with a `breakdown_by`, set
  `breakdown_by.color: { "mode": "categorical", "palette": "elastic_line_optimized", "mapping": [] }`. On `line` layers
  with several `y` columns and no breakdown, `y[].color` accepts only a static color, so give each column
  `color: { "type": "static", "color": "<hex>" }` with consecutive hex values from the `elastic_line_optimized` preview
  in the palette catalog. Bar and area layers keep the default palette.
- Other coloring: omit explicit `color` properties unless colors were requested; Lens applies its default palettes.
  Never introduce or switch to legacy palette ids (`eui_amsterdam`, `kibana_v7_legacy`, `elastic_brand_2023`).

```json
{
  "type": "xy",
  "title": "Log volume over time",
  "axis": {
    "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false }, "title": { "visible": false } },
    "y": { "title": { "visible": false } }
  },
  "legend": {
    "position": "bottom",
    "layout": { "type": "grid" },
    "visibility": "visible",
    "statistics": ["avg", "min", "max"]
  },
  "styling": { "areas": { "fill": "gradient" } },
  "layers": [
    {
      "type": "area",
      "data_source": {
        "type": "esql",
        "query": "FROM logs* | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS count = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
      },
      "x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" },
      "y": [{ "column": "count", "label": "Logs" }]
    }
  ]
}
```

## Heatmap

### Design

- Keep the default "Temperature" palette that Lens binds to the data; use a custom palette or thresholds only when the
  user asks.

### Config

- Omit `metric.color` or use `color: { "type": "auto" }`; generate explicit `steps` (5 bands, colors from the 5-stop
  preview) only when the user requests a custom palette or gives thresholds.

## Tag cloud

- Only for short strings (tags, status codes, country codes, browsers); never for long text. No panel title — the terms
  are the content.
- No coloring rules beyond the general [Color](#color) guidance.

## Region map

- Choose only when the data has region identifiers that join to map boundaries. No coloring rules beyond the general
  [Color](#color) guidance.

## Data table

### Design

- Color table values as badges, and only where color adds meaning (status, severity, magnitude). Do not color cell
  backgrounds or text unless the user asks.

### Config

Column color settings go on the column entry in `metrics[]` or `rows[]`:

- Prefer `"apply_color_to": "badge"`; avoid cell background or text coloring unless the user asks.
- Numeric columns: when coloring is useful, use `"apply_color_to": "badge"` with `color: { "type": "auto" }` so Lens
  computes stops from table data. Generate explicit 5-band `steps` only when the user asks for a palette or thresholds.
- Categorical (keyword/text) columns: when coloring is useful, use
  `color: { "mode": "categorical", "palette": "<palette id>", "mapping": [] }` so Lens assigns colors to actual values.
- NEVER apply categorical mapping to a numeric column or dynamic palette steps to a keyword column.

```json
"metrics": [{ "column": "error_rate", "format": { "type": "number", "decimals": 1, "suffix": "%" }, "apply_color_to": "badge", "color": { "type": "auto" } }],
"rows": [{ "column": "service", "apply_color_to": "badge", "color": { "mode": "categorical", "palette": "default", "mapping": [] } }]
```

## Pie and donut

### Design

- Use the default palette; per-slice or custom colors only when the user asks.
- Keep the category count small (ideally fewer than 7); above that, prefer a bar chart or table.

### Config

- Omit explicit `color` properties; Lens applies its default palette. Add colors only when the user explicitly requests
  them.
- Donuts: `"styling": { "donut_hole": "m" }` on a `pie`.

## Treemap, waffle, mosaic

- Follow the general [Color](#color) guidance: let Lens apply its default palette and add explicit colors only when the
  user asks or when a category must keep one color across charts.

## Color

### Design

- Add color only when it adds meaning: status colors for meaningful thresholds, intensity colors for magnitude, and one
  consistent color for the same category wherever it appears across charts. Neutral data with no useful color meaning
  stays uncolored.
- Choose palettes from the [Kibana palette catalog](color-palettes.md), never invented colors or legacy palettes:
  "Status" for threshold bands, "Temperature" for intensity, "Complementary" for divergence, "Negative"/"Positive" for
  adverse/favorable values, "Cool"/"Warm"/"Gray" for neutral magnitude, and a categorical palette for distinct
  categories: `elastic_line_optimized` on line charts, `default` elsewhere, `severity` when categories are severities.
- Thresholds are data values in the metric's own unit and scale. When only the colors change, keep the existing
  thresholds.
- Respect explicit user choices and meaningful existing color assignments. An off-palette color is not automatically
  wrong; do not assume an existing color was invented just because its history is unknown.
- Cross-chart consistency is your job: when a category (a service, a status code) appears in several panels, give it the
  same color in every panel's config.

### Config

#### Default policy

- Prefer Lens defaults for unknown-scale data: use `color: { "type": "auto" }` or omit `color` when Lens can calculate
  better thresholds at render time.
- Generate explicit numeric `steps` only when the chart-specific rules above allow it (metric bounded values, gauge
  bands) or when the user asks for a custom palette or exact thresholds.
- The chart-specific coloring rules above override this policy where they differ.

#### Coloring mode — choose by column type

- Numeric columns → `color: { "type": "auto" }` by default;
  `color: { "type": "dynamic", "range": "absolute" | "percentage", "steps": [...] }` only when explicit steps are
  allowed.
- Keyword / text columns → `color: { "mode": "categorical", "palette": "<palette id>", "mapping": [] }`.
- NEVER apply categorical mapping to a numeric column or dynamic palette steps to a keyword column.
- NEVER use the deprecated `type: "legacy_dynamic"`.

#### Dynamic steps — mechanics for when the rules call for explicit `steps`

- Pick exactly ONE gradient palette, following the design guidance on which palette fits which meaning.
- Use the step count the chart type calls for: 3 for metrics, 4 for gauges, 5 for heatmaps and tables. For a recolor of
  an existing chart, keep its current step count and copy the preview with that many stops.
- Every `steps[*].color` hex MUST come from the selected palette's preview line for that step count, exactly as written.
- Each step is `{ "gte": <lower, inclusive>, "lt": <upper, exclusive>, "color": "#hex" }`; the last step uses `lte`
  instead of `lt`. Steps must be continuous, and every step except the first needs `gte`.
- Step thresholds are data values, not display labels; keep them in the same unit and scale as the metric column. For
  rates, do not assume per-second thresholds unless the ES|QL query computes per-second values.
- Keep palette order by default; to reverse, reverse the `steps` colors yourself. There is no `reverse` field.

#### Categorical mapping — pick a palette by id

- Set `color: { "mode": "categorical", "palette": "<palette id>", "mapping": [] }` and let Lens auto-assign a distinct
  color per distinct value at render time.
- The `palette` value MUST be one of the categorical palette ids in the catalog, verbatim (`default`,
  `elastic_line_optimized`, `severity`).
- Leave `mapping: []` by default. Only define explicit `mapping[]` entries when the user names specific values to color,
  or when a category must keep one color across charts.
- When you do map explicit values, each entry is
  `{ "values": ["<value>"], "color": { "type": "color_code", "value": "#hex" } }`, drawing the hex from one of the
  catalog palettes.
chart-types-reference.md 13.8 KB
# Chart Types Reference

Complete schema reference for each supported chart type via the Kibana dashboards & visualizations API.

**Supported Chart Types:**

- `metric` — Single metric value
- `xy` — Line, area, bar charts
- `gauge` — Gauge visualization
- `heatmap` — Heatmap charts
- `tag_cloud` — Tag/word cloud
- `data_table` — Data tables
- `region_map` — Region/choropleth maps
- `pie`, `treemap`, `mosaic`, `waffle` — Partition charts (use `pie` with `styling.donut_hole` for donuts: `"s"`, `"m"`,
  or `"l"`)

## DataView Aggregation Operations

When using `data_view_reference` or `data_view_spec` datasets, the following operations are available:

| Operation            | Description                          | Requires Field |
| -------------------- | ------------------------------------ | -------------- |
| `count`              | Document count                       | No             |
| `average`            | Average value                        | Yes            |
| `sum`                | Sum of values                        | Yes            |
| `max`                | Maximum value                        | Yes            |
| `min`                | Minimum value                        | Yes            |
| `unique_count`       | Cardinality                          | Yes            |
| `median`             | Median value                         | Yes            |
| `standard_deviation` | Standard deviation                   | Yes            |
| `percentile`         | Percentile (with `percentile` param) | Yes            |
| `percentile_rank`    | Percentile rank (with `rank` param)  | Yes            |
| `last_value`         | Last value (with `time_field`)       | Yes            |
| `date_histogram`     | Time buckets (for x-axis)            | Yes            |
| `terms`              | Top values (for x-axis/breakdown)    | Yes            |

## Metric

Single metric value display. Uses a `metrics` (plural) array with `type: "primary"` or `type: "secondary"`.

**ES|QL:**

```json
{
  "type": "metric",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS count = COUNT()"
  },
  "metrics": [
    {
      "type": "primary",
      "column": "count"
    }
  ]
}
```

**dataView:**

```json
{
  "type": "metric",
  "data_source": { "type": "data_view_reference", "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247" },
  "metrics": [
    {
      "type": "primary",
      "operation": "count",
      "label": "Total Events"
    }
  ]
}
```

**Metric Item Properties:**

| Property    | Type   | Required | Description                                                     |
| ----------- | ------ | -------- | --------------------------------------------------------------- |
| `type`      | string | Yes      | `"primary"` or `"secondary"`                                    |
| `operation` | string | dataView | Aggregation name (for dataView only; not used with ES\|QL)      |
| `column`    | string | ES\|QL   | ES\|QL column name                                              |
| `field`     | string | dataView | Field name (required for dataView aggregations needing a field) |
| `label`     | string | No       | Display label                                                   |

**Metric Styling:** Styling is configured at the **config root level** (sibling to `type`, `data_source`, `metrics`),
not inside `metrics[]`. Uses `primary` and `secondary` sub-objects:

```json
{
  "type": "metric",
  "data_source": { ... },
  "metrics": [{ "type": "primary", "operation": "count" }],
  "styling": {
    "primary": {
      "position": "bottom",
      "labels": { "alignment": "left" },
      "value": { "sizing": "auto", "alignment": "right" }
    }
  }
}
```

> **Tip:** For ES|QL metrics in dashboards, avoid redundant labels by leaving the panel `title` empty (`""`) and
> aliasing the column name in ES|QL with backticks (e.g. ``STATS `Total Requests` = COUNT()`` and setting
> `"column": "Total Requests"`).
>
> **Trend background.** With `background_chart: { "type": "trend" }` the API adds a time bucket to the query when it
> generates the trendline layer. `FROM` queries need a `?_tstart` / `?_tend` filter; `TS` queries must not group by
> `BUCKET(@timestamp, ...)`, only `TBUCKET`. See the Metric section of the
> [chart design guidelines](chart-design.md#metric) for the full rules.

## XY Charts

Line, area, and bar charts. For ES|QL, the `data_source` goes **inside each layer**.

### Bar Chart

```json
{
  "type": "xy",
  "layers": [
    {
      "type": "bar",
      "data_source": {
        "type": "esql",
        "query": "FROM logs | STATS count = COUNT() BY status"
      },
      "x": { "column": "status" },
      "y": [{ "column": "count" }]
    }
  ]
}
```

### Line Chart (Time Series)

```json
{
  "type": "xy",
  "axis": {
    "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false } }
  },
  "layers": [
    {
      "type": "line",
      "data_source": {
        "type": "esql",
        "query": "FROM logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS count = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
      },
      "x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" },
      "y": [{ "column": "count" }]
    }
  ]
}
```

### Area Chart

```json
{
  "type": "xy",
  "axis": {
    "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false } }
  },
  "layers": [
    {
      "type": "area",
      "data_source": {
        "type": "esql",
        "query": "FROM metrics | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS avg_cpu = AVG(cpu) BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
      },
      "x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" },
      "y": [{ "column": "avg_cpu" }]
    }
  ]
}
```

### Multiple Y-Axis Values

```json
{
  "type": "xy",
  "axis": {
    "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false } }
  },
  "layers": [
    {
      "type": "line",
      "data_source": {
        "type": "esql",
        "query": "FROM logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS count = COUNT(), errors = COUNT(CASE(level == \"error\", 1, null)) BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
      },
      "x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" },
      "y": [
        { "column": "count", "label": "Total" },
        { "column": "errors", "label": "Errors" }
      ]
    }
  ]
}
```

### Split Series (Color by Field)

```json
{
  "type": "xy",
  "axis": {
    "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false } }
  },
  "layers": [
    {
      "type": "line",
      "data_source": {
        "type": "esql",
        "query": "FROM logs | WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS count = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend), host"
      },
      "x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" },
      "y": [{ "column": "count" }],
      "breakdown_by": { "column": "host" }
    }
  ]
}
```

**Layer Types:**

- `bar` — Vertical bars
- `bar_stacked` — Stacked bars
- `bar_percentage` — Percentage bars
- `bar_horizontal` — Horizontal bars
- `bar_horizontal_stacked` — Horizontal stacked bars
- `bar_horizontal_percentage` — Horizontal percentage bars
- `line` — Line chart
- `area` — Area chart
- `area_stacked` — Stacked area
- `area_percentage` — Percentage area

## Gauge

For ES|QL, reference the query output column directly. Do not pass `min`/`max`/`goal` for ES|QL gauges — the API injects
defaults. Do **not** include `operation` in `metric` — it is not a valid property for gauge and will be rejected.

```json
{
  "type": "gauge",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS success_rate = COUNT(CASE(TO_INTEGER(status) == 200, 1, null)) * 100.0 / COUNT()"
  },
  "metric": { "column": "success_rate" }
}
```

**Gauge Properties:**

| Property        | Type   | Required | Description        |
| --------------- | ------ | -------- | ------------------ |
| `metric.column` | string | Yes      | ES\|QL column name |

## Heatmap

```json
{
  "type": "heatmap",
  "data_source": {
    "type": "esql",
    "query": "FROM kibana_sample_data_logs | STATS count = COUNT() BY hour = DATE_EXTRACT(\"hour_of_day\", @timestamp), day = DATE_EXTRACT(\"day_of_week\", @timestamp)"
  },
  "x": { "column": "hour" },
  "y": { "column": "day" },
  "metric": { "column": "count" }
}
```

## Tag Cloud

Uses `tag_by` for the tag dimension and `metric` for the value.

```json
{
  "type": "tag_cloud",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS count = COUNT() BY keyword"
  },
  "tag_by": { "column": "keyword" },
  "metric": { "column": "count" }
}
```

## Datatable

For ES|QL, uses `metrics` and `rows` arrays. Each entry uses `{ column: "..." }`.

```json
{
  "type": "data_table",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS count = COUNT(), avg_bytes = AVG(bytes) BY host"
  },
  "metrics": [{ "column": "count" }, { "column": "avg_bytes" }],
  "rows": [{ "column": "host" }]
}
```

**For dataView**, the datatable uses aggregation operations:

```json
{
  "type": "data_table",
  "data_source": { "type": "data_view_reference", "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247" },
  "metrics": [{ "operation": "count" }, { "operation": "average", "field": "bytes" }],
  "rows": [
    {
      "operation": "terms",
      "fields": ["host.keyword"],
      "limit": 15,
      "rank_by": { "type": "metric", "metric_index": 0, "direction": "desc" }
    }
  ]
}
```

## Partition (Pie, Treemap, Mosaic, Waffle)

Partition charts display parts of a whole. Uses a flat structure (no `layers`) with `metrics` for the slice sizes and
`group_by` for the rings or groupings. The schema is identical for all partition types—simply change `"type": "pie"` to
`"treemap"`, `"mosaic"`, or `"waffle"`. To create a donut, use `"type": "pie"` with `"styling": { "donut_hole": "m" }`.
Valid `donut_hole` values are `"none"`, `"s"`, `"m"`, or `"l"`.

**ES|QL Example:**

```json
{
  "type": "pie",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS count = COUNT() BY os"
  },
  "metrics": [{ "column": "count" }],
  "group_by": [{ "column": "os" }]
}
```

## Region Map

```json
{
  "type": "region_map",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS count = COUNT() BY geo.country_iso_code"
  },
  "region": { "column": "geo.country_iso_code" },
  "metric": { "column": "count" }
}
```

## Common Patterns

### Renaming Columns for Clarity

```json
{
  "type": "metric",
  "data_source": {
    "type": "esql",
    "query": "FROM logs | STATS total_events = COUNT(), error_count = COUNT(CASE(level == \"error\", 1, null)) | EVAL error_rate = ROUND(error_count * 100.0 / total_events, 2)"
  },
  "metrics": [{ "type": "primary", "column": "error_rate" }]
}
```

### Time Bucketing

**Auto buckets (Recommended):**

Do **not** reassign the BUCKET result. Use the full expression as both the `BY` clause and the `column` reference, with
a `label` for display:

```esql
WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart | STATS count = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)
```

```json
"x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)", "label": "@timestamp" }
```

**Important:** Always set `"scale": "temporal"` on the x-axis for time series charts. Without it, Kibana treats the
bucket column as categorical text and renders unsorted, verbose timestamp strings instead of a proper multilevel time
axis.

```json
"axis": {
  "x": { "scale": "temporal", "domain": { "type": "fit", "rounding": false } }
}
```

**Hourly buckets:**

```esql
STATS count = COUNT() BY bucket = DATE_TRUNC(1 hour, @timestamp)
```

**Daily buckets:**

```esql
STATS count = COUNT() BY bucket = DATE_TRUNC(1 day, @timestamp)
```

**5-minute buckets:**

```esql
STATS count = COUNT() BY bucket = DATE_TRUNC(5 minutes, @timestamp)
```

### Number Formatting

Use the `format` property on metrics, y-axis columns, and gauge metrics to display values with proper units.

| Format     | Properties                                             | Example Output |
| ---------- | ------------------------------------------------------ | -------------- |
| `bytes`    | `{ "type": "bytes", "decimals": 0 }`                   | 5 KB, 19 KB    |
| `bits`     | `{ "type": "bits", "decimals": 1 }`                    | 40.2 kbit      |
| `number`   | `{ "type": "number", "decimals": 2, "compact": true }` | 5.75K          |
| `percent`  | `{ "type": "percent", "decimals": 1 }`                 | 42.5%          |
| `duration` | `{ "type": "duration", "from": "ms", "to": "auto" }`   | 1.5 s          |
| `custom`   | `{ "type": "custom", "pattern": "0,0.00" }`            | 5,750.16       |

All formats accept an optional `"suffix"` (e.g., `" /s"` for rate displays). Duration `from` must be one of the short
unit codes `ps`, `ns`, `us`, `ms`, `s`, `min`, `h`, `d`, `w`, `mo`, `y`, matching how the field is stored; `to` is
`auto`, `auto-approximate`, or one of the standard units. See
[Chart Design Guidelines](chart-design.md#general-rules-all-chart-types) for when to apply each format.

**Percent formatting:** Two options depending on the value range. `"type": "percent"` expects a decimal fraction (0.425
→ 42.5%). `{ "type": "number", "decimals": 1, "suffix": "%" }` works when the value is already a whole-number percentage
(42.5 → 42.5%).

**dataView operation example:**

```json
{ "operation": "average", "field": "bytes", "format": { "type": "bytes", "decimals": 0 } }
```

**ES|QL column example:**

```json
{ "column": "avg_bytes", "format": { "type": "bytes", "decimals": 0 } }
```

**Gauge metric example:**

```json
"metric": { "operation": "max", "field": "bytes", "format": { "type": "bytes", "decimals": 0 } }
```

### Filtering in ES|QL

```esql
FROM logs
| WHERE @timestamp > NOW() - 24 hours AND level == "error"
| STATS count = COUNT() BY host
```
color-palettes.md 3.8 KB
# Kibana Palette Catalog

The palettes Kibana's Lens palette pickers offer, with their ids and light-theme color stops. Generated from Kibana's
own palette definitions (`@kbn/palettes`, Kibana main branch, September 2026). Legacy palettes are excluded so that
generated charts use the current palette set unless the user asks otherwise.

Use this catalog whenever you write explicit colors: every hex value in a `steps[]` entry or a categorical `mapping[]`
MUST be copied verbatim from a preview line below. Never invent colors. When judging whether an existing color belongs
to a palette, compare the saved hex values, not a screenshot. See [Color](chart-design.md#color) for when color is
appropriate and which palette fits which meaning.

## Gradient palettes

For threshold bands and magnitude. Charts sample a palette at the number of bands they use: pick the preview line
matching your step count (3 bands for metrics, 4 for gauges, 5 for heatmaps and tables) and copy those hex values in
order. To reverse a palette, reverse the order of the `steps` colors yourself — there is no `reverse` field.

| Name          | Id              | Meaning                               |
| ------------- | --------------- | ------------------------------------- |
| Status        | `status`        | Threshold bands: good → warning → bad |
| Temperature   | `temperature`   | Intensity / cold-to-hot magnitude     |
| Complementary | `complementary` | Divergence around a midpoint          |
| Negative      | `red`           | Adverse values (higher is worse)      |
| Positive      | `green`         | Favorable values (higher is better)   |
| Cool          | `cool`          | Neutral magnitude                     |
| Warm          | `warm`          | Neutral magnitude                     |
| Gray          | `gray`          | Neutral magnitude                     |

### 3-stop previews (metric status bands)

- Status: #24c292, #fcd883, #f6726a
- Temperature: #61a2ff, #ebeff5, #f6726a
- Complementary: #61a2ff, #f6f9fc, #eaae01
- Negative: #fdcdc9, #fda198, #f6726a
- Positive: #bde8d8, #7fd5b4, #24c292
- Cool: #c4daff, #95beff, #61a2ff
- Warm: #ffcac3, #fe9f96, #f6726a
- Gray: #a2aec4, #596883, #1d2a3e

### 4-stop previews (gauge bands)

- Status: #24c292, #aee8d2, #ffc9c2, #f6726a
- Temperature: #61a2ff, #cfe1ff, #ffd4cf, #f6726a
- Complementary: #61a2ff, #accefe, #f0d47f, #eaae01
- Negative: #fcd8d6, #feb7b0, #fc968d, #f6726a
- Positive: #cbece1, #9fdfc6, #6dd1ac, #24c292
- Cool: #cfe1ff, #adccff, #89b7ff, #61a2ff
- Warm: #ffd5cf, #ffb5ac, #fc948b, #f6726a
- Gray: #b6c0d3, #7b8aa4, #485872, #1d2a3e

### 5-stop previews (heatmap and table bands)

- Status: #24c292, #aee8d2, #fcd883, #ffc9c2, #f6726a
- Temperature: #61a2ff, #cfe1ff, #f6f9fc, #ffd4cf, #f6726a
- Complementary: #61a2ff, #accefe, #f6f9fc, #f0d47f, #eaae01
- Negative: #fcdfdd, #fec4bf, #feaaa2, #fb8f86, #f6726a
- Positive: #d4efe6, #b1e4d1, #8cd9bb, #62cea6, #24c292
- Cool: #d6e5ff, #bad5ff, #9fc4ff, #82b3ff, #61a2ff
- Warm: #ffdbd6, #ffc2ba, #ffa89f, #fb8d84, #f6726a
- Gray: #c2cbdb, #92a0b8, #667690, #3f4e67, #1d2a3e

## Categorical palettes

For distinct categories. Configs reference the **id**, not the name, in
`color: { mode: "categorical", palette: "<id>", mapping: [] }`. The previews show the first five colors of each palette.

- `default` (Elastic, 10 colors): #16C5C0, #A6EDEA, #61A2FF, #BFDBFF, #EE72A6
- `elastic_line_optimized` (Elastic, line optimized, 10 colors): #16C5C0, #61A2FF, #EE72A6, #EAAE01, #F6726A
- `severity` (Severity, 6 colors): #24C292, #B5E5F2, #FCD883, #FF995E, #EE4C48

## Excluded legacy palettes

Never introduce or switch a chart to these ids: `eui_amsterdam` (Kibana 7.0), `kibana_v7_legacy` (Kibana 4.0),
`elastic_brand_2023` (Elastic classic). An existing chart that already uses one is not automatically wrong — leave it
unless the user asks for a recolor.
dashboard-api-reference.md 8.9 KB
# Dashboard API Reference

The Dashboards API provides CRUD endpoints for managing Kibana dashboards.

## Prerequisites

**Version Requirement:** Kibana 9.4+ (SNAPSHOT)

## API Versioning

All requests require the `Elastic-Api-Version: 2023-10-31` header.

## Endpoints

### Get Dashboard

```http
GET kbn:/api/dashboards/{id}
```

**Response:**

```json
{
  "id": "dashboardsApiTest",
  "data": {
    "title": "Dashboards API Test",
    "panels": [
      {
        "grid": { "y": 0, "x": 0, "w": 9, "h": 4 },
        "config": { "content": "## Dashboard from API!" },
        "id": "ee5f034d-ae54-4ac5-b437-93ac5db0363a",
        "type": "markdown"
      }
    ],
    "time_range": { "from": "now-2d", "to": "now" }
  },
  "meta": {
    "managed": false,
    "updated_at": "2025-12-08T17:33:48.177Z",
    "updated_by": "user_id",
    "version": "WzMwLDFd",
    "created_at": "2025-12-08T17:33:48.177Z",
    "created_by": "user_id"
  },
  "spaces": ["default"]
}
```

### Create Dashboard

```http
POST kbn:/api/dashboards
```

**Request Body:**

```json
{
  "title": "My Dashboard",
  "panels": [ ... ],
  "time_range": { "from": "now-24h", "to": "now" }
}
```

The request body is flat — `title`, `panels`, and `time_range` go at the root level. Dashboard IDs are auto-generated by
the API. `POST` does not accept an `id` parameter. To create-or-update, use `PUT /api/dashboards/{id}`.

**Properties:**

| Property     | Required | Description        |
| ------------ | -------- | ------------------ |
| `title`      | Yes      | Dashboard title    |
| `panels`     | Yes      | Array of panels    |
| `time_range` | No       | Default time range |

**Response** wraps the definition in a `data` envelope:

```json
{
  "id": "auto-generated-id",
  "data": { "title": "My Dashboard", "panels": [...] },
  "meta": { ... },
  "spaces": ["default"]
}
```

### Update Dashboard (Upsert)

`PUT` supports upsert — it creates the dashboard if it does not exist, or updates it if it does.

```http
PUT kbn:/api/dashboards/{id}
```

**Request Body:**

```json
{
  "title": "Updated Title",
  "panels": [ ... ],
  "time_range": { "from": "now-7d", "to": "now" }
}
```

### Delete Dashboard

```http
DELETE kbn:/api/dashboards/{id}
```

**Response:** Empty on success.

## Space-Specific Endpoints

To operate on dashboards in a specific space, use the space-prefixed URL:

```http
GET kbn:/s/{space-id}/api/dashboards/{id}
POST kbn:/s/{space-id}/api/dashboards
PUT kbn:/s/{space-id}/api/dashboards/{id}
DELETE kbn:/s/{space-id}/api/dashboards/{id}
```

## Dashboard Request Body Schema

| Property           | Type   | Required | Description                |
| ------------------ | ------ | -------- | -------------------------- |
| `title`            | string | Yes      | Dashboard title            |
| `panels`           | array  | Yes      | Array of panel definitions |
| `time_range`       | object | No       | Default time range         |
| `description`      | string | No       | Dashboard description      |
| `refresh_interval` | object | No       | Auto-refresh settings      |

### time_range Object

```json
{
  "from": "now-24h",
  "to": "now"
}
```

Supports relative (`now-1h`, `now-7d`) and absolute (`2024-01-01T00:00:00Z`) formats.

## Panel Schema

### Common Panel Properties

| Property | Type   | Required | Description                  |
| -------- | ------ | -------- | ---------------------------- |
| `type`   | string | Yes      | Panel type (see below)       |
| `id`     | string | Yes      | Unique panel identifier      |
| `grid`   | object | Yes      | Grid position and size       |
| `config` | object | Yes      | Panel-specific configuration |

### grid Object

```json
{
  "x": 0,
  "y": 0,
  "w": 24,
  "h": 15
}
```

| Property | Description               |
| -------- | ------------------------- |
| `x`      | Column position (0-47)    |
| `y`      | Row position              |
| `w`      | Width in columns (max 48) |
| `h`      | Height in rows            |

## Panel Types

Panel types correspond to embeddable type identifiers registered in Kibana.

### markdown (Markdown Text)

```json
{
  "type": "markdown",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 48, "h": 4 },
  "config": {
    "content": "## Markdown content here"
  }
}
```

### vis (Visualization)

```json
{
  "type": "vis",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 24, "h": 15 },
  "config": {
    "ref_id": "visualization-id"
  }
}
```

Or with inline definition (recommended — properties are at config root, not nested under `attributes`):

```json
{
  "type": "vis",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 24, "h": 15 },
  "config": {
    "type": "metric",
    "data_source": {
      "type": "esql",
      "query": "FROM logs | STATS count = COUNT()"
    },
    "metrics": [{ "type": "primary", "column": "count" }]
  }
}
```

### links (Dashboard Links)

> **Note:** The `links` panel type may not be available in all Kibana versions.

```json
{
  "type": "links",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 8, "h": 4 },
  "config": {
    "links": [
      { "type": "dashboard", "destination": "dashboard-id-1" },
      { "type": "dashboard", "destination": "dashboard-id-2" }
    ]
  }
}
```

### map (Maps)

> **Note:** The `map` panel type may not be available in all Kibana versions.

```json
{
  "type": "map",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 24, "h": 18 },
  "config": {
    "ref_id": "map-object-id"
  }
}
```

### discover_session (Saved Search)

```json
{
  "type": "discover_session",
  "id": "unique-id",
  "grid": { "x": 0, "y": 0, "w": 48, "h": 15 },
  "config": {
    "ref_id": "saved-search-id"
  }
}
```

## Example: Complete Dashboard

```json
{
  "title": "Operations Dashboard",
  "panels": [
    {
      "type": "markdown",
      "id": "header",
      "grid": { "x": 0, "y": 0, "w": 48, "h": 3 },
      "config": { "content": "# Operations Overview" }
    },
    {
      "type": "vis",
      "id": "total-events",
      "grid": { "x": 0, "y": 3, "w": 12, "h": 8 },
      "config": {
        "type": "metric",
        "data_source": {
          "type": "esql",
          "query": "FROM logs | STATS count = COUNT()"
        },
        "metrics": [{ "type": "primary", "column": "count" }]
      }
    },
    {
      "type": "vis",
      "id": "events-by-host",
      "grid": { "x": 12, "y": 3, "w": 36, "h": 15 },
      "config": {
        "type": "xy",
        "layers": [
          {
            "type": "bar",
            "data_source": {
              "type": "esql",
              "query": "FROM logs | STATS count = COUNT() BY host"
            },
            "x": { "column": "host" },
            "y": [{ "column": "count" }]
          }
        ]
      }
    }
  ],
  "time_range": { "from": "now-24h", "to": "now" }
}
```

## Copying Dashboards

1. Call `GET kbn:/api/dashboards/{id}` on the source cluster.
2. Edit the exported definition (change title, panels, or id as needed).
3. Call `PUT kbn:/api/dashboards/{id}` on the destination cluster.

**Note:** Cannot move a dashboard with the same id between spaces in the same cluster without deleting the origin first.

## Common Issues

| Error                   | Solution                                                                     |
| ----------------------- | ---------------------------------------------------------------------------- |
| "401 Unauthorized"      | Verify credentials and Kibana privileges                                     |
| "404 Not Found"         | Verify dashboard/visualization ID exists                                     |
| "409 Conflict"          | Dashboard/viz with that ID already exists; delete first or use update        |
| "id not allowed in PUT" | Remove `id` and `spaces` from update body                                    |
| Schema validation error | For ES\|QL: ensure column names match query output; use `{ column: 'name' }` |
| ES\|QL column reference | ES\|QL uses `{ column: 'col' }` to reference query output columns            |
| Metric chart structure  | Metric chart requires `metrics` (plural) array: `[{ type: 'primary', ... }]` |
| Tagcloud bucketing      | Tagcloud requires `tag_by` for the tag dimension                             |
| Datatable structure     | ES\|QL data_table requires `metrics` + `rows` arrays                         |
| XY chart fails          | Put `data_source` inside each layer (for both dataView and ES\|QL)           |
| Heatmap property names  | Heatmap uses `x`, `y`, `metric` for axes and value                           |
| XY axis config          | Use `axis` (singular); `y` for left axis, `y2` for right axis                |
| ref_id panels missing   | Prefer inline definitions (properties in `config`) over `ref_id`             |

## Testing from Dev Tools

Prefix requests with `kbn:` and include version header:

```text
GET kbn:/api/dashboards/my-dashboard
{
  "headers": { "Elastic-Api-Version": "2023-10-31" }
}

POST kbn:/api/dashboards
{
  "headers": { "Elastic-Api-Version": "2023-10-31" },
  "body": { ... }
}
```
dashboard-design.md 14.1 KB
# Dashboard Design Guidelines

How to compose, structure, and lay out a dashboard so it reads well. These rules apply to every dashboard you create or
update through `PUT kbn:/api/dashboards/{id}`. Chart-level rules (chart type choice, titles, units, legends, colors)
live in [Chart Design Guidelines](chart-design.md).

## Composition

A well-composed dashboard orders panels as **summary metrics → trends → breakdowns and distributions**:

1. **Consider a markdown panel when it adds value** — to set context about what the dashboard monitors, data sources, or
   important notes. Not every dashboard needs one. Never use a markdown panel as a dashboard title.
2. **Lead with high-level metrics** (metric or gauge panels): total counts, averages, key performance indicators that
   give an at-a-glance summary.
3. **Follow with time-series trends** (xy line/area panels): how the key metrics change over time.
4. **Follow with breakdowns and distributions** (xy bar, heatmap, tag cloud, partition charts, or ranking tables): top-N
   rankings, categorical splits, and density views. A table of top countries belongs here, not with summary metrics.
5. **Include as many panels as are valuable for the underlying data and user intent.** Let the richness and diversity of
   the available fields drive the panel count instead of a fixed numeric target.
6. **Every panel should serve a clear purpose.** Do not add panels just to fill space, but do not artificially limit the
   dashboard when more panels would provide genuine insight.

When the user's request is vague (for example "create a dashboard for my logs"), inspect the index mapping thoroughly
(`GET /{index}/_mapping`) and compose a rich dashboard that covers the breadth of the available data — overview metrics,
time-series trends, breakdowns, and distributions. Let the fields drive the panel count rather than defaulting to a
minimal set.

### Primary time series

Before writing panels, pick one or two **primary time-series xy charts** — the overview trend that matches the dashboard
title or intent. On a new dashboard, give at least one and at most two of them legend statistics (avg/min/max shown in
the legend). Skip this for categorical bar charts and for charts whose measure is already an `AVG`/`MIN`/`MAX` of a
field. See [Series statistics](chart-design.md#series-statistics-versus-measures) for how to express it.

## Titles and descriptions

- Every dashboard MUST have a non-empty `title`. For a new dashboard also set `description`. If an existing dashboard's
  title is empty or a placeholder such as `"User Dashboard"`, invent a title from its contents.
- Derive the dashboard title, description, section titles, panel titles, and markdown text from what the queries
  actually measure and the indices they read — not from the existing dashboard name or an assumed domain. Rename
  anything misleading.
- Panel titles must be self-explanatory and exhaustive so axis titles become unnecessary. Never duplicate information
  across the panel title, axis titles, and metric labels. Charts that display their information within themselves
  (metric, gauge, tag cloud, waffle) get no panel title at all.

## Sections

Sections are collapsible groups of panels. In the API a section is an entry of the top-level `panels` array with a
`title`, `collapsed`, a `grid` holding only `y`, and its own nested `panels`. Each section's panels start again at
`y: 0`, and the next section's outer `y` is the previous one plus 1:

```json
"panels": [
  {
    "title": "Key metrics",
    "collapsed": false,
    "grid": { "y": 0 },
    "panels": [
      {
        "type": "vis",
        "id": "total-requests",
        "grid": { "x": 0, "y": 0, "w": 12, "h": 5 },
        "config": {
          "type": "metric",
          "data_source": { "type": "esql", "query": "FROM logs* | STATS `Total requests` = COUNT()" },
          "metrics": [{ "type": "primary", "column": "Total requests" }]
        }
      }
    ]
  },
  {
    "title": "Trends",
    "collapsed": false,
    "grid": { "y": 1 },
    "panels": [
      { "type": "vis", "id": "requests-over-time", "grid": { "x": 0, "y": 0, "w": 48, "h": 10 }, "config": { "type": "xy", "...": "..." } }
    ]
  }
]
```

A complete dashboard built this way, with three sections, ES|QL panels, and ES|QL-sourced controls, is in
[assets/dashboard-esql.json](../assets/dashboard-esql.json), with a data-view counterpart in
[assets/dashboard-data-view.json](../assets/dashboard-data-view.json).

### When to use sections

- Keep small dashboards flat when a single sequence of panels is easy to scan.
- Use sections to separate summary metrics, trends, and breakdowns in that order. Each section must contain only panels
  matching its purpose: a "Key metrics" section contains summary metric/gauge panels, not time-series charts or ranking
  tables.
- Use per-domain sections when they make the dashboard clearer; keep summary metrics → trends → breakdowns ordered
  within each domain.
- Prefer sections for larger dashboards, especially when there are roughly 6 or more visualization panels or when the
  layout would otherwise feel long and hard to navigate.
- Do not add sections only for decoration. Use them when they make the dashboard structure clearer.
- Leave `collapsed: false` unless the user asks for collapsed sections; collapsed panels are not rendered until
  expanded.

## Controls

Controls are interactive filters pinned above the dashboard that let users explore data without editing queries. They
live in the root `pinned_panels` array of the dashboard body:

```json
"pinned_panels": [
  {
    "type": "options_list_control",
    "width": "medium",
    "grow": true,
    "config": {
      "title": "Service",
      "data_view_id": "<data view id>",
      "field_name": "service.name"
    }
  }
]
```

**When building a new dashboard from scratch**, proactively add 3–5 dropdown controls for the most useful categorical
fields. Pick fields that appear in panel `BY` / `WHERE` clauses and prefer low-cardinality keyword fields (for example
`service.name`, `host.name`, `env`, `region`, `kubernetes.namespace`, `http.response.status_code`). Avoid
high-cardinality identifiers (trace IDs, request IDs, UUIDs).

Do not add controls to dashboards already scoped to a single entity (one host, one service, and so on).

**Control types:**

- `options_list_control` — dropdown for categorical / keyword fields. The most common type (95% of cases).
- `range_slider_control` — numeric range slider. Add sparingly, only when filtering by a numeric threshold is useful
  across multiple panels (for example `latency`, `bytes`, `duration`).
- `time_slider_control` — global time sub-range picker. Add at most one per dashboard, only when time-range narrowing
  within the global window is useful. Its `config` can be `{}`.

**Where the options come from.** An `options_list_control` lists its values from a data view field or from an ES|QL
query:

- Data view: `config.data_view_id` and `config.field_name`. Look the data view up with `GET kbn:/api/data_views`; if
  none covers the index, create one with `POST kbn:/api/data_views/data_view` and a body such as
  `{ "data_view": { "title": "logs-*", "timeFieldName": "@timestamp" } }`.
- ES|QL (Kibana 9.5+): `config.values_source: "esql"` and `config.esql_query`. No data view is needed. End the query
  with `STATS BY <field>` so it returns one column of distinct values, and use the same field name the panel queries
  filter on. On 9.4 use the data view form above.

On a dashboard whose panels are all ES|QL, prefer the ES|QL source so the dashboard does not depend on a data view that
may not exist.

```json
"pinned_panels": [
  {
    "type": "options_list_control",
    "width": "medium",
    "grow": true,
    "config": {
      "title": "Host",
      "values_source": "esql",
      "esql_query": "FROM metrics-* | STATS BY host.name",
      "selected_options": []
    }
  }
]
```

**Required fields per control:**

- `type`: one of the three above.
- `options_list_control`: `config.data_view_id` and `config.field_name`, or `config.values_source: "esql"` and
  `config.esql_query`.
- `range_slider_control`: `config.data_view_id` and `config.field_name`.
- `config.title` (optional, `options_list_control` and `range_slider_control` only): human-readable label shown above
  the control (for example `"Service"`).

**Defaults:** `width: "medium"`, `grow: true` (fills available horizontal space). Override only if the user asks.

**Removing controls:** drop the entry from `pinned_panels` and `PUT` the full body back.

## Panel layout

The dashboard uses a **48-column grid**. On a 16:9 screen, roughly **20–24 rows** are visible without scrolling. Aim for
**8–12 panels above the fold**.

Every panel requires `grid: { x, y, w, h }`. The origin `(0, 0)` is the top-left corner.

### Grid sizes by chart type

Use these sizes — **do not make metric or gauge panels full-width**:

| Panel                     | Width `w`   | Height `h` | Notes                                                                  |
| ------------------------- | ----------- | ---------- | ---------------------------------------------------------------------- |
| Metric                    | 6, 8, or 12 | 5–6        | Single-number panels — keep them **small**. Fit 4–8 per row.           |
| Gauge                     | 12          | 8          | Up to 4 per row.                                                       |
| XY (line / area / bar)    | 24          | 10         | Use full-width (`w: 48`) only for the primary time series.             |
| Heatmap                   | 24          | 10         | Needs height for the color matrix.                                     |
| Tag cloud                 | 24          | 10         |                                                                        |
| Pie / donut               | 12          | 10         |                                                                        |
| Treemap / waffle / mosaic | 24          | 10         |                                                                        |
| Markdown                  | 24–48       | 4–9        | Size based on content length and layout needs — not always full-width. |
| Data table                | 24–48       | 12–16      | Prefer full-width so columns are readable.                             |

Metric rows: 8 metrics → each `w: 6, h: 5`; 6 metrics → each `w: 8, h: 5`; 4 metrics → each `w: 12, h: 5`.

Prefer `w` values that divide 48 evenly: **6, 8, 12, 24, 48**.

### Grid packing rules

- **Automatic upward movement:** Kibana moves each panel upward at its current `x` until another panel or the top of its
  grid blocks it. A larger `y` does not preserve empty space above a panel or guarantee row alignment. Use sections, not
  blank rows, to separate semantic groups.
- **Eliminate dead space:** Always calculate the bottom edge (`y + h`) of every panel. When starting a new row or
  placing panels below a row, set the new row's `y` to **previous row's `y + max(h)`** across all panels in that row —
  do not use only one neighbor's `y + h`.
- **Align row heights:** If multiple panels are placed side-by-side in a row (sharing the same `y`), they should have
  the exact same height (`h`). If they do not, you must fill the resulting empty vertical space before placing the next
  full-width panel.

### Positioning rules

Always set `x` and `y` so panels tile with **no gaps**:

1. **Fill rows left to right.** Start at `x: 0`. The next panel's `x` = previous panel's `x + w`. When a panel would
   exceed column 48, start a new row.
2. **New row `y`** = previous row's `y + max(h)` of all panels in that row.
3. **Same `h` per row** when possible, so rows align cleanly.
4. Panels' `x + w` must never exceed 48.
5. **When updating a dashboard**, inspect the existing panels' `grid` from the `GET` response. If there is empty space
   (a gap where a panel was removed, or unused columns beside a tall panel), place the new panel in that gap instead of
   appending below. Choose `w` and `h` to fit the available space.
6. **Markdown panels** use an explicit `grid` like any other panel. Size based on content length (`w: 24–48, h: 4–9`)
   and account for their height when positioning subsequent panels.

### Reflow after layout changes

- After resizing, moving, or removing panels, choose final sizes first, then recalculate positions across the affected
  layout, including panels whose sizes did not change. Pack rows using the rules above; do not keep old coordinates that
  leave gaps. Reflow each section separately.
- Update existing panels in place (keep their `id`). Before sending the `PUT`, check the planned coordinates for
  avoidable gaps, overlaps, and grid bounds.

### Section grid rules

- Each section has its own coordinate space. Panels nested under a section's `panels` are section-relative: each section
  starts at `y: 0`. The same 48-column grid and sizing guidance apply within each section.
- A section occupies exactly one row in the outer dashboard grid. When placing anything after a section, the next outer
  `y` is `section.grid.y + 1` (not the sum of the internal panel heights).
- Internal panel heights affect layout inside the section only; they do not increase the section's outer-grid height.
- When mixing top-level panels and sections, compute outer `y` sequentially: top-level panels advance by `y + h`,
  sections advance by `y + 1`.
- Top-level panels and sections share the same outer grid. A top-level panel placed at the same `y` as a section
  collides with it and is pushed **below** the section. Because `PUT` replaces the whole `panels` array, insert a panel
  above a section by renumbering the outer `y` of the section and everything after it in the body you send.

### Example: 4 KPI metrics + 2 time-series charts + 1 breakdown bar chart

```text
metric  (x:0,  y:0,  w:12, h:5)
metric  (x:12, y:0,  w:12, h:5)
metric  (x:24, y:0,  w:12, h:5)
metric  (x:36, y:0,  w:12, h:5)
xy-line (x:0,  y:5,  w:24, h:10)
xy-line (x:24, y:5,  w:24, h:10)
xy-bar  (x:0,  y:15, w:48, h:10)
```

### Example: the same dashboard with sections

```text
section "Key metrics"   (outer y:0)
  metric  (x:0,  y:0, w:12, h:5) … metric (x:36, y:0, w:12, h:5)
section "Trends"        (outer y:1)
  xy-line (x:0,  y:0, w:24, h:10)   xy-line (x:24, y:0, w:24, h:10)
section "Breakdowns"    (outer y:2)
  xy-bar  (x:0,  y:0, w:48, h:10)
```
lens-api-reference.md 3.2 KB
# Lens Visualizations API Reference

The Visualizations API provides CRUD endpoints for standalone Lens library items (Kibana 9.4+).

## Endpoints

### List Visualizations

```http
GET kbn:/api/visualizations?query=&page=&per_page=
```

| Parameter  | Type   | Description                     |
| ---------- | ------ | ------------------------------- |
| `query`    | string | Search query                    |
| `page`     | number | Page number (default: 1)        |
| `per_page` | number | Results per page (default: 100) |

### Get Visualization

```http
GET kbn:/api/visualizations/{id}
```

### Create Visualization

```http
POST kbn:/api/visualizations
```

`POST` auto-generates an id. Send the definition without an id field.

### Update Visualization (Upsert)

```http
PUT kbn:/api/visualizations/{id}
```

`PUT` creates the visualization when the id does not exist.

### Delete Visualization

```http
DELETE kbn:/api/visualizations/{id}
```

## Response Envelope

Single-item responses wrap the definition:

```json
{
  "id": "uuid",
  "data": { "type": "metric", "data_source": { ... }, "metrics": [ ... ] },
  "meta": {
    "created_at": "ISO timestamp",
    "updated_at": "ISO timestamp",
    "managed": false
  }
}
```

List responses return `{ "data": [ ... ], "meta": { "page", "per_page", "total" } }`.

## Common Properties

| Property                | Type    | Description                               |
| ----------------------- | ------- | ----------------------------------------- |
| `type`                  | string  | Chart type (required)                     |
| `data_source`           | object  | Data source configuration (required)      |
| `title`                 | string  | Display title                             |
| `sampling`              | number  | Sampling rate 0–1 (default: 1)            |
| `ignore_global_filters` | boolean | Ignore dashboard filters (default: false) |

## Dataset Configuration

### ES|QL Dataset

Use when the user requests ES|QL. The API persists a Lens saved object backed by a text-based ES|QL datasource.

```json
{
  "data_source": {
    "type": "esql",
    "query": "FROM logs* | STATS count = COUNT()"
  }
}
```

Reference result columns with `{ "column": "count" }` on metrics or layer axes — not `operation: "count"`.

### Data View Dataset

```json
{
  "data_source": {
    "type": "data_view_reference",
    "ref_id": "90943e30-9a47-11e8-b64d-95841ca0b247"
  }
}
```

Use aggregation operations such as `count`, `average`, `sum`, `terms`, and `date_histogram` on metrics and axes.

### Index Pattern Dataset

```json
{
  "data_source": {
    "type": "data_view_spec",
    "index_pattern": "logs-*",
    "time_field": "@timestamp"
  }
}
```

## Metric Example (ES|QL)

```json
{
  "type": "metric",
  "title": "Total Requests",
  "data_source": {
    "type": "esql",
    "query": "FROM logs* | STATS count = COUNT()"
  },
  "metrics": [{ "type": "primary", "column": "count" }]
}
```

## Error Responses

| Code | Meaning                                   |
| ---- | ----------------------------------------- |
| 400  | Schema validation failure                 |
| 401  | Authentication required                   |
| 404  | Visualization not found                   |
| 409  | Conflict on create when id already exists |

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE