Skip to content

Commit

Permalink
[ML] ML on Kibana Management: Add ability to pass a group ID filter t…
Browse files Browse the repository at this point in the history
…o job management page (#74533)

* handle group id in url for anomaly detection

* filter analytics list by group id.

* handle list of groupIds

* ensure analytics can handle jobid in url. rename util function

* add tests for getSelectedIdFromUrl and getGroupQueryText

* keep groupIds as array of strings and jobId as single string

* fix tests and update types
  • Loading branch information
alvarezmelissa87 committed Aug 10, 2020
1 parent 8f15621 commit 4ee483b
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ import { getTaskStateBadge, getJobTypeBadge, useColumns } from './use_columns';
import { ExpandedRow } from './expanded_row';
import { AnalyticStatsBarStats, StatsBar } from '../../../../../components/stats_bar';
import { CreateAnalyticsButton } from '../create_analytics_button';
import { getSelectedJobIdFromUrl } from '../../../../../jobs/jobs_list/components/utils';
import {
getSelectedIdFromUrl,
getGroupQueryText,
} from '../../../../../jobs/jobs_list/components/utils';
import { SourceSelection } from '../source_selection';

function getItemIdToExpandedRowMap(
Expand Down Expand Up @@ -99,16 +102,22 @@ export const DataFrameAnalyticsList: FC<Props> = ({

// Query text/job_id based on url but only after getAnalytics is done first
// selectedJobIdFromUrlInitialized makes sure the query is only run once since analytics is being refreshed constantly
const [selectedJobIdFromUrlInitialized, setSelectedJobIdFromUrlInitialized] = useState(false);
const [selectedIdFromUrlInitialized, setSelectedIdFromUrlInitialized] = useState(false);
useEffect(() => {
if (selectedJobIdFromUrlInitialized === false && analytics.length > 0) {
const selectedJobIdFromUrl = getSelectedJobIdFromUrl(window.location.href);
if (selectedJobIdFromUrl !== undefined) {
setSelectedJobIdFromUrlInitialized(true);
setSearchQueryText(selectedJobIdFromUrl);
if (selectedIdFromUrlInitialized === false && analytics.length > 0) {
const { jobId, groupIds } = getSelectedIdFromUrl(window.location.href);
let queryText = '';

if (groupIds !== undefined) {
queryText = getGroupQueryText(groupIds);
} else if (jobId !== undefined) {
queryText = jobId;
}

setSelectedIdFromUrlInitialized(true);
setSearchQueryText(queryText);
}
}, [selectedJobIdFromUrlInitialized, analytics]);
}, [selectedIdFromUrlInitialized, analytics]);

// Subscribe to the refresh observable to trigger reloading the analytics list.
useRefreshAnalyticsList({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
EuiLink,
RIGHT_ALIGNMENT,
} from '@elastic/eui';
import { getJobIdUrl } from '../../../../../util/get_job_id_url';
import { getJobIdUrl, TAB_IDS } from '../../../../../util/get_selected_ids_url';

import { getAnalysisType, DataFrameAnalyticsId } from '../../../../common';
import {
Expand Down Expand Up @@ -137,7 +137,7 @@ export const progressColumn = {
};

export const getDFAnalyticsJobIdLink = (item: DataFrameAnalyticsListRow) => (
<EuiLink href={getJobIdUrl('data_frame_analytics', item.id)}>{item.id}</EuiLink>
<EuiLink href={getJobIdUrl(TAB_IDS.DATA_FRAME_ANALYTICS, item.id)}>{item.id}</EuiLink>
);

export const useColumns = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import React, { Component, Fragment } from 'react';

import { ml } from '../../../../services/ml_api_service';
import { JobGroup } from '../job_group';
import { getSelectedJobIdFromUrl, clearSelectedJobIdFromUrl } from '../utils';
import { getGroupQueryText, getSelectedIdFromUrl, clearSelectedJobIdFromUrl } from '../utils';

import { EuiSearchBar, EuiFlexGroup, EuiFlexItem, EuiFormRow } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
Expand Down Expand Up @@ -54,15 +54,23 @@ export class JobFilterBar extends Component {

componentDidMount() {
// If job id is selected in url, filter table to that id
const selectedId = getSelectedJobIdFromUrl(window.location.href);
if (selectedId !== undefined) {
let defaultQueryText;
const { jobId, groupIds } = getSelectedIdFromUrl(window.location.href);

if (groupIds !== undefined) {
defaultQueryText = getGroupQueryText(groupIds);
} else if (jobId !== undefined) {
defaultQueryText = jobId;
}

if (defaultQueryText !== undefined) {
this.setState(
{
selectedId,
defaultQueryText,
},
() => {
// trigger onChange with query for job id to trigger table filter
const query = EuiSearchBar.Query.parse(selectedId);
const query = EuiSearchBar.Query.parse(defaultQueryText);
this.onChange({ query });
}
);
Expand All @@ -87,7 +95,7 @@ export class JobFilterBar extends Component {
};

render() {
const { error, selectedId } = this.state;
const { error, defaultQueryText } = this.state;
const filters = [
{
type: 'field_value_toggle_group',
Expand Down Expand Up @@ -147,7 +155,7 @@ export class JobFilterBar extends Component {
return (
<EuiFlexGroup direction="column">
<EuiFlexItem data-test-subj="mlJobListSearchBar" grow={false}>
{selectedId === undefined && (
{defaultQueryText === undefined && (
<EuiSearchBar
box={{
incremental: true,
Expand All @@ -157,12 +165,12 @@ export class JobFilterBar extends Component {
className="mlJobFilterBar"
/>
)}
{selectedId !== undefined && (
{defaultQueryText !== undefined && (
<EuiSearchBar
box={{
incremental: true,
}}
defaultQuery={selectedId}
defaultQuery={defaultQueryText}
filters={filters}
onChange={this.onChange}
className="mlJobFilterBar"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,28 @@ import PropTypes from 'prop-types';
import React from 'react';

import { JobGroup } from '../job_group';
import { getGroupIdsUrl, TAB_IDS } from '../../../../util/get_selected_ids_url';

export function JobDescription({ job }) {
export function JobDescription({ job, isManagementTable }) {
return (
<React.Fragment>
<div className="job-description">
{job.description} &nbsp;
{job.groups.map((group) => (
<JobGroup key={group} name={group} />
))}
{job.groups.map((group) => {
if (isManagementTable === true) {
return (
<a key={group} href={getGroupIdsUrl(TAB_IDS.ANOMALY_DETECTION, [group])}>
<JobGroup name={group} />
</a>
);
}
return <JobGroup key={group} name={group} />;
})}
</div>
</React.Fragment>
);
}
JobDescription.propTypes = {
job: PropTypes.object.isRequired,
isManagementTable: PropTypes.bool,
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { toLocaleString } from '../../../../util/string_utils';
import { ResultLinks, actionsMenuContent } from '../job_actions';
import { JobDescription } from './job_description';
import { JobIcon } from '../../../../components/job_message_icon';
import { getJobIdUrl } from '../../../../util/get_job_id_url';
import { getJobIdUrl, TAB_IDS } from '../../../../util/get_selected_ids_url';
import { TIME_FORMAT } from '../../../../../../common/constants/time_format';

import { EuiBadge, EuiBasicTable, EuiButtonIcon, EuiLink, EuiScreenReaderOnly } from '@elastic/eui';
Expand Down Expand Up @@ -71,7 +71,7 @@ export class JobsList extends Component {
return id;
}

return <EuiLink href={getJobIdUrl('jobs', id)}>{id}</EuiLink>;
return <EuiLink href={getJobIdUrl(TAB_IDS.ANOMALY_DETECTION, id)}>{id}</EuiLink>;
}

getPageOfJobs(index, size, sortField, sortDirection) {
Expand Down Expand Up @@ -189,7 +189,9 @@ export class JobsList extends Component {
sortable: true,
field: 'description',
'data-test-subj': 'mlJobListColumnDescription',
render: (description, item) => <JobDescription job={item} />,
render: (description, item) => (
<JobDescription job={item} isManagementTable={isManagementTable} />
),
textOnly: true,
width: '20%',
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
export function getSelectedJobIdFromUrl(str: string): string;

export function getSelectedIdFromUrl(str: string): { groupIds?: string[]; jobId?: string };
export function getGroupQueryText(arr: string[]): string;
export function clearSelectedJobIdFromUrl(str: string): void;
Original file line number Diff line number Diff line change
Expand Up @@ -370,21 +370,34 @@ function getUrlVars(url) {
return vars;
}

export function getSelectedJobIdFromUrl(url) {
export function getSelectedIdFromUrl(url) {
const result = {};
if (typeof url === 'string') {
const isGroup = url.includes('groupIds');
url = decodeURIComponent(url);
if (url.includes('mlManagement') && url.includes('jobId')) {

if (url.includes('mlManagement')) {
const urlParams = getUrlVars(url);
const decodedJson = rison.decode(urlParams.mlManagement);
return decodedJson.jobId;

if (isGroup) {
result.groupIds = decodedJson.groupIds;
} else {
result.jobId = decodedJson.jobId;
}
}
}
return result;
}

export function getGroupQueryText(groupIds) {
return `groups:(${groupIds.join(' or ')})`;
}

export function clearSelectedJobIdFromUrl(url) {
if (typeof url === 'string') {
url = decodeURIComponent(url);
if (url.includes('mlManagement') && url.includes('jobId')) {
if (url.includes('mlManagement') && (url.includes('jobId') || url.includes('groupIds'))) {
const urlParams = getUrlVars(url);
const clearedParams = `ml#/jobs?_g=${urlParams._g}`;
window.history.replaceState({}, document.title, clearedParams);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { getGroupQueryText, getSelectedIdFromUrl } from './utils';

describe('ML - Jobs List utils', () => {
const jobId = 'test_job_id_1';
const jobIdUrl = `http://localhost:5601/aql/app/ml#/jobs?mlManagement=(jobId:${jobId})`;
const groupIdOne = 'test_group_id_1';
const groupIdTwo = 'test_group_id_2';
const groupIdsUrl = `http://localhost:5601/aql/app/ml#/jobs?mlManagement=(groupIds:!(${groupIdOne},${groupIdTwo}))`;
const groupIdUrl = `http://localhost:5601/aql/app/ml#/jobs?mlManagement=(groupIds:!(${groupIdOne}))`;

describe('getSelectedIdFromUrl', () => {
it('should get selected job id from the url', () => {
const actual = getSelectedIdFromUrl(jobIdUrl);
expect(actual).toStrictEqual({ jobId });
});

it('should get selected group ids from the url', () => {
const expected = { groupIds: [groupIdOne, groupIdTwo] };
const actual = getSelectedIdFromUrl(groupIdsUrl);
expect(actual).toStrictEqual(expected);
});

it('should get selected group id from the url', () => {
const expected = { groupIds: [groupIdOne] };
const actual = getSelectedIdFromUrl(groupIdUrl);
expect(actual).toStrictEqual(expected);
});
});

describe('getGroupQueryText', () => {
it('should get query string for selected group ids', () => {
const actual = getGroupQueryText([groupIdOne, groupIdTwo]);
expect(actual).toBe(`groups:(${groupIdOne} or ${groupIdTwo})`);
});

it('should get query string for selected group id', () => {
const actual = getGroupQueryText([groupIdOne]);
expect(actual).toBe(`groups:(${groupIdOne})`);
});
});
});
20 changes: 0 additions & 20 deletions x-pack/plugins/ml/public/application/util/get_job_id_url.ts

This file was deleted.

39 changes: 39 additions & 0 deletions x-pack/plugins/ml/public/application/util/get_selected_ids_url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import rison from 'rison-node';
import { getBasePath } from './dependency_cache';

export enum TAB_IDS {
DATA_FRAME_ANALYTICS = 'data_frame_analytics',
ANOMALY_DETECTION = 'jobs',
}

function getSelectedIdsUrl(tabId: TAB_IDS, settings: { [key: string]: string | string[] }): string {
// Create url for filtering by job id or group ids for kibana management table
const encoded = rison.encode(settings);
const url = `?mlManagement=${encoded}`;
const basePath = getBasePath();

return `${basePath.get()}/app/ml#/${tabId}${url}`;
}

// Create url for filtering by group ids for kibana management table
export function getGroupIdsUrl(tabId: TAB_IDS, ids: string[]): string {
const settings = {
groupIds: ids,
};

return getSelectedIdsUrl(tabId, settings);
}

// Create url for filtering by job id for kibana management table
export function getJobIdUrl(tabId: TAB_IDS, id: string): string {
const settings = {
jobId: id,
};

return getSelectedIdsUrl(tabId, settings);
}

0 comments on commit 4ee483b

Please sign in to comment.