Query Output

On this page:

About Query Output

Query Output is a data visualization widget that accepts the response from the query endpoint.

Currently there are 10 options available for displaying the response data.

For more information on each display type and how to get the supported display types for each response, visit the "Display Types" section in this doc.

Setting Up Query Output

The following sections in this document contain detailed information about how to customize the properties of this widget.

import React, { Component} from 'react'
import { QueryOutput } from 'react-autoql';

import 'react-autoql/dist/autoql.esm.css'

export default class App extends Component {
  render = () => {
    return (
      <QueryOutput
        authentication={{
          apiKey="your-api-key"
          domain="https://yourdomain.com"
          token="your-jwt-token"
        }}
        queryResponse={responseFromAPI}
      />
    )
  }
}

Props

Prop NameData TypeDefault Value
queryResponse (Required)Object-
authentication (Required if autoQLConfig.enableDrilldowns = true)Object{}
autoQLConfigObject{}
themeConfigObject{}
dataFormattingObject{}
queryInputRefInstance of <QueryInput/>undefined
displayTypeStringundefined
onRecommendedDisplayTypeFunction(displayType) => {}
onDrilldownStartFunction(activeKey) => {}
onDrilldownEndFunction({ response, error }) => {}
activeChartElementKeyStringundefined
enableDynamicChartingBooleantrue
autoChartAggregationsBooleantrue
onQueryValidationSelectOptionFunction() => {}
autoSelectQueryValidationSuggestionBooleantrue
queryValidationSelectionsArray of Suggestion Objectsundefined
renderSuggestionsAsDropdownBooleanfalse
selectedSuggestionStringundefined

authentication Prop

KeyValue TypeDescription
tokenStringYour valid JWT encrypted with your user ID and customer ID. For more information on how to create this token, please visit the "Security" section of our docs.
apiKeyStringYour API key. For more information on how to obtain this, please visit the "Security" section of our docs.
domainStringThe base URL for your API. For more information on how to obtain this, please visit the "Security" section of our docs.

autoQLConfig Prop

KeyValue TypeDefault valueDescription
enableDrilldownsBooleantrueAllows a network call to be made on data click to drilldown into data and receive a new query response. Authentication must be provided if this is enabled
enableQueryInterpretationBooleantrueAllow the query response to include the english interpretation of your query
defaultShowInterpretationBooleanfalseShow the english interpretation underneath the query response

themeConfig Prop

KeyValue TypeDescription
themeString: 'light' || 'dark''light'
accentColorStringlight theme: '#28a8e0', dark theme: '#525252'
fontFamilyString'sans-serif'

theme: Color theme for Query Output. Currently there are two options: light theme and dark theme. In addition to changing the overall theme, you can also change the accent color using the accentColor prop.

accentColor: Primary accent color used in Query Output. This is the color of the header and speech-to-text button. If also using Query Output, this will be the color of the messages displayed in the interface (both natural language query inputs from users and the associated responses that are generated and returned to the user). Note that the visualization (table and chart) colors will not be affected here.

fontFamily: Customize the font family to the provided font wherever possible. Accepts any CSS font family that is available, and if none is provided, will default to Sans-Serif.

dataFormatting Prop

KeyValue TypeDescription
currencyCodeString'USD'
languageCodeString'en-US'
currencyDecimalsNumber2
quantityDecimalsNumber1
comparisonDisplayString: 'PERCENT' || 'RATIO''PERCENT'
monthYearFormatString'MMM YYYY'
dayMonthYearFormatString'll'

currencyCode: If your data is not in USD, you can specify a different currency code here. All visualizations (tables and charts) will show the default currency formatting for the specified code.

queryResponse (Required): This is the whole response object supplied from the query endpoint (or validate endpoint, if enabled). You must pass in this whole object to the QueryOutput component.

For more information on the structure of a query response, please visit API Reference

QueryInputRef: The ref of the QueryInput component. This is used when the response returns a list of suggestions or when the response is returned from the validate endpoint. If the user clicks on a suggestion to run a new query, the QueryInput component will animate and submit the suggested query automatically.

displayType: This is where you can pass in the type of visualization you wish to use for the data. You must pass in a supported display type to the QueryOutput (see the Display Types section below for more details). If an invalid display type or non-supported display type is passed in, the returned display will default to a table. QueryOutput also provides a callback: onRecommendedDisplayType that returns another display type that is supported.

onRecommendedDisplayType: If QueryOutput is unable to render the provided displayType, it will call this function with another display type that will work. QueryOutput's parent component can then switch the displayType to the new value.

onDrilldownStart: (activeKey) => {}: Function called when user clicks on a table or chart to trigger a drilldown query. This function returns the key of the chart element that was clicked. The activeKey can be passed into a new QueryOutput component via the activeChartElementKey

onDrilldownEnd: ({ response, error }) => {}: Function called when a drilldown query is complete. This function returns the following:

  • response: data returned from the drilldown API which can either be an error response or a successful response. In either case, this response can be provided to any QueryOutput component and it will render the appropriate message
  • error: An error that was caught unrelated to the drilldown network request.

activeChartElementKey: The ID of one of the chart elements such as a bar or column. The active chart element will be highlighted in the secondary chart color to indicate that it is active.

enableDynamicCharting: Enables the ability to dynamically change the categories for the x and y axes in a chart by clicking on the axis label. If enableDynamicCharting is true and there are other category options available for that axis, an arrow will appear beside the axis label.

autoChartAggregations: If autoChartAggregations is true, the default display type for aggregation queries will be a chart instead of a table.

onQueryValidationSelectOption: (queryText, newSelectedSuggestions): A function that is called when a user changes the word in any of the suggested replacement dropdowns.

queryText: The new query string

newSelectedSuggestions: An array populated with each selected suggestion corresponding to each dropdown.

autoSelectQueryValidationSuggestion: If set to true, each dropdown with a detected unknown word will automatically be populated with the first replacement suggestion for that word. If set to false, each dropdown will be populated with the original word from the user's query.

queryValidationSelections: If you already know the replacement suggestions and want to specify the initial array of selected words, you can use this prop. This will override the autoSelectQueryValidationSuggestion prop.

renderSuggestionsAsDropdown: In the case where a query could not be interpreted with high confidence, a list of query suggestions that the user can click on will be returned. If this prop is set to true, the suggestions will be rendered as a dropdown instead of a list.

selectedSuggestion: If renderSuggestionsAsDropdown is set to true, you can specify the initial selection with this prop if it is known.

🚧

Currency

Setting a currency code does not perform a currency conversion. It only displays the number in the desired format.

languageCode: If the currency code from your country requires letters not contained in the English alphabet in order to show symbols correctly, you can pass in a locale here. For more details on how to do this, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

currencyDecimals: Number of digits to display after a decimal point for currencies.

quantityDecimals: Number of digits to display after a decimal point for quantity values.

comparisonDisplay: Format for displaying comparison types (ex. changes in data). "Percent" will multiply the number by 100 and display a "%" symbol. "Ratio" will display the original number as-is.

monthYearFormat: The format to display the representation of a whole month. (ex. March 2020). Chata.ai defaults to dayjs for date formatting, however most Moment.js formatting will work here as well. Please see the dayjs docs for formatting options.

dayMonthYearFormat: The format to display the representation of a single day (e.g. March 18, 2020). Chata.ai defaults to dayjs for date formatting, however most Moment.js formatting will work here as well. Please see the dayjs docs for formatting options.

themeConfig Prop

KeyValue TypeDescription
themeString: 'light' || 'dark''light'
accentColorStringlight theme: '#28a8e0', dark theme: '#525252'
fontFamilyString'sans-serif'
chartColorsArray['#26A7E9', '#A5CD39', '#DD6A6A', '#FFA700', '#00C1B2']

theme: Color theme for Query Output. Currently there are two options: light theme and dark theme. In addition to changing the overall theme, you can also change the accent color using the accentColor prop.

accentColor: Primary accent color used in Query Output. This is the color of the header and all the messages displayed in the interface (both natural language query inputs from users and the associated responses that are generated and returned to the user). The visualization (table and chart) colors will not be affected here.

fontFamily: Customize the font family to the provided font wherever possible. Accepts any CSS font family that is available, and if none is provided, will default to Sans-Serif.

chartColors: Array of color options for the visualization themes, starting with the most primary. You can pass any valid CSS color format in here, however it is recommended that the color is opaque (ex. "#26A7E9", "rgb(111, 227, 142)", or "red"). Charts will always apply the colors in order from first to last. If the visualization requires more colors than provided, all colors will be used and then repeated in order.

Display Types

There are 13 display types available for data visualization. Below are the names and descriptions for each display type:

Display TypeOption ValueDescription
TabletableDisplays array data in a regular table. (We use the Tabulator library)
Pivot Tablepivot_tableDisplays a multi-dimensional table, with the first column frozen.
Bar ChartbarOrdinal data is on the y-axis, numerical data is on the x-axis, bars are horizontal. Will show a series for each column of data where applicable.
Column ChartcolumnOrdinal data is on the x-axis, numerical data is on the y-axis, bars are vertical. Will show a series for each column of data where applicable.
Line ChartlineOrdinal data is on the x-axis, numerical data is on the y-axis. Will show a line series for each column of data where applicable.
Column Line Combocolumn_lineOrdinal data is on the x-axis, numerical data is on the y-axis. The left axis is the scale for the columns, the right axis is the scale for the lines. Will show a multiple column series and line series where applicable.
Heat MapheatmapThe position of the squares are based on the categories, and the opacity of the squares are based on the values.
Bubble ChartbubbleThe position of the bubbles are based on the categories, and the radius of the bubbles are based on the values.
Stacked Column Chartstacked_columnOrdinal data is on the x-axis, numerical data is on the y-axis, bars are vertical. Columns are split into categories using the third dimension. Will show a legend for the categories on the right hand side.
Stacked Bar Chartstacked_barOrdinal data is on the y-axis, numerical data is on the x-axis, bars are horizontal. Bars are split into categories using the third dimension. Will show a legend for the categories on the right hand side.
Stacked Area Chartstacked_areaOrdinal data is on the x-axis, numerical data is on the y-axis. Each area is stacked on top of the previous area. Will show a legend for the categories on the right hand side.
ScatterplotscatterplotBoth axes are numerical data, and a point is plotted for each row for 2 numeric columns (x,y).
HistogramhistogramStatistical graph that represents the distribution of a continuous dataset. Only requires one column of data, but must be numerical. The columns will be based on a bucket range from the numerical data. This graph also includes a slider interface to decrease or increase the bucket size of the data.

📘

Supported Display Types

Depending on the data structure of the query response, only certain display types may be supported. To learn about which display types are supported for your query response, see the "Supported Display Types" section below.

Supported Display Types

To get a list of display types supported by the response data, you can access the following function from the library:

getSupportedDisplayTypes({ response }): returns an array of supported display types.

Simply import it along with the QueryOutput component and pass in the query response:

import React, { Component } from 'react'
import { QueryOutput, getSupportedDisplayTypes } from 'react-autoql'

import 'react-autoql/dist/autoql.esm.css'

export default class App extends Component {

...

  render = () => {
    const supportedDisplayTypes = getSupportedDisplayTypes({ response: this.state.queryResponse })

    return supportedDisplayTypes.map(displayType => {
    	return (
        <QueryOutput
      	  authentication={{
            apiKey="your-api-key"
            domain="https://yourdomain.com"
            token="your-jwt-token"
          }}  
          queryResponse={this.state.queryResponse}
          displayType={displayType}
        />
      )
    })
  }
}

If you wish to see if a particular display type is valid, you can use the isDisplayTypeValid function:

isDisplayTypeValid(queryResponse, displayType): checks if the provided display type is included in the supported display types array. Returns either true or false.

Default Display Types

Depending on the data structure, the default display type may change. If we are able to return a pivot table out of the data, this will be the default response, otherwise a regular table will be returned as the default.

You can also call the getDefaultDisplayType function to get this value:

getDefaultDisplayType(queryResponse, defaultToChart): returns either 'table' or 'pivot_table' depending on the data structure.

Examples

import React, { Component, Fragment } from 'react'
import { QueryInput, QueryOutput } from 'react-autoql';

import 'react-autoql/dist/autoql.esm.css'

export default class App extends Component {
  queryInputRef = undefined;

  state = {
    queryResponse: undefined,
    activeChartElementKey: undefined,
  }

  render = () => {
    return (
      <Fragment>
        <QueryInput
      	  authentication={{
            apiKey="your-api-key"
            domain="https://yourdomain.com"
            token="your-jwt-token"
          }}
          ref={r => (this.queryInputRef = r)}
          onResponseCallback={response => {
            this.setState({
              queryResponse: response
            })
          }}
        />
        <QueryOutput
      	  authentication={{
            apiKey="your-api-key"
            domain="https://yourdomain.com"
            token="your-jwt-token"
          }}
          queryInputRef={this.queryInputRef}
          queryResponse={this.state.queryResponse}
          displayType="bar"
					onDrilldownStart={(activeKey) => {
            console.log('CLICKED', groupByObject, queryID)
          	this.setState({
              activeChartElementKey: activeKey
            })
          }}
          onDrilldownEnd={({ response, error }) => {
            this.setState({
              queryResponse: response
            })
          }}
          activeChartElementKey={this.state.activeChartElementKey}
        />
      </Fragment>
    )
  }
}