Skip to content

Commit

Permalink
lens config builder docs (elastic#177993)
Browse files Browse the repository at this point in the history
  • Loading branch information
ppisljar authored Mar 12, 2024
1 parent 004a160 commit 3401d3d
Show file tree
Hide file tree
Showing 16 changed files with 1,095 additions and 0 deletions.
29 changes: 29 additions & 0 deletions dev_docs/lens/breakdown.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
### `breakdown`

The `breakdown` configuration within the Lens Config Builder API allows developers to define how data should be segmented or aggregated in their visualizations.

#### Types of Breakdown Configurations

The `breakdown` configuration in case of using ES|QL or Datatable as a datasource just takes in the field name to use as a breakdown.

When using index as a datasource, breakdown can still be a field name, in which case lens will try to choose the most appropriate option, or it could be one of the following:

1. **Top Values (`LensBreakdownTopValuesConfig`):**
- Breaks down data based on the top occurring values for a specified field.
- Attributes include `field` (the field to break down by) and `size` (the number of top values to display).
- Ideal for pie charts, tag clouds, or any visualization where highlighting the most common or significant categories is beneficial.

2. **Date Histogram (`LensBreakdownDateHistogramConfig`):**
- Segments data over time using a specified date field.
- Attributes include `field` (the date field for the histogram), and `minimumInterval` (the smallest interval to use, e.g., `1M` for monthly).
- Useful for time series data, showing trends over time in line charts, area charts, etc.

3. **Intervals (`LensBreakdownIntervalsConfig`):**
- Divides data into intervals based on a numeric field.
- Attributes include `field` (the numeric field to create intervals from) and `granularity` (the interval size).
- Applicable for histograms or any visualization that benefits from numeric range segmentation.

4. **Filters (`LensBreakdownFiltersConfig`):**
- Allows for custom segmentation of data based on a collection of Elasticsearch filters.
- Attributes include an array of `filters`, each with a `label` (optional) and a `filter` string defining the filter query.
- Offers maximum flexibility in data segmentation, suitable for creating comparative visualizations across custom-defined segments.
82 changes: 82 additions & 0 deletions dev_docs/lens/config_api.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
---
id: kibDevLensConfigAPI
slug: /kibana-dev-docs/lens/config-builder
title: Lens Config Builder API Documentation
description: Lens Config Builder API Documentation
date: 2024-03-04
tags: ['kibana', 'dev', 'lens', 'introduction']
---

## Introduction

The Lens Config Builder API provides a streamlined and flexible interface for developers to construct and integrate Lens configurations within their applications. Lens, as a powerful visualization tool in Kibana, enables users to create, visualize, and analyze data in diverse and complex ways. This API aims to simplify the process of generating these visualizations programmatically, allowing for dynamic and customizable integration points with Lens. By abstracting the complexities of Lens configuration details, developers can focus on delivering rich data visualization experiences tailored to their application's needs.

```
import LensConfigBuilder, LensConfig from '@kbn/lens-embeddable-utils/config_builder';
const config: LensConfig = {
chartType: 'metric',
title: 'my metric chart',
dataset: { esql: 'from my_index | stats sum=sum(my_field)'}
value: 'sum'
}
const configBuilder = new LensConfigBuilder(lensFormulaAPI, dataViewsAPI);
const lensConfig = configBuilder(config, {
timeRange: { from: 'now-30d', to: 'now', type: 'relative' },
embeddable: true,
}
<LensEmbeddable ...lensConfig />
```

## Main Interface

### LensConfigBuilder

The `LensConfigBuilder` class is the central interface of the API, facilitating the creation of various Lens chart types through a unified and simplified process. It leverages predefined chart configurations and integrates seamlessly with essential Kibana services, such as formula calculations and data view management, to produce either Lens attributes or embeddable inputs based on the developer's requirements.

#### Constructor

The constructor requires two parameters:

- `formulaAPI`: An instance of `FormulaPublicApi`, allowing the builder to perform formula calculations necessary for certain visualizations.
- `dataViewsAPI`: An instance of `DataViewsPublicPluginStart`, enabling the builder to access and manage data views within Kibana.

#### build Method

The `build` method is the primary method used to generate a Lens configuration. It accepts a `LensConfig` object, detailing the type of chart and its options, and an optional `LensConfigOptions` object for additional configuration options like filters, queries, and time ranges.

**Parameters:**

- `config`: A `LensConfig` object specifying the chart type and its configuration.
- `options` (optional): A `LensConfigOptions` object providing additional settings such as embeddable options, time range overrides, filters, and queries.

**Returns:** A Promise resolving to either `LensAttributes` or `LensEmbeddableInput`, depending on the options provided. This allows the generated configuration to be directly used within Kibana Lens visualizations.

Here's a detailed breakdown of each property within the `LensConfigOptions`:

### embeddable

- **Type:** `boolean`
- **Optional**
- **Description:** Determines the format of the output generated by the `LensConfigBuilder`. When set to `true`, the output will be in the form of `LensEmbeddableInput`, suitable for embedding directly into a Kibana dashboard as an embeddable object. If `false` or not set, the output will be `LensAttributes`, representing the configuration attributes for Lens visualizations without the embedding specifics.

### timeRange

- **Type:** `TimeRange`
- **Optional**
- **Description:** Allows for an optional override of the time range for the visualization. The `TimeRange` object includes `from` and `to` properties to specify the start and end times, and a `type` property indicating whether the range is `relative` or `absolute`. This is particularly useful for tailoring the visualization to specific time frames of interest, independent of the global time filters applied in Kibana.

### filters

- **Type:** `Filter[]`
- **Optional**
- **Description:** Provides an array of `Filter` objects that will be applied to the visualization, enabling developers to pre-define and apply specific filters to the data being visualized. This allows for the creation of more focused and relevant visualizations by pre-filtering the data based on specific criteria.

### query

- **Type:** `Query`
- **Optional**
- **Description:** Allows specifying a query to further refine the data displayed in the visualization. The `Query` object includes a `language` property (e.g., `kuery` or `lucene`) and a `query` string, which represents the actual query to be executed. This is useful for dynamically adjusting the data set based on user input or application context, providing a flexible way to interact with the data.
20 changes: 20 additions & 0 deletions dev_docs/lens/dataset.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
### `dataset`

The `dataset` configuration within the Lens Config Builder API defines the source of data for a visualization.

#### Types of Dataset Configurations

1. **LensESQLDataset (`LensESQLDataset`):**
- Utilizes the Elasticsearch Query Language (ES|QL) for retrieving data.
- Attributes include:
- `esql`: A string containing the ES|QL query. ES|QL is a powerful query language that allows for complex search and aggregation operations, making this dataset type particularly flexible and powerful for advanced data retrieval scenarios.

2. **LensDatatableDataset (`LensDatatableDataset`):**
- Represents data in a tabular format, suitable for direct visualization or further processing.
- This dataset type is typically used when data is already aggregated or processed and just needs to be displayed.

3. **LensDataviewDataset (`LensDataviewDataset`):**
- Targets data within a specific Elasticsearch index or data view.
- Attributes include:
- `index`: The ID of the data view or the name of the Elasticsearch index pattern.
- `timeFieldName` (optional): The name of the field used for time-based operations, providing context for time range queries and aggregations.
118 changes: 118 additions & 0 deletions dev_docs/lens/examples.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
---
id: kibDevLensConfigAPIExamples
slug: /kibana-dev-docs/lens/config-builder/examples
title: Lens Config Builder API Examples
description: Lens Config Builder API Examples
date: 2024-03-04
tags: ['kibana', 'dev', 'lens', 'examples']
---

Here are a few simple configurations for different types of visualizations using the Lens Config Builder API.
These examples demonstrate how to set up basic charts, including Metric, Pie, and XY (line chart) visualizations.
Each configuration showcases the flexibility and ease of defining visual attributes, queries, and other options
to tailor the visualization to specific requirements.

### Metric Chart Configuration

```javascript
const metricConfig = {
chartType: 'metric',
title: 'Total Sales',
dataset: {
esql: 'from myindex | stats totalSales = sum(sales_field)',
},
value: 'totalSales',
label: 'Total Sales Value',
};
```

**Explanation:**

- `chartType`: Specifies the type of chart, in this case, a metric chart.
- `title`: The title of the visualization, displayed as "Total Sales."
- `dataset`: Defines the data source, in this case using ES|QL to select data.
- `value`: Field name in the result to use for value.
- `label`: The label for the metric, providing context to the value displayed.

### Pie Chart Configuration

```javascript
const pieConfig = {
chartType: 'pie',
title: 'Sales by Category',
dataset: {
esql: 'from myindex | stats totalSales = sum(sales_field) by category_field | limit 10',
},
breakdown: ['category_field'],
value: 'totalSales',
legend: {
show: true,
position: 'right',
},
};
```

**Explanation:**

- `chartType`: Indicates that this configuration is for a pie chart.
- `title`: Sets the visualization title to "Sales by Category."
- `dataset`: Selects the data with ES|QL
- `value`: specifies which field to use for value
- `breakdown`: Specifies which field to use for breakdown
- `legend`: Configures the legend to be shown on the right side of the chart, aiding in category identification.

### XY Chart Configuration (Line Chart)

```javascript
const xyConfig = {
chartType: 'xy',
title: 'Monthly Sales Trend',
dataset: {
esql: 'FROM sales_data | EVAL timestamp=DATE_TRUNC(3 hour, @timestamp) | stats sales = SUM(sales_field) by timestamp',
},
layers: [
{
type: 'series',
seriesType: 'line',
xAxis: 'timestamp',
yAxis: [
{
value: 'sales',
label: 'Total Sales',
}
],
},
],
axisTitleVisibility: {
showXAxisTitle: true,
showYAxisTitle: true,
},
};
```

**Explanation:**

- `chartType`: Specifies an XY chart, which can represent various types of line, area, and bar charts.
- `title`: The title for the visualization, "Monthly Sales Trend."
- `dataset`: Uses ES|QL to select the data.
- `layers`: Defines a single layer for the chart, in this case, a line chart representing sales over time.
- `type`: Indicates the layer is a series.
- `seriesType`: Specifies the chart as a line chart.
- `xAxis`: Defines the field to use for x axis.
- `yAxis`: Defines the field to use for y axis and the label
- `axisTitleVisibility`: Ensures both X and Y axis titles are displayed for clarity.

These configurations illustrate the API's capability to define various visualization types with a straightforward and comprehensible structure, enabling developers to quickly integrate rich data visualizations into their applications.


### Converting to actual lens configuration

Any of the above LensConfigs can be converted to actual lens configuration which can be passed to lens embeddable like this:

```
const configBuilder = new LensConfigBuilder(lensFormulaAPI, dataViewsAPI);
const lensConfig = configBuilder(config, {
timeRange: { from: 'now-30d', to: 'now', type: 'relative' },
embeddable: true,
}
```
84 changes: 84 additions & 0 deletions dev_docs/lens/gauge.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
---
id: kibDevLensConfigAPIGauge
slug: /kibana-dev-docs/lens/config-builder/gauge
title: Lens Config Builder API - Gauge
description: Lens Config Builder API - Gauge
date: 2024-03-04
tags: ['kibana', 'dev', 'lens', 'gauge']
---

import Dataset from './dataset.mdx';
import Breakdown from './breakdown.mdx';

Understanding `LensGaugeConfig` in detail

## Required Properties

### `chartType`

- **Type:** Fixed value `'gauge'`
- **Description:** Sets the chart type to gauge.

### `title`

- **Type:** `string`
- **Description:** The title of the visualization.

<Dataset />

### `value`

- **Type:** `LensLayerQuery`
- **Description:** Specifies the field or formula used to determine the main value displayed by the gauge. This is critical for representing the core metric around which the gauge visualization is centered.

## Optional Properties

### `label`

- **Type:** `string`
- **Description:** Offers a descriptive label for the gauge's main value, providing additional context and helping to clarify what the gauge measures.

### `queryMinValue`

- **Type:** `LensLayerQuery`
- **Description:** Defines a query for calculating the minimum value of the gauge's scale. This is particularly useful for gauges that measure a metric's performance against predefined ranges.

### `queryMaxValue`

- **Type:** `LensLayerQuery`
- **Description:** Determines a query for establishing the maximum value of the gauge's scale, setting the upper boundary for what the gauge can display.

### `queryGoalValue`

- **Type:** `LensLayerQuery`
- **Description:** Allows specifying a goal or target value for the gauge, enabling users to visually assess how the current value compares to a set objective.

### `shape`

- **Type:** `'arc' | 'circle' | 'horizontalBullet' | 'verticalBullet'`
- **Description:** Controls the appearance of the gauge by defining its shape. Each shape can convey the data differently, offering various stylistic and functional approaches to data presentation.

<Breakdown />

## Example

```
const gaugeConfig: LensConfig = {
chartType: 'gauge',
title: 'CPU Utilization',
dataset: {
esql: 'from myindex | stats avgCpuUtilization = avg(cpu_utilization) | eval max=100 ',
},
value: 'avgCpuUtilization',
label: 'Average CPU Utilization',
queryMaxValue: 'max',
shape: 'arc',
};
const configBuilder = new LensConfigBuilder(lensFormulaAPI, dataViewsAPI);
const lensConfig = configBuilder.build(gaugeConfig, {
timeRange: { from: 'now-1h', to: 'now', type: 'relative' },
embeddable: true,
});
```

This example demonstrates how to create a gauge visualization using the `LensGaugeConfig`. It sets up a gauge to display the average CPU utilization.
Loading

0 comments on commit 3401d3d

Please sign in to comment.