Skip to content

Commit

Permalink
filtering (making it work with expressions) (#55351)
Browse files Browse the repository at this point in the history
* adding meta information to KibanaDatatable

* updating filtering functions to use new information

* moving filter creation to APPLY_FILTER_ACTION

* adding SELECT_RANGE_ACTION and TRIGGER

* making _meta optional

* inlining legacy code for inspector

* fixing jest tests

* keeping apply_filter_action and adding value_click_action and trigger

* utilities for serializing/unserializing aggConfigs

* renaming prop to indexPatternId

* cleanup

* updating interpreter functional baselines

* trying to fix tests

* Fix legend tests

* reverting update to multi metric screenshot

* updating based on review

* updating tests

Co-authored-by: Nick Partridge <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
3 people authored Feb 3, 2020
1 parent 8def60e commit f271365
Show file tree
Hide file tree
Showing 75 changed files with 700 additions and 281 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,23 @@

import _ from 'lodash';
import moment from 'moment';
import { esFilters } from '../../../../../../../plugins/data/public';
import { esFilters } from '../../../../../../plugins/data/public';
import { deserializeAggConfig } from '../../search/expressions/utils';

export function onBrushEvent(event) {
export async function onBrushEvent(event, getIndexPatterns) {
const isNumber = event.data.ordered;
const isDate = isNumber && event.data.ordered.date;

const xRaw = _.get(event.data, 'series[0].values[0].xRaw');
if (!xRaw) return [];
const column = xRaw.table.columns[xRaw.column];
if (!column) return [];
const aggConfig = event.aggConfigs[xRaw.column];
if (!aggConfig) return [];
const indexPattern = aggConfig.getIndexPattern();
if (!column.meta) return [];
const indexPattern = await getIndexPatterns().get(column.meta.indexPatternId);
const aggConfig = deserializeAggConfig({
...column.meta,
indexPattern,
});
const field = aggConfig.params.field;
if (!field) return [];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,36 @@
import _ from 'lodash';
import moment from 'moment';
import expect from '@kbn/expect';

jest.mock('../../../../../ui/public/agg_types/agg_configs', () => ({
AggConfigs: function AggConfigs() {
return {
createAggConfig: ({ params }) => ({
params,
getIndexPattern: () => ({
timeFieldName: 'time',
}),
}),
};
},
}));

import { onBrushEvent } from './brush_event';

describe('brushEvent', () => {
const DAY_IN_MS = 24 * 60 * 60 * 1000;
const JAN_01_2014 = 1388559600000;

const aggConfigs = [
{
params: {},
getIndexPattern: () => ({
timeFieldName: 'time',
}),
},
];

const baseEvent = {
aggConfigs: [
{
params: {},
getIndexPattern: () => ({
timeFieldName: 'time',
}),
},
],
data: {
fieldFormatter: _.constant({}),
series: [
Expand All @@ -47,6 +62,11 @@ describe('brushEvent', () => {
columns: [
{
id: '1',
meta: {
type: 'histogram',
indexPatternId: 'indexPatternId',
aggConfigParams: aggConfigs[0].params,
},
},
],
},
Expand All @@ -69,9 +89,11 @@ describe('brushEvent', () => {
expect(onBrushEvent).to.be.a(Function);
});

test('ignores event when data.xAxisField not provided', () => {
test('ignores event when data.xAxisField not provided', async () => {
const event = _.cloneDeep(baseEvent);
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: () => baseEvent.data.indexPattern,
}));
expect(filters.length).to.equal(0);
});

Expand All @@ -84,22 +106,26 @@ describe('brushEvent', () => {
};

beforeEach(() => {
aggConfigs[0].params.field = dateField;
dateEvent = _.cloneDeep(baseEvent);
dateEvent.aggConfigs[0].params.field = dateField;
dateEvent.data.ordered = { date: true };
});

test('by ignoring the event when range spans zero time', () => {
test('by ignoring the event when range spans zero time', async () => {
const event = _.cloneDeep(dateEvent);
event.range = [JAN_01_2014, JAN_01_2014];
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: () => dateEvent.data.indexPattern,
}));
expect(filters.length).to.equal(0);
});

test('by updating the timefilter', () => {
test('by updating the timefilter', async () => {
const event = _.cloneDeep(dateEvent);
event.range = [JAN_01_2014, JAN_01_2014 + DAY_IN_MS];
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: async () => dateEvent.data.indexPattern,
}));
expect(filters[0].range.time.gte).to.be(new Date(JAN_01_2014).toISOString());
// Set to a baseline timezone for comparison.
expect(filters[0].range.time.lt).to.be(new Date(JAN_01_2014 + DAY_IN_MS).toISOString());
Expand All @@ -114,17 +140,19 @@ describe('brushEvent', () => {
};

beforeEach(() => {
aggConfigs[0].params.field = dateField;
dateEvent = _.cloneDeep(baseEvent);
dateEvent.aggConfigs[0].params.field = dateField;
dateEvent.data.ordered = { date: true };
});

test('creates a new range filter', () => {
test('creates a new range filter', async () => {
const event = _.cloneDeep(dateEvent);
const rangeBegin = JAN_01_2014;
const rangeEnd = rangeBegin + DAY_IN_MS;
event.range = [rangeBegin, rangeEnd];
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: () => dateEvent.data.indexPattern,
}));
expect(filters.length).to.equal(1);
expect(filters[0].range.anotherTimeField.gte).to.equal(moment(rangeBegin).toISOString());
expect(filters[0].range.anotherTimeField.lt).to.equal(moment(rangeEnd).toISOString());
Expand All @@ -142,22 +170,26 @@ describe('brushEvent', () => {
};

beforeEach(() => {
aggConfigs[0].params.field = numberField;
numberEvent = _.cloneDeep(baseEvent);
numberEvent.aggConfigs[0].params.field = numberField;
numberEvent.data.ordered = { date: false };
});

test('by ignoring the event when range does not span at least 2 values', () => {
test('by ignoring the event when range does not span at least 2 values', async () => {
const event = _.cloneDeep(numberEvent);
event.range = [1];
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: () => numberEvent.data.indexPattern,
}));
expect(filters.length).to.equal(0);
});

test('by creating a new filter', () => {
test('by creating a new filter', async () => {
const event = _.cloneDeep(numberEvent);
event.range = [1, 2, 3, 4];
const filters = onBrushEvent(event);
const filters = await onBrushEvent(event, () => ({
get: () => numberEvent.data.indexPattern,
}));
expect(filters.length).to.equal(1);
expect(filters[0].range.numberField.gte).to.equal(1);
expect(filters[0].range.numberField.lt).to.equal(4);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

import { chromeServiceMock } from '../../../../../../../core/public/mocks';
import { chromeServiceMock } from '../../../../../../core/public/mocks';

jest.doMock('ui/new_platform', () => ({
npStart: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
* under the License.
*/

import { onBrushEvent } from './brush_event';
import { esFilters } from '../../../../../../../plugins/data/public';
import { esFilters } from '../../../../../../plugins/data/public';
import { deserializeAggConfig } from '../../search/expressions/utils';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { getIndexPatterns } from '../../../../../../plugins/data/public/services';

/**
* For terms aggregations on `__other__` buckets, this assembles a list of applicable filter
Expand Down Expand Up @@ -63,11 +65,16 @@ const getOtherBucketFilterTerms = (table, columnIndex, rowIndex) => {
* @param {string} cellValue - value of the current cell
* @return {array|string} - filter or list of filters to provide to queryFilter.addFilters()
*/
const createFilter = (aggConfigs, table, columnIndex, rowIndex, cellValue) => {
const createFilter = async (table, columnIndex, rowIndex) => {
if (!table || !table.columns || !table.columns[columnIndex]) return;
const column = table.columns[columnIndex];
const aggConfig = aggConfigs[columnIndex];
const aggConfig = deserializeAggConfig({
type: column.meta.type,
aggConfigParams: column.meta.aggConfigParams,
indexPattern: await getIndexPatterns().get(column.meta.indexPatternId),
});
let filter = [];
const value = rowIndex > -1 ? table.rows[rowIndex][column.id] : cellValue;
const value = rowIndex > -1 ? table.rows[rowIndex][column.id] : null;
if (value === null || value === undefined || !aggConfig.isFilterable()) {
return;
}
Expand All @@ -85,26 +92,28 @@ const createFilter = (aggConfigs, table, columnIndex, rowIndex, cellValue) => {
return filter;
};

const createFiltersFromEvent = event => {
const createFiltersFromEvent = async event => {
const filters = [];
const dataPoints = event.data || [event];

dataPoints
.filter(point => point)
.forEach(val => {
const { table, column, row, value } = val;
const filter = createFilter(event.aggConfigs, table, column, row, value);
if (filter) {
filter.forEach(f => {
if (event.negate) {
f = esFilters.toggleFilterNegated(f);
}
filters.push(f);
});
}
});
await Promise.all(
dataPoints
.filter(point => point)
.map(async val => {
const { table, column, row } = val;
const filter = await createFilter(table, column, row);
if (filter) {
filter.forEach(f => {
if (event.negate) {
f = esFilters.toggleFilterNegated(f);
}
filters.push(f);
});
}
})
);

return filters;
};

export { createFilter, createFiltersFromEvent, onBrushEvent };
export { createFilter, createFiltersFromEvent };
91 changes: 91 additions & 0 deletions src/legacy/core_plugins/data/public/actions/select_range_action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { i18n } from '@kbn/i18n';
import {
IAction,
createAction,
IncompatibleActionError,
} from '../../../../../plugins/ui_actions/public';
// @ts-ignore
import { onBrushEvent } from './filters/brush_event';
import {
esFilters,
FilterManager,
TimefilterContract,
changeTimeFilter,
extractTimeFilter,
mapAndFlattenFilters,
} from '../../../../../plugins/data/public';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { getIndexPatterns } from '../../../../../plugins/data/public/services';

export const SELECT_RANGE_ACTION = 'SELECT_RANGE_ACTION';

interface ActionContext {
data: any;
timeFieldName: string;
}

async function isCompatible(context: ActionContext) {
try {
const filters: esFilters.Filter[] = (await onBrushEvent(context.data, getIndexPatterns)) || [];
return filters.length > 0;
} catch {
return false;
}
}

export function selectRangeAction(
filterManager: FilterManager,
timeFilter: TimefilterContract
): IAction<ActionContext> {
return createAction<ActionContext>({
type: SELECT_RANGE_ACTION,
id: SELECT_RANGE_ACTION,
getDisplayName: () => {
return i18n.translate('data.filter.applyFilterActionTitle', {
defaultMessage: 'Apply filter to current view',
});
},
isCompatible,
execute: async ({ timeFieldName, data }: ActionContext) => {
if (!(await isCompatible({ timeFieldName, data }))) {
throw new IncompatibleActionError();
}

const filters: esFilters.Filter[] = (await onBrushEvent(data, getIndexPatterns)) || [];

const selectedFilters: esFilters.Filter[] = mapAndFlattenFilters(filters);

if (timeFieldName) {
const { timeRangeFilter, restOfFilters } = extractTimeFilter(
timeFieldName,
selectedFilters
);
filterManager.addFilters(restOfFilters);
if (timeRangeFilter) {
changeTimeFilter(timeFilter, timeRangeFilter);
}
} else {
filterManager.addFilters(selectedFilters);
}
},
});
}
Loading

0 comments on commit f271365

Please sign in to comment.