Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Data Frame Analytics/Anomaly Detection: Custom URLs - entity dropdown reflects Data View update #155096

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,26 @@
import { shallow } from 'enzyme';

jest.mock('../../../services/job_service', () => 'mlJobService');
jest.mock('../../../contexts/kibana', () => ({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a mock for this whole file in x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/kibana_context.ts so I wonder if just jest.mock('../../../contexts/kibana'); would work here?

useMlKibana: () => ({
services: {
application: {
navigateToApp: jest.fn(),
},
data: {
dataViews: [],
},
},
}),
}));

import React from 'react';

import { CustomUrlEditor } from './editor';
import { TIME_RANGE_TYPE, URL_TYPE } from './constants';
import { CustomUrlSettings } from './utils';
import { DataViewListItem } from '@kbn/data-views-plugin/common';
import { Job } from '../../../../../common/types/anomaly_detection_jobs';

function prepareTest(
customUrl: CustomUrlSettings,
Expand Down Expand Up @@ -54,15 +67,15 @@ function prepareTest(
{ id: 'pattern2', title: 'Data view 2' },
] as DataViewListItem[];

const queryEntityFieldNames = ['airline'];
const job = { job_id: 'id', analysis_config: { influencers: ['airline'] } } as Job;

const props = {
customUrl,
setEditCustomUrl: setEditCustomUrlFn,
savedCustomUrls,
dashboards,
dataViewListItems,
queryEntityFieldNames,
job,
};

return shallow(<CustomUrlEditor {...props} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import React, { ChangeEvent, FC } from 'react';
import React, { ChangeEvent, useMemo, useState, useRef, useEffect, FC } from 'react';

import {
EuiComboBox,
Expand All @@ -25,11 +25,16 @@ import {
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import { DataViewListItem } from '@kbn/data-views-plugin/common';
import { DataView } from '@kbn/data-views-plugin/public';
import { CustomUrlSettings, isValidCustomUrlSettingsTimeRange } from './utils';
import { isValidLabel } from '../../../util/custom_url_utils';
import { type DataFrameAnalyticsConfig } from '../../../../../common/types/data_frame_analytics';
import { Job, isAnomalyDetectionJob } from '../../../../../common/types/anomaly_detection_jobs';

import { TIME_RANGE_TYPE, TimeRangeType, URL_TYPE } from './constants';
import { UrlConfig } from '../../../../../common/types/custom_urls';
import { useMlKibana } from '../../../contexts/kibana';
import { getDropDownOptions } from './get_dropdown_options';

function getLinkToOptions() {
return [
Expand Down Expand Up @@ -60,8 +65,8 @@ interface CustomUrlEditorProps {
savedCustomUrls: UrlConfig[];
dashboards: Array<{ id: string; title: string }>;
dataViewListItems: DataViewListItem[];
queryEntityFieldNames: string[];
showTimeRangeSelector?: boolean;
job: Job | DataFrameAnalyticsConfig;
}

/*
Expand All @@ -73,9 +78,42 @@ export const CustomUrlEditor: FC<CustomUrlEditorProps> = ({
savedCustomUrls,
dashboards,
dataViewListItems,
queryEntityFieldNames,
showTimeRangeSelector = true,
job,
}) => {
const [queryEntityFieldNames, setQueryEntityFieldNames] = useState<string[]>([]);
const isAnomalyJob = useMemo(() => isAnomalyDetectionJob(job), [job]);

const {
services: {
data: { dataViews },
},
} = useMlKibana();

const isFirst = useRef(true);

useEffect(() => {
async function getQueryEntityDropdownOptions() {
let dataViewToUse: DataView | undefined;
const dataViewId = customUrl?.kibanaSettings?.discoverIndexPatternId;

try {
dataViewToUse = await dataViews.get(dataViewId ?? '');
} catch (e) {
dataViewToUse = undefined;
}
const dropDownOptions = await getDropDownOptions(isFirst.current, job, dataViewToUse);
setQueryEntityFieldNames(dropDownOptions);

if (isFirst.current) {
isFirst.current = false;
}
}

if (job !== undefined) {
getQueryEntityDropdownOptions();
}
}, [dataViews, job, customUrl?.kibanaSettings?.discoverIndexPatternId]);

if (customUrl === undefined) {
return null;
}
Expand Down Expand Up @@ -112,6 +150,7 @@ export const CustomUrlEditor: FC<CustomUrlEditorProps> = ({
kibanaSettings: {
...kibanaSettings,
discoverIndexPatternId: e.target.value,
queryFieldNames: [],
},
});
};
Expand Down Expand Up @@ -307,58 +346,57 @@ export const CustomUrlEditor: FC<CustomUrlEditorProps> = ({
</EuiFormRow>
)}

{(type === URL_TYPE.KIBANA_DASHBOARD || type === URL_TYPE.KIBANA_DISCOVER) &&
showTimeRangeSelector && (
<>
<EuiSpacer size="m" />
<EuiFlexGroup>
<EuiFlexItem grow={false}>
{(type === URL_TYPE.KIBANA_DASHBOARD || type === URL_TYPE.KIBANA_DISCOVER) && isAnomalyJob && (
<>
<EuiSpacer size="m" />
<EuiFlexGroup>
<EuiFlexItem grow={false}>
<EuiFormRow
label={
<FormattedMessage
id="xpack.ml.customUrlsEditor.timeRangeLabel"
defaultMessage="Time range"
/>
}
className="url-time-range"
display="rowCompressed"
>
<EuiSelect
options={timeRangeOptions}
value={timeRange.type}
onChange={onTimeRangeTypeChange}
data-test-subj="mlJobCustomUrlTimeRangeInput"
compressed
/>
</EuiFormRow>
</EuiFlexItem>
{timeRange.type === TIME_RANGE_TYPE.INTERVAL && (
<EuiFlexItem>
<EuiFormRow
label={
<FormattedMessage
id="xpack.ml.customUrlsEditor.timeRangeLabel"
defaultMessage="Time range"
id="xpack.ml.customUrlsEditor.intervalLabel"
defaultMessage="Interval"
/>
}
className="url-time-range"
error={invalidIntervalError}
isInvalid={isInvalidTimeRange}
display="rowCompressed"
>
<EuiSelect
options={timeRangeOptions}
value={timeRange.type}
onChange={onTimeRangeTypeChange}
data-test-subj="mlJobCustomUrlTimeRangeInput"
<EuiFieldText
value={timeRange.interval}
onChange={onTimeRangeIntervalChange}
isInvalid={isInvalidTimeRange}
data-test-subj="mlJobCustomUrlTimeRangeIntervalInput"
compressed
/>
</EuiFormRow>
</EuiFlexItem>
{timeRange.type === TIME_RANGE_TYPE.INTERVAL && (
<EuiFlexItem>
<EuiFormRow
label={
<FormattedMessage
id="xpack.ml.customUrlsEditor.intervalLabel"
defaultMessage="Interval"
/>
}
className="url-time-range"
error={invalidIntervalError}
isInvalid={isInvalidTimeRange}
display="rowCompressed"
>
<EuiFieldText
value={timeRange.interval}
onChange={onTimeRangeIntervalChange}
isInvalid={isInvalidTimeRange}
data-test-subj="mlJobCustomUrlTimeRangeIntervalInput"
compressed
/>
</EuiFormRow>
</EuiFlexItem>
)}
</EuiFlexGroup>
</>
)}
)}
</EuiFlexGroup>
</>
)}

{type === URL_TYPE.OTHER && (
<EuiFormRow
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { DataView } from '@kbn/data-views-plugin/public';
import {
isDataFrameAnalyticsConfigs,
type DataFrameAnalyticsConfig,
} from '../../../../../common/types/data_frame_analytics';
import { Job, isAnomalyDetectionJob } from '../../../../../common/types/anomaly_detection_jobs';
import { getQueryEntityFieldNames, getSupportedFieldNames } from './utils';

export function getDropDownOptions(
isFirstRender: boolean,
job: Job | DataFrameAnalyticsConfig,
dataView?: DataView
) {
if (isAnomalyDetectionJob(job) && isFirstRender) {
return getQueryEntityFieldNames(job);
} else if ((isDataFrameAnalyticsConfigs(job) || !isFirstRender) && dataView !== undefined) {
return getSupportedFieldNames(job, dataView);
}
return [];
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import rison from '@kbn/rison';
import url from 'url';
import { setStateToKbnUrl } from '@kbn/kibana-utils-plugin/public';
import { cleanEmptyKeys } from '@kbn/dashboard-plugin/public';
import type { DataView } from '@kbn/data-views-plugin/common';
import type { DataView, DataViewField } from '@kbn/data-views-plugin/common';
import { isFilterPinned, Filter } from '@kbn/es-query';
import { DataViewListItem } from '@kbn/data-views-plugin/common';
import { TimeRange as EsQueryTimeRange } from '@kbn/es-query';
Expand Down Expand Up @@ -92,7 +92,10 @@ export function getNewCustomUrlDefaults(
// which matches the indices configured in the job datafeed.
let query: estypes.QueryDslQueryContainer = {};
let indicesName: string | undefined;
let backupIndicesName: string | undefined;
let backupDataViewId: string | undefined;
let jobId;

if (
isAnomalyDetectionJob(job) &&
dataViews !== undefined &&
Expand All @@ -106,12 +109,16 @@ export function getNewCustomUrlDefaults(
jobId = job.job_id;
} else if (isDataFrameAnalyticsConfigs(job) && dataViews !== undefined && dataViews.length > 0) {
indicesName = job.dest.index;
backupIndicesName = job.source.index[0];
query = job.source?.query ?? {};
jobId = job.id;
}

const defaultDataViewId = dataViews.find((dv) => dv.title === indicesName)?.id;
kibanaSettings.discoverIndexPatternId = defaultDataViewId;
if (defaultDataViewId === undefined && backupIndicesName !== undefined) {
backupDataViewId = dataViews.find((dv) => dv.title === backupIndicesName)?.id;
}
kibanaSettings.discoverIndexPatternId = defaultDataViewId ?? backupDataViewId ?? '';
kibanaSettings.filters =
defaultDataViewId === null ? [] : getFiltersForDSLQuery(query, defaultDataViewId, jobId);

Expand All @@ -134,17 +141,23 @@ export function getNewCustomUrlDefaults(
// Returns the list of supported field names that can be used
// to add to the query used when linking to a Kibana dashboard or Discover.
export function getSupportedFieldNames(
job: DataFrameAnalyticsConfig,
job: DataFrameAnalyticsConfig | Job,
dataView: DataView
): string[] {
const resultsField = job.dest.results_field;
const sortedFields = dataView.fields.getAll().sort((a, b) => a.name.localeCompare(b.name)) ?? [];
const categoryFields = sortedFields.filter(
(f) =>
let filterFunction: (field: DataViewField) => boolean = (field: DataViewField) =>
categoryFieldTypes.some((type) => {
return field.esTypes?.includes(type);
});

if (isDataFrameAnalyticsConfigs(job)) {
const resultsField = job.dest.results_field;
filterFunction = (f) =>
categoryFieldTypes.some((type) => {
return f.esTypes?.includes(type);
}) && !f.name.startsWith(resultsField ?? DEFAULT_RESULTS_FIELD)
);
}) && !f.name.startsWith(resultsField ?? DEFAULT_RESULTS_FIELD);
}
const categoryFields = sortedFields.filter(filterFunction);
return categoryFields.map((field) => field.name);
}

Expand Down
Loading