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

filtering (making it work with expressions) #55351

Merged
merged 20 commits into from
Feb 3, 2020
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -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;
Copy link
Contributor

Choose a reason for hiding this comment

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

@ppisljar This is the line you are referring to in #61949, right?

Copy link
Member Author

@ppisljar ppisljar Apr 7, 2020

Choose a reason for hiding this comment

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

yes, passing valid rowId is cruical now and regionmap was passing wrong info for a very long time.

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;
Copy link
Contributor

Choose a reason for hiding this comment

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

Can this be further typed out? The types are so critical to the trigger and what actions can be attached to it.

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm going to create an issue to track this

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