1.1.61 • Published 1 year ago

intuned-adx-query-charts v1.1.61

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

adx-query-charts

Build Status    npm version

Draw charts from Azure Data Explorer queries

Installation

npm install adx-query-charts

Dependencies

  1. lodash: npm i lodash
  2. css-element-queries: npm i css-element-queries
  3. highcharts: npm i highcharts Please note: Highcharts/Highstock libraries are free to use with Log Analytics/adx-query-charts. If you plan to use Highcharts separately, in your own project, you must obtain a license: follow the link − License and Pricing.

Usage

import * as Charts from 'adx-query-charts';

const highchartsVisualizer = new Charts.HighchartsVisualizer();
const chartHelper = chartHelper = new Charts.KustoChartHelper('chart-elem-id', highchartsVisualizer);
const chartOptions: Charts.IChartOptions = {
    chartType: Charts.ChartType.UnstackedColumn,
    columnsSelection: {
        xAxis: { name: 'timestamp', type: Charts.DraftColumnType.DateTime },
        yAxes: [{ name: 'requestCount', type: Charts.DraftColumnType.Int }]
    }
};

// Draw the chart - the chart will be drawn inside an element with 'chart-elem-id' id
chartHelper.draw(queryResultData, chartOptions);

API

KustoChartHelper

Method:Description:Input:Return value:
drawDraw the chartIQueryResultData - The original query result dataIChartOptions - The information required to draw the chartPromise<IChartInfo>
changeThemeChange the theme of an existing chartChartTheme - The theme to applyPromise<void>
getSupportedColumnTypesGet the supported column types for the axes and the split-byfor a specific chart typeChartType - The type of the chartISupportedColumnTypes
getSupportedColumnsInResultGet the supported columns from the query result data for the axes and the split-by for a specific chart typeIQueryResultData - The original query result data ChartType - The type of the chartISupportedColumns
getDefaultSelectionGet the default columns selection from the query result data.Select the default columns for the axes and the split-by for drawing a default chart of a specific chart type.IQueryResultData - The original query result data ChartType - The type of the chartISupportedColumns - (Optional) The list of the supported column types for the axes and the split-byColumnsSelection
downloadChartJPGImageDownload the chart as JPG image(error: Error) => void - Optional A callback that will be called if the module failed to export the chart imagevoid

IChartOptions

Option name:Type:Details:Default value:
chartTypeChartTypeMandatory. The type of the chart to draw
columnsSelectionColumnsSelectionThe columns selection for the Axes and the split-by of the chartIf not provided, default columns will be selected. See: getDefaultSelection method
maxUniqueXValuesnumberThe maximum number of the unique X-axis values.The chart will show the biggest values, and the rest will be aggregated to a separate data point.100
exceedMaxDataPointLabelstringThe label of the data point that contains the aggregated value of all the X-axis values that exceed the 'maxUniqueXValues''OTHER'
aggregationTypeAggregationTypeMultiple rows with the same values for the X-axis and the split-by will be aggregated using a function of this type.For example, assume we get the following query result data:'2016-08-02T10:00:00Z', 'Chrome 51.0', 15, '2016-08-02T10:00:00Z', 'Internet Explorer 9.0', 4When drawing a chart with columnsSelection = { xAxis: timestamp, yAxes: count_ }, and aggregationType = AggregationType.Sum we need to aggregate the values of the same timestamp value and return one row with "2016-08-02T10:00:00Z", 19AggregationType.Sum
titlestringThe title of the chart
legendOptionsILegendOptionsThe legend configuration options
yMinimumValuenumberThe minimum value to be displayed on the y-axis.If not provided, the minimum value is automatically calculated.
yMaximumValuenumberThe maximum value to be displayed on the y-axis.If not provided, the maximum value is automatically calculated.
animationDurationMSnumberThe duration of the animation for chart rendering.The animation can be disabled by setting it to 0.1000
fontFamilystringChart labels font family'az_ea_font, wf_segoe-ui_normal, \"Segoe UI\", \"Segoe WP\", Tahoma, Arial, sans-serif'
chartThemeChartThemeThe theme of the chartChartTheme.Light
getUtcOffsetFunction(dateValue: number): numberCallback that is used to get the desired offset from UTC in minutes for date value. Used to handle timezone.The offset will be added to the original UTC date from the query results data.For example:For 'South Africa Standard Time' timezone return -120 and the displayed date will be:'11/25/2019, 02:00 PM' instead of '11/25/2019, 04:00 PM'See time zone info(https://msdn.microsoft.com/en-us/library/ms912391(v=winembedded.11)If dateFormatter wasn't provided, the callback will be also used for the X axis labels and the tooltip header. Otherwise - it will only be used for positioning the x-axis. Callback inputs:    dateValue - The time value in milliseconds since midnight, January 1, 1970 UTC of the date from the query result.     For example: 1574666160000 represents '2019-11-25T07:16:00.000Z'Callback return value:    The desired offset from UTC in hoursIf not provided, the utcOffset will be 0
dateFormatterFunction(dateValue: number, defaultFormat: DateFormat): stringCallback that is used to format the date values both in the axis and the tooltipCallback inputs:    dateValue - The original date value in milliseconds since midnight, January 1, 1970 UTC    DateFormat - The default format of the labelCallback return value:    The string represents the display value of the dateValueIf not provided - the default formatting will apply
numberFormatterFunction(numberValue: number): stringCallback that is used to format number values both in the axis and the tooltipCallback inputs:    numberValue - The original numberCallback return value:    The string represents the display value of the numberValueIf not provided - the default formatting will apply
xAxisTitleFormatterFunction(xAxisColumn: IColumn): stringCallback that is used to get the xAxis titleCallback inputs:    IColumn - The x-axis columnCallback return value:    The desired x-axis titleIf not provided - the xAxis title will be the xAxis column name
yAxisTitleFormatterFunction(yAxisColumns: IColumn[]): stringCallback that is used to get the yAxis titleCallback inputs:    IColumn[] - The y-axis columnsCallback return value:    The desired y-axis titleIf not provided - the yAxis title will be the first yAxis column name
updateCustomOptionsFunction(originalOptions: any): voidCallback that is called to allow altering the options of the external charting library before rendering the chart.Used to allow flexibility and control of the external charting library.USE WITH CAUTION changing the original options might break the functionality / backward compatibility when using a different IVisualizer or upgrading the charting library.Validating the updated options is the user's responsibility.For official chart options - please make contribution to the base code.Callback inputs:    originalOptions - The custom charting options that are given to the external charting library
onFinishDataTransformationFunction(dataTransformationInfo: IDataTransformationInfo) : Promise<boolean>Callback that is called when all the data transformations required to draw the chart are finishedCallback inputs:    IDataTransformationInfo - The information regarding the applied transformations on the original query resultsCallback return value:    The promise that is used to continue/stop drawing the chart    When provided, the drawing of the chart will be suspended until this promise will be resolved    When resolved with true - the chart will continue the drawing    When resolved with false - the chart drawing will be canceled
onFinishDrawingFunction(chartInfo: IChartInfo) : voidCallback that is called when the chart drawing is finished Callback inputs:    IChartInfo - The information regarding the chart
onFinishChartAnimationFunction(chartInfo: IChartInfo) : voidCallback that is called when the chart animation is finished Callback inputs:    IChartInfo - The information regarding the chart
onDataPointClickedFunction(dataPoint: IDataPoint) : voidWhen this callback is provided, the chart data points will be clickable.The callback will be called when chart's data point will be clicked, providing the clicked data point information.Callback inputs:    IDataPoint - The information regarding the columns and values of the clicked data point.    Note that the value of a date-time column in the dataPoint object will be its numeric value - Date.valueOf().

IDataTransformationInfo

Option name:Type:Details:
numberOfDataPointsnumberThe amount of the data points that will be drawn for the chart
isPartialDatabooleanTrue if the chart presents partial data from the original query resultsThe chart data will be partial when the maximum number of the unique X-axis values exceed the 'maxUniqueXValues' in IChartOptions
isAggregationAppliedbooleanTrue if aggregation was applied on the original query results in order to draw the chartSee 'aggregationType' in IChartOptions for more details

IChartInfo

Option name:Type:Details:
dataTransformationInfoIDataTransformationInfoThe information regarding the applied transformations on the original query results
statusDrawChartStatusThe status of the draw action
errorChartErrorOptional The error information in case that the draw action failed

ILegendOptions

Option name:Type:Details:
isEnabledbooleanOptional Set to false if you want to hide the legend. Default value: true (show legend)
positionLegendPositionOptional The position of the legend (relative to the chart). Default value: Bottom

ChartType

enum ChartType {
    Line,
    Scatter,
    UnstackedArea,
    StackedArea,
    PercentageArea,
    UnstackedColumn,
    StackedColumn,
    PercentageColumn,
    UnstackedBar,
    StackedBar,
    PercentageBar,
    Pie,
    Donut,
}

Columns selection per chart type

Chart type:X-axis:Y-axis:Split-by:
Line / Scatter UnstackedArea / StackedArea / PercentageArea UnstackedColumn / StackedColumn / PercentageColumn UnstackedBar / StackedBar / PercentageBarSingle selectionDateTime / Int / Long Decimal / Real / StringIf split-by column is selected: y-axis restricted to single selection If split-by column is not selected: y-axis can be single/multi selection Int / Long / Decimal / RealSingle selection String
Pie / DonutSingle selection StringSingle selection Int / Long / Decimal / RealSingle / Multi selection String / DateTime / Bool

ColumnsSelection

interface IColumn {
    name: string;
    type: DraftColumnType;
}

class ColumnsSelection {
    xAxis: IColumn;
    yAxes: IColumn[];
    splitBy?: IColumn[];
}

See Columns selection per chart type(#Columns selection per chart type)

AggregationType

enum AggregationType {
    Sum,
    Average,
    Min,
    Max
}

ChartTheme

enum ChartTheme {
    Dark,
    Light
}

ErrorCode

enum ErrorCode {
    InvalidQueryResultData,
    InvalidColumnsSelection,
    UnsupportedTypeInColumnsSelection,
    InvalidChartContainerElementId,
    InvalidDate,
    FailedToCreateVisualization,
    EmptyPie
}

CustomError

class ChartError extends Error {
    errorCode: ErrorCode;
}

See ErrorCode

DateFormat

export enum DateFormat {
    FullDate       // The full date and time. For example: 12/7/2019, 2:30:00.600
    Time           // The full time, without the milliseconds. For example: 2:30:00
    FullTime       // The full time, including the milliseconds. For example: 2:30:00.600
    HourAndMinute  // The hours and minutes. For example: 2:30
    MonthAndDay    // The month and day. For example: July 12th
    MonthAndYear   // The month and day. For example: July 2019
    Year           // The year. For example: 2019
}

DrawChartStatus

export enum DrawChartStatus {
    Success = 'Success',   // Successfully drawn the chart
    Failed = 'Failed',     // There was an error while trying to draw the chart
    Canceled = 'Canceled'  // The chart drawing was canceled
}

See 'onFinishDataTransformation' return value in IChartOptions for more information regarding drawing cancellation

IColumn

type IRowValue = string | number;
type ISeriesRowValue = IRowValue | string[] | number[];
type IRow = IRowValue[];
type ISeriesRow = ISeriesRowValue[];

interface IColumn {
    name: string;
    type: DraftColumnType;
}

IQueryResultData

interface IQueryResultData {
    rows: IRow[] | ISeriesRow[];
    columns: IColumn[];
}

See IColumn

ISupportedColumns

interface ISupportedColumns {
    xAxis: IColumn[];
    yAxis: IColumn[];
    splitBy: IColumn[];
}

See IColumn

DraftColumnType

See: https://kusto.azurewebsites.net/docs/query/scalar-data-types/index.html

enum DraftColumnType {
    Bool,
    DateTime,
    Decimal,
    Dynamic,
    Guid,
    Int,
    Long,
    Real,
    String,
    TimeSpan
}

ISupportedColumnTypes

interface ISupportedColumnTypes {
    xAxis: DraftColumnType[];
    yAxis: DraftColumnType[];
    splitBy: DraftColumnType[];
}

See DraftColumnType

IDataPoint

export interface IDataPointInfo {
    column: IColumn;
    value: IRowValue;
}

export interface IDataPoint {
    x: IDataPointInfo;
    y: IDataPointInfo;
    splitBy?: IDataPointInfo;
}

LegendPosition

export enum LegendPosition {
    Bottom,
    Right
}

Test

Unit tests are written using Jest.

Run tests: npm run test

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.