From c3951e9374d848756de33894bad8a6739cdd3d2f Mon Sep 17 00:00:00 2001 From: Alexey Antonov Date: Fri, 8 Nov 2019 06:02:49 +0300 Subject: [PATCH] Move @kbn/es-query into data plugin - filters folder (#49843) Dismissing reviews from ml and canvas as this is only an import change. * Move @kbn/es-query into data plugin - filters folder * fix PR comments --- .../src/es_query/migrate_filter.js | 2 +- .../src/filters/__tests__/phrase.js | 92 ----- .../src/filters/__tests__/query.js | 46 --- .../src/filters/__tests__/range.js | 156 --------- packages/kbn-es-query/src/filters/exists.js | 30 -- packages/kbn-es-query/src/filters/index.d.ts | 51 --- .../kbn-es-query/src/filters/lib/index.ts | 95 ------ .../src/filters/lib/phrase_filter.ts | 65 ---- .../src/filters/lib/range_filter.ts | 58 ---- packages/kbn-es-query/src/filters/phrase.js | 85 ----- packages/kbn-es-query/src/index.d.ts | 1 - packages/kbn-es-query/src/index.js | 1 - .../kbn-es-query/src/kuery/functions/is.js | 2 +- .../kbn-es-query/src/kuery/functions/range.js | 2 +- packages/kbn-es-query/src/utils/filters.js | 133 ++++++++ .../filter/action/apply_filter_action.ts | 11 +- .../apply_filter_popover_content.tsx | 9 +- .../apply_filters/apply_filters_popover.tsx | 10 +- .../public/filter/filter_bar/filter_bar.tsx | 35 +- .../filter/filter_bar/filter_editor/index.tsx | 10 +- .../lib/filter_editor_utils.test.ts | 22 +- .../filter_editor/lib/filter_editor_utils.ts | 54 ++- .../lib/fixtures/exists_filter.ts | 6 +- .../lib/fixtures/phrase_filter.ts | 6 +- .../lib/fixtures/phrases_filter.ts | 6 +- .../lib/fixtures/range_filter.ts | 6 +- .../filter_editor/lib/get_display_value.ts | 7 +- .../lib/get_filter_display_text.tsx | 4 +- .../public/filter/filter_bar/filter_item.tsx | 24 +- .../filter/filter_bar/filter_view/index.tsx | 6 +- .../filter_state_manager.test.ts | 23 +- .../filter_manager/filter_state_manager.ts | 8 +- .../test_helpers/get_stub_filter.ts | 6 +- .../filter_manager/test_helpers/stub_state.ts | 4 +- .../components/create_search_bar.tsx | 4 +- .../search_bar/components/search_bar.tsx | 6 +- .../data/public/search/search_bar/index.tsx | 4 +- .../lib/saved_query_service.test.ts | 4 +- .../timefilter/lib/change_time_filter.test.ts | 6 +- .../timefilter/lib/change_time_filter.ts | 6 +- .../lib/extract_time_filter.test.ts | 36 +- .../timefilter/lib/extract_time_filter.ts | 10 +- .../public/np_ready/public/types.ts | 3 +- .../filter_manager/phrase_filter_manager.js | 18 +- .../filter_manager/range_filter_manager.js | 4 +- .../kibana/public/dashboard/dashboard_app.tsx | 8 +- .../dashboard/dashboard_app_controller.tsx | 4 +- .../dashboard/dashboard_state_manager.ts | 8 +- .../public/dashboard/lib/filter_utils.ts | 6 +- .../migrations/move_filters_to_query.test.ts | 8 +- .../migrations/move_filters_to_query.ts | 10 +- .../saved_dashboard/saved_dashboard.d.ts | 5 +- .../kibana/public/dashboard/types.ts | 4 +- .../discover/angular/context/api/context.ts | 6 +- .../angular/doc_table/components/table_row.js | 4 +- .../discover/embeddable/search_embeddable.ts | 8 +- .../public/discover/embeddable/types.ts | 4 +- .../embeddable/visualize_embeddable.ts | 11 +- .../public/vis/timelion_request_handler.ts | 6 +- .../public/vega_request_handler.ts | 9 +- .../public/vega_view/vega_base_view.js | 6 +- .../buckets/_terms_other_bucket_helper.js | 9 +- .../create_filter/date_histogram.test.ts | 4 +- .../buckets/create_filter/date_histogram.ts | 4 +- .../buckets/create_filter/date_range.ts | 6 +- .../buckets/create_filter/filters.ts | 4 +- .../buckets/create_filter/histogram.ts | 6 +- .../buckets/create_filter/ip_range.ts | 6 +- .../agg_types/buckets/create_filter/range.ts | 4 +- .../buckets/create_filter/terms.test.ts | 17 +- .../agg_types/buckets/create_filter/terms.ts | 12 +- .../agg_types/buckets/date_histogram.ts | 3 +- .../ui/public/agg_types/buckets/date_range.ts | 7 +- .../ui/public/agg_types/buckets/geo_hash.ts | 3 +- .../ui/public/agg_types/buckets/histogram.ts | 7 +- .../buckets/migrate_include_exclude_format.ts | 9 +- .../courier/search_source/search_source.js | 4 +- .../__tests__/filter_generator.js | 8 +- .../public/filter_manager/filter_generator.js | 8 +- .../ui/public/vis/vis_filters/brush_event.js | 4 +- .../ui/public/vis/vis_filters/vis_filters.js | 6 +- .../loader/embedded_visualize_handler.ts | 4 +- .../ui/public/visualize/loader/types.ts | 4 +- .../loader/utils/query_geohash_bounds.ts | 6 +- .../public/embeddable/dashboard_container.tsx | 6 +- .../common/es_query/__tests__/fields_mock.ts | 320 ++++++++++++++++++ .../common/es_query/filters}/custom_filter.ts | 0 .../common/es_query/filters}/exists_filter.ts | 12 + .../filters}/geo_bounding_box_filter.ts | 0 .../es_query/filters}/geo_polygon_filter.ts | 0 .../data/common/es_query/filters/index.ts | 24 +- .../es_query/filters}/match_all_filter.ts | 0 .../common/es_query/filters}/meta_filter.ts | 44 +-- .../es_query/filters}/missing_filter.ts | 0 .../es_query/filters/phrase_filter.test.ts | 97 ++++++ .../common/es_query/filters/phrase_filter.ts | 144 ++++++++ .../common/es_query/filters/phrases_filter.ts | 63 ++-- .../filters/query_string_filter.test.ts | 39 ++- .../es_query/filters}/query_string_filter.ts | 15 + .../es_query/filters/range_filter.test.ts | 174 ++++++++++ .../common/es_query/filters/range_filter.ts | 124 +++++-- .../data/common/es_query/filters/types.ts | 57 ++++ .../plugins/data/common/es_query/index.ts | 8 +- src/plugins/data/common/index.ts | 1 + src/plugins/data/public/index.ts | 1 - .../filter_manager/filter_manager.test.ts | 94 ++--- .../query/filter_manager/filter_manager.ts | 39 ++- .../lib/compare_filters.test.ts | 46 ++- .../filter_manager/lib/compare_filters.ts | 12 +- .../filter_manager/lib/dedup_filters.test.ts | 66 ++-- .../query/filter_manager/lib/dedup_filters.ts | 10 +- .../lib/generate_mapping_chain.test.ts | 14 +- .../lib/generate_mapping_chain.ts | 4 +- .../lib/map_and_flatten_filters.test.ts | 6 +- .../lib/map_and_flatten_filters.ts | 6 +- .../filter_manager/lib/map_filter.test.ts | 14 +- .../query/filter_manager/lib/map_filter.ts | 4 +- .../lib/mappers/map_default.test.ts | 7 +- .../filter_manager/lib/mappers/map_default.ts | 6 +- .../lib/mappers/map_exists.test.ts | 7 +- .../filter_manager/lib/mappers/map_exists.ts | 10 +- .../lib/mappers/map_geo_bounding_box.test.ts | 9 +- .../lib/mappers/map_geo_bounding_box.ts | 18 +- .../lib/mappers/map_geo_polygon.test.ts | 48 ++- .../lib/mappers/map_geo_polygon.ts | 19 +- .../lib/mappers/map_match_all.test.ts | 5 +- .../lib/mappers/map_match_all.ts | 8 +- .../lib/mappers/map_missing.test.ts | 9 +- .../filter_manager/lib/mappers/map_missing.ts | 11 +- .../lib/mappers/map_phrase.test.ts | 8 +- .../filter_manager/lib/mappers/map_phrase.ts | 29 +- .../filter_manager/lib/mappers/map_phrases.ts | 6 +- .../lib/mappers/map_query_string.test.ts | 13 +- .../lib/mappers/map_query_string.ts | 8 +- .../lib/mappers/map_range.test.ts | 23 +- .../filter_manager/lib/mappers/map_range.ts | 28 +- .../filter_manager/lib/only_disabled.test.ts | 46 +-- .../query/filter_manager/lib/only_disabled.ts | 9 +- .../filter_manager/lib/uniq_filters.test.ts | 49 ++- .../query/filter_manager/lib/uniq_filters.ts | 8 +- .../test_helpers/get_filters_array.ts | 4 +- .../test_helpers/get_stub_filter.ts | 6 +- .../data/public/query/filter_manager/types.ts | 6 +- src/plugins/data/public/query/index.tsx | 1 - .../public/lib/actions/apply_filter_action.ts | 6 +- .../add_panel/add_panel_action.test.tsx | 6 +- .../inspect_panel_action.test.tsx | 4 +- .../remove_panel_action.test.tsx | 6 +- .../embeddables/filterable_container.tsx | 7 +- .../embeddables/filterable_embeddable.tsx | 4 +- .../public/tests/apply_filter_action.test.ts | 4 +- .../embeddable/public/tests/container.test.ts | 6 +- .../public/tests/explicit_input.test.ts | 6 +- .../public/expression_types/kibana_context.ts | 5 +- src/plugins/expressions/public/types/index.ts | 4 +- .../functions/common/saved_map.ts | 4 +- .../server/lib/build_embeddable_filters.ts | 10 +- .../lens/public/app_plugin/app.test.tsx | 8 +- .../plugins/lens/public/app_plugin/app.tsx | 4 +- .../editor_frame/data_panel_wrapper.tsx | 4 +- .../editor_frame/editor_frame.tsx | 4 +- .../editor_frame/expression_helpers.ts | 4 +- .../editor_frame/save.test.ts | 4 +- .../editor_frame/workspace_panel.test.tsx | 5 +- .../embeddable/embeddable.test.tsx | 15 +- .../embeddable/embeddable.tsx | 7 +- .../embeddable/expression_wrapper.tsx | 6 +- .../public/indexpattern_plugin/field_item.tsx | 5 +- .../public/persistence/saved_object_store.ts | 4 +- x-pack/legacy/plugins/lens/public/types.ts | 8 +- .../maps/public/angular/map_controller.js | 4 +- .../layers/tooltips/es_tooltip_property.js | 5 +- .../index_based/data_loader/data_loader.ts | 2 - .../components/embeddables/embedded_map.tsx | 4 +- .../embeddables/embedded_map_helpers.tsx | 4 +- .../public/components/embeddables/types.ts | 4 +- .../events_viewer/events_viewer.tsx | 5 +- .../public/components/events_viewer/index.tsx | 4 +- .../public/components/navigation/helpers.ts | 4 +- .../navigation/tab_navigation/types.ts | 5 +- .../index.test.tsx | 4 +- .../add_filter_to_global_search_bar/index.tsx | 4 +- .../public/components/search_bar/index.tsx | 8 +- .../public/components/timeline/helpers.tsx | 5 +- .../public/components/url_state/helpers.ts | 5 +- .../url_state/initialize_redux_by_url.tsx | 5 +- .../siem/public/components/url_state/types.ts | 5 +- .../components/url_state/use_url_state.tsx | 11 +- .../plugins/siem/public/lib/keury/index.ts | 5 +- .../siem/public/pages/hosts/details/index.tsx | 1 - .../siem/public/pages/hosts/details/types.ts | 5 +- .../plugins/siem/public/pages/hosts/types.ts | 5 +- .../public/pages/network/ip_details/types.ts | 5 +- .../siem/public/pages/network/types.ts | 5 +- .../siem/public/store/inputs/actions.ts | 4 +- .../plugins/siem/public/store/inputs/model.ts | 4 +- .../lib/detection_engine/alerts/types.ts | 4 +- 197 files changed, 1963 insertions(+), 1587 deletions(-) delete mode 100644 packages/kbn-es-query/src/filters/__tests__/phrase.js delete mode 100644 packages/kbn-es-query/src/filters/__tests__/query.js delete mode 100644 packages/kbn-es-query/src/filters/__tests__/range.js delete mode 100644 packages/kbn-es-query/src/filters/exists.js delete mode 100644 packages/kbn-es-query/src/filters/index.d.ts delete mode 100644 packages/kbn-es-query/src/filters/lib/index.ts delete mode 100644 packages/kbn-es-query/src/filters/lib/phrase_filter.ts delete mode 100644 packages/kbn-es-query/src/filters/lib/range_filter.ts delete mode 100644 packages/kbn-es-query/src/filters/phrase.js create mode 100644 packages/kbn-es-query/src/utils/filters.js create mode 100644 src/plugins/data/common/es_query/__tests__/fields_mock.ts rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/custom_filter.ts (100%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/exists_filter.ts (81%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/geo_bounding_box_filter.ts (100%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/geo_polygon_filter.ts (100%) rename packages/kbn-es-query/src/filters/lib/phrases_filter.ts => src/plugins/data/common/es_query/filters/index.ts (66%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/match_all_filter.ts (100%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/meta_filter.ts (75%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/missing_filter.ts (100%) create mode 100644 src/plugins/data/common/es_query/filters/phrase_filter.test.ts create mode 100644 src/plugins/data/common/es_query/filters/phrase_filter.ts rename packages/kbn-es-query/src/filters/phrases.js => src/plugins/data/common/es_query/filters/phrases_filter.ts (51%) rename packages/kbn-es-query/src/filters/query.js => src/plugins/data/common/es_query/filters/query_string_filter.test.ts (56%) rename {packages/kbn-es-query/src/filters/lib => src/plugins/data/common/es_query/filters}/query_string_filter.ts (78%) create mode 100644 src/plugins/data/common/es_query/filters/range_filter.test.ts rename packages/kbn-es-query/src/filters/range.js => src/plugins/data/common/es_query/filters/range_filter.ts (51%) create mode 100644 src/plugins/data/common/es_query/filters/types.ts rename packages/kbn-es-query/src/filters/index.js => src/plugins/data/common/es_query/index.ts (84%) diff --git a/packages/kbn-es-query/src/es_query/migrate_filter.js b/packages/kbn-es-query/src/es_query/migrate_filter.js index d5f52648b027e..b74fc485a6184 100644 --- a/packages/kbn-es-query/src/es_query/migrate_filter.js +++ b/packages/kbn-es-query/src/es_query/migrate_filter.js @@ -18,7 +18,7 @@ */ import _ from 'lodash'; -import { getConvertedValueForField } from '../filters'; +import { getConvertedValueForField } from '../utils/filters'; export function migrateFilter(filter, indexPattern) { if (filter.match) { diff --git a/packages/kbn-es-query/src/filters/__tests__/phrase.js b/packages/kbn-es-query/src/filters/__tests__/phrase.js deleted file mode 100644 index dbd794a018d9e..0000000000000 --- a/packages/kbn-es-query/src/filters/__tests__/phrase.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 { buildInlineScriptForPhraseFilter, buildPhraseFilter } from '../phrase'; -import expect from '@kbn/expect'; -import _ from 'lodash'; -import indexPattern from '../../__fixtures__/index_pattern_response.json'; -import filterSkeleton from '../../__fixtures__/filter_skeleton'; - -let expected; - -describe('Filter Manager', function () { - describe('Phrase filter builder', function () { - beforeEach(() => { - expected = _.cloneDeep(filterSkeleton); - }); - - it('should be a function', function () { - expect(buildPhraseFilter).to.be.a(Function); - }); - - it('should return a match query filter when passed a standard field', function () { - const field = getField(indexPattern, 'bytes'); - expected.query = { - match_phrase: { - bytes: 5 - } - }; - expect(buildPhraseFilter(field, 5, indexPattern)).to.eql(expected); - }); - - it('should return a script filter when passed a scripted field', function () { - const field = getField(indexPattern, 'script number'); - expected.meta.field = 'script number'; - _.set(expected, 'script.script', { - source: '(' + field.script + ') == value', - lang: 'expression', - params: { - value: 5, - } - }); - expect(buildPhraseFilter(field, 5, indexPattern)).to.eql(expected); - }); - }); - - describe('buildInlineScriptForPhraseFilter', function () { - - it('should wrap painless scripts in a lambda', function () { - const field = { - lang: 'painless', - script: 'return foo;', - }; - - const expected = `boolean compare(Supplier s, def v) {return s.get() == v;}` + - `compare(() -> { return foo; }, params.value);`; - - expect(buildInlineScriptForPhraseFilter(field)).to.be(expected); - }); - - it('should create a simple comparison for other langs', function () { - const field = { - lang: 'expression', - script: 'doc[bytes].value', - }; - - const expected = `(doc[bytes].value) == value`; - - expect(buildInlineScriptForPhraseFilter(field)).to.be(expected); - }); - }); -}); - -function getField(indexPattern, name) { - return indexPattern.fields.find(field => field.name === name); -} diff --git a/packages/kbn-es-query/src/filters/__tests__/query.js b/packages/kbn-es-query/src/filters/__tests__/query.js deleted file mode 100644 index 8b774f05c29d3..0000000000000 --- a/packages/kbn-es-query/src/filters/__tests__/query.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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 { buildQueryFilter } from '../query'; -import { cloneDeep } from 'lodash'; -import expect from '@kbn/expect'; -import indexPattern from '../../__fixtures__/index_pattern_response.json'; -import filterSkeleton from '../../__fixtures__/filter_skeleton'; - -let expected; - -describe('Filter Manager', function () { - describe('Phrase filter builder', function () { - beforeEach(() => { - expected = cloneDeep(filterSkeleton); - }); - - it('should be a function', function () { - expect(buildQueryFilter).to.be.a(Function); - }); - - it('should return a query filter when passed a standard field', function () { - expected.query = { - foo: 'bar' - }; - expect(buildQueryFilter({ foo: 'bar' }, indexPattern.id)).to.eql(expected); - }); - - }); -}); diff --git a/packages/kbn-es-query/src/filters/__tests__/range.js b/packages/kbn-es-query/src/filters/__tests__/range.js deleted file mode 100644 index 9b23fc23908d4..0000000000000 --- a/packages/kbn-es-query/src/filters/__tests__/range.js +++ /dev/null @@ -1,156 +0,0 @@ -/* - * 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 { buildRangeFilter } from '../range'; -import expect from '@kbn/expect'; -import _ from 'lodash'; -import indexPattern from '../../__fixtures__/index_pattern_response.json'; -import filterSkeleton from '../../__fixtures__/filter_skeleton'; - -let expected; - -describe('Filter Manager', function () { - describe('Range filter builder', function () { - beforeEach(() => { - expected = _.cloneDeep(filterSkeleton); - }); - - it('should be a function', function () { - expect(buildRangeFilter).to.be.a(Function); - }); - - it('should return a range filter when passed a standard field', function () { - const field = getField(indexPattern, 'bytes'); - expected.range = { - bytes: { - gte: 1, - lte: 3 - } - }; - expect(buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern)).to.eql(expected); - }); - - it('should return a script filter when passed a scripted field', function () { - const field = getField(indexPattern, 'script number'); - expected.meta.field = 'script number'; - _.set(expected, 'script.script', { - lang: 'expression', - source: '(' + field.script + ')>=gte && (' + field.script + ')<=lte', - params: { - value: '>=1 <=3', - gte: 1, - lte: 3 - } - }); - expect(buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern)).to.eql(expected); - }); - - it('should wrap painless scripts in comparator lambdas', function () { - const field = getField(indexPattern, 'script date'); - const expected = `boolean gte(Supplier s, def v) {return !s.get().toInstant().isBefore(Instant.parse(v))} ` + - `boolean lte(Supplier s, def v) {return !s.get().toInstant().isAfter(Instant.parse(v))}` + - `gte(() -> { ${field.script} }, params.gte) && ` + - `lte(() -> { ${field.script} }, params.lte)`; - - const inlineScript = buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern).script.script.source; - expect(inlineScript).to.be(expected); - }); - - it('should throw an error when gte and gt, or lte and lt are both passed', function () { - const field = getField(indexPattern, 'script number'); - expect(function () { - buildRangeFilter(field, { gte: 1, gt: 3 }, indexPattern); - }).to.throwError(); - expect(function () { - buildRangeFilter(field, { lte: 1, lt: 3 }, indexPattern); - }).to.throwError(); - }); - - it('to use the right operator for each of gte, gt, lt and lte', function () { - const field = getField(indexPattern, 'script number'); - _.each({ gte: '>=', gt: '>', lte: '<=', lt: '<' }, function (operator, key) { - const params = {}; - params[key] = 5; - const filter = buildRangeFilter(field, params, indexPattern); - - expect(filter.script.script.source).to.be( - '(' + field.script + ')' + operator + key); - expect(filter.script.script.params[key]).to.be(5); - expect(filter.script.script.params.value).to.be(operator + 5); - - }); - }); - - describe('when given params where one side is infinite', function () { - const field = getField(indexPattern, 'script number'); - let filter; - beforeEach(function () { - filter = buildRangeFilter(field, { gte: 0, lt: Infinity }, indexPattern); - }); - - describe('returned filter', function () { - it('is a script filter', function () { - expect(filter).to.have.property('script'); - }); - - it('contain a param for the finite side', function () { - expect(filter.script.script.params).to.have.property('gte', 0); - }); - - it('does not contain a param for the infinite side', function () { - expect(filter.script.script.params).not.to.have.property('lt'); - }); - - it('does not contain a script condition for the infinite side', function () { - const field = getField(indexPattern, 'script number'); - const script = field.script; - expect(filter.script.script.source).to.equal(`(${script})>=gte`); - }); - }); - }); - - describe('when given params where both sides are infinite', function () { - const field = getField(indexPattern, 'script number'); - let filter; - beforeEach(function () { - filter = buildRangeFilter( - field, { gte: -Infinity, lt: Infinity }, indexPattern); - }); - - describe('returned filter', function () { - it('is a match_all filter', function () { - expect(filter).not.to.have.property('script'); - expect(filter).to.have.property('match_all'); - }); - - it('does not contain params', function () { - expect(filter).not.to.have.property('params'); - }); - - it('meta field is set to field name', function () { - expect(filter.meta.field).to.equal('script number'); - }); - }); - }); - }); -}); - -function getField(indexPattern, name) { - return indexPattern.fields.find(field => field.name === name); -} diff --git a/packages/kbn-es-query/src/filters/exists.js b/packages/kbn-es-query/src/filters/exists.js deleted file mode 100644 index 0c82279fb4417..0000000000000 --- a/packages/kbn-es-query/src/filters/exists.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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. - */ - -// Creates a filter where the given field exists -export function buildExistsFilter(field, indexPattern) { - return { - meta: { - index: indexPattern.id - }, - exists: { - field: field.name - } - }; -} diff --git a/packages/kbn-es-query/src/filters/index.d.ts b/packages/kbn-es-query/src/filters/index.d.ts deleted file mode 100644 index c05e32dbf07b9..0000000000000 --- a/packages/kbn-es-query/src/filters/index.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 { CustomFilter, ExistsFilter, PhraseFilter, PhrasesFilter, RangeFilter } from './lib'; -import { RangeFilterParams } from './lib/range_filter'; - -export * from './lib'; - -// We can't import the real types from the data plugin, so need to either duplicate -// them here or figure out another solution, perhaps housing them in this package -type Field = any; -type IndexPattern = any; - -export function buildExistsFilter(field: Field, indexPattern: IndexPattern): ExistsFilter; - -export function buildPhraseFilter( - field: Field, - value: string, - indexPattern: IndexPattern -): PhraseFilter; - -export function buildPhrasesFilter( - field: Field, - values: string[], - indexPattern: IndexPattern -): PhrasesFilter; - -export function buildQueryFilter(query: any, index: string, alias?: string): CustomFilter; - -export function buildRangeFilter( - field: Field, - params: RangeFilterParams, - indexPattern: IndexPattern, - formattedValue?: string -): RangeFilter; diff --git a/packages/kbn-es-query/src/filters/lib/index.ts b/packages/kbn-es-query/src/filters/lib/index.ts deleted file mode 100644 index ea02398710341..0000000000000 --- a/packages/kbn-es-query/src/filters/lib/index.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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. - */ - -// The interface the other filters extend -export * from './meta_filter'; - -// The actual filter types -import { CustomFilter } from './custom_filter'; -import { ExistsFilter, isExistsFilter } from './exists_filter'; -import { GeoBoundingBoxFilter, isGeoBoundingBoxFilter } from './geo_bounding_box_filter'; -import { GeoPolygonFilter, isGeoPolygonFilter } from './geo_polygon_filter'; -import { - PhraseFilter, - isPhraseFilter, - isScriptedPhraseFilter, - getPhraseFilterField, - getPhraseFilterValue, -} from './phrase_filter'; -import { PhrasesFilter, isPhrasesFilter } from './phrases_filter'; -import { QueryStringFilter, isQueryStringFilter } from './query_string_filter'; -import { - RangeFilter, - isRangeFilter, - isScriptedRangeFilter, - RangeFilterParams, -} from './range_filter'; -import { MatchAllFilter, isMatchAllFilter } from './match_all_filter'; -import { MissingFilter, isMissingFilter } from './missing_filter'; - -export { - CustomFilter, - ExistsFilter, - isExistsFilter, - GeoBoundingBoxFilter, - isGeoBoundingBoxFilter, - GeoPolygonFilter, - isGeoPolygonFilter, - PhraseFilter, - isPhraseFilter, - isScriptedPhraseFilter, - getPhraseFilterField, - getPhraseFilterValue, - PhrasesFilter, - isPhrasesFilter, - QueryStringFilter, - isQueryStringFilter, - RangeFilter, - isRangeFilter, - isScriptedRangeFilter, - RangeFilterParams, - MatchAllFilter, - isMatchAllFilter, - MissingFilter, - isMissingFilter, -}; - -// Any filter associated with a field (used in the filter bar/editor) -export type FieldFilter = - | ExistsFilter - | GeoBoundingBoxFilter - | GeoPolygonFilter - | PhraseFilter - | PhrasesFilter - | RangeFilter - | MatchAllFilter - | MissingFilter; - -export enum FILTERS { - CUSTOM = 'custom', - PHRASES = 'phrases', - PHRASE = 'phrase', - EXISTS = 'exists', - MATCH_ALL = 'match_all', - MISSING = 'missing', - QUERY_STRING = 'query_string', - RANGE = 'range', - GEO_BOUNDING_BOX = 'geo_bounding_box', - GEO_POLYGON = 'geo_polygon', -} diff --git a/packages/kbn-es-query/src/filters/lib/phrase_filter.ts b/packages/kbn-es-query/src/filters/lib/phrase_filter.ts deleted file mode 100644 index 124a5da372487..0000000000000 --- a/packages/kbn-es-query/src/filters/lib/phrase_filter.ts +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 { get, isPlainObject } from 'lodash'; -import { Filter, FilterMeta } from './meta_filter'; - -export type PhraseFilterMeta = FilterMeta & { - params: { - query: string; // The unformatted value - }; - script?: { - script: { - params: any; - }; - }; - field?: any; -}; - -export type PhraseFilter = Filter & { - meta: PhraseFilterMeta; -}; - -type PhraseFilterValue = string | number | boolean; - -export const isPhraseFilter = (filter: any): filter is PhraseFilter => { - const isMatchPhraseQuery = filter && filter.query && filter.query.match_phrase; - - const isDeprecatedMatchPhraseQuery = - filter && - filter.query && - filter.query.match && - Object.values(filter.query.match).find((params: any) => params.type === 'phrase'); - - return !!(isMatchPhraseQuery || isDeprecatedMatchPhraseQuery); -}; - -export const isScriptedPhraseFilter = (filter: any): filter is PhraseFilter => - Boolean(get(filter, 'script.script.params.value')); - -export const getPhraseFilterField = (filter: PhraseFilter) => { - const queryConfig = filter.query.match_phrase || filter.query.match; - return Object.keys(queryConfig)[0]; -}; - -export const getPhraseFilterValue = (filter: PhraseFilter): PhraseFilterValue => { - const queryConfig = filter.query.match_phrase || filter.query.match; - const queryValue = Object.values(queryConfig)[0] as any; - return isPlainObject(queryValue) ? queryValue.query : queryValue; -}; diff --git a/packages/kbn-es-query/src/filters/lib/range_filter.ts b/packages/kbn-es-query/src/filters/lib/range_filter.ts deleted file mode 100644 index fc8d05d575d59..0000000000000 --- a/packages/kbn-es-query/src/filters/lib/range_filter.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 { get, keys } from 'lodash'; -import { Filter, FilterMeta } from './meta_filter'; - -export interface RangeFilterParams { - from?: number | string; - to?: number | string; - gt?: number | string; - lt?: number | string; - gte?: number | string; - lte?: number | string; - format?: string; -} - -export type RangeFilterMeta = FilterMeta & { - params: RangeFilterParams; - field?: any; -}; - -export type RangeFilter = Filter & { - meta: RangeFilterMeta; - script?: { - script: { - params: any; - }; - }; - range: { [key: string]: RangeFilterParams }; -}; - -const hasRangeKeys = (params: RangeFilterParams) => - Boolean( - keys(params).find((key: string) => ['gte', 'gt', 'lte', 'lt', 'from', 'to'].includes(key)) - ); - -export const isRangeFilter = (filter: any): filter is RangeFilter => filter && filter.range; - -export const isScriptedRangeFilter = (filter: any): filter is RangeFilter => { - const params: RangeFilterParams = get(filter, 'script.script.params', {}); - - return hasRangeKeys(params); -}; diff --git a/packages/kbn-es-query/src/filters/phrase.js b/packages/kbn-es-query/src/filters/phrase.js deleted file mode 100644 index f0134f289ad9d..0000000000000 --- a/packages/kbn-es-query/src/filters/phrase.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - */ - -// Creates an filter where the given field matches the given value -export function buildPhraseFilter(field, value, indexPattern) { - const filter = { meta: { index: indexPattern.id } }; - const convertedValue = getConvertedValueForField(field, value); - - if (field.scripted) { - filter.script = getPhraseScript(field, value); - filter.meta.field = field.name; - } else { - filter.query = { match_phrase: {} }; - filter.query.match_phrase[field.name] = convertedValue; - } - return filter; -} - -export function getPhraseScript(field, value) { - const convertedValue = getConvertedValueForField(field, value); - const script = buildInlineScriptForPhraseFilter(field); - - return { - script: { - source: script, - lang: field.lang, - params: { - value: convertedValue - } - } - }; -} - -// See https://github.com/elastic/elasticsearch/issues/20941 and https://github.com/elastic/kibana/issues/8677 -// and https://github.com/elastic/elasticsearch/pull/22201 -// for the reason behind this change. Aggs now return boolean buckets with a key of 1 or 0. -export function getConvertedValueForField(field, value) { - if (typeof value !== 'boolean' && field.type === 'boolean') { - if ([1, 'true'].includes(value)) { - return true; - } - else if ([0, 'false'].includes(value)) { - return false; - } - else { - throw new Error(`${value} is not a valid boolean value for boolean field ${field.name}`); - } - } - return value; -} - -/** - * Takes a scripted field and returns an inline script appropriate for use in a script query. - * Handles lucene expression and Painless scripts. Other langs aren't guaranteed to generate valid - * scripts. - * - * @param {object} scriptedField A Field object representing a scripted field - * @returns {string} The inline script string - */ -export function buildInlineScriptForPhraseFilter(scriptedField) { - // We must wrap painless scripts in a lambda in case they're more than a simple expression - if (scriptedField.lang === 'painless') { - return `boolean compare(Supplier s, def v) {return s.get() == v;}` + - `compare(() -> { ${scriptedField.script} }, params.value);`; - } - else { - return `(${scriptedField.script}) == value`; - } -} diff --git a/packages/kbn-es-query/src/index.d.ts b/packages/kbn-es-query/src/index.d.ts index ca4455da33f45..c06cef6367fe7 100644 --- a/packages/kbn-es-query/src/index.d.ts +++ b/packages/kbn-es-query/src/index.d.ts @@ -19,4 +19,3 @@ export * from './es_query'; export * from './kuery'; -export * from './filters'; diff --git a/packages/kbn-es-query/src/index.js b/packages/kbn-es-query/src/index.js index 086b2f6db8d0d..963999bd0999b 100644 --- a/packages/kbn-es-query/src/index.js +++ b/packages/kbn-es-query/src/index.js @@ -18,5 +18,4 @@ */ export * from './kuery'; -export * from './filters'; export * from './es_query'; diff --git a/packages/kbn-es-query/src/kuery/functions/is.js b/packages/kbn-es-query/src/kuery/functions/is.js index 33ae2112e3c0c..63ade9e8793a7 100644 --- a/packages/kbn-es-query/src/kuery/functions/is.js +++ b/packages/kbn-es-query/src/kuery/functions/is.js @@ -21,7 +21,7 @@ import _ from 'lodash'; import * as ast from '../ast'; import * as literal from '../node_types/literal'; import * as wildcard from '../node_types/wildcard'; -import { getPhraseScript } from '../../filters'; +import { getPhraseScript } from '../../utils/filters'; import { getFields } from './utils/get_fields'; import { getTimeZoneFromSettings } from '../../utils/get_time_zone_from_settings'; import { getFullFieldNameNode } from './utils/get_full_field_name_node'; diff --git a/packages/kbn-es-query/src/kuery/functions/range.js b/packages/kbn-es-query/src/kuery/functions/range.js index 80181cfc003f1..f7719998ad524 100644 --- a/packages/kbn-es-query/src/kuery/functions/range.js +++ b/packages/kbn-es-query/src/kuery/functions/range.js @@ -20,7 +20,7 @@ import _ from 'lodash'; import { nodeTypes } from '../node_types'; import * as ast from '../ast'; -import { getRangeScript } from '../../filters'; +import { getRangeScript } from '../../utils/filters'; import { getFields } from './utils/get_fields'; import { getTimeZoneFromSettings } from '../../utils/get_time_zone_from_settings'; import { getFullFieldNameNode } from './utils/get_full_field_name_node'; diff --git a/packages/kbn-es-query/src/utils/filters.js b/packages/kbn-es-query/src/utils/filters.js new file mode 100644 index 0000000000000..6e4f5c342688c --- /dev/null +++ b/packages/kbn-es-query/src/utils/filters.js @@ -0,0 +1,133 @@ +/* + * 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 { pick, get, reduce, map } from 'lodash'; + +/** @deprecated + * @see src/plugins/data/public/es_query/filters/phrase_filter.ts + * Code was already moved into src/plugins/data/public. + * This method will be removed after moving 'es_query' into new platform + * */ +export const getConvertedValueForField = (field, value) => { + if (typeof value !== 'boolean' && field.type === 'boolean') { + if ([1, 'true'].includes(value)) { + return true; + } else if ([0, 'false'].includes(value)) { + return false; + } else { + throw new Error(`${value} is not a valid boolean value for boolean field ${field.name}`); + } + } + return value; +}; + +/** @deprecated + * @see src/plugins/data/public/es_query/filters/phrase_filter.ts + * Code was already moved into src/plugins/data/public. + * This method will be removed after moving 'es_query' into new platform + * */ +export const buildInlineScriptForPhraseFilter = (scriptedField) => { + // We must wrap painless scripts in a lambda in case they're more than a simple expression + if (scriptedField.lang === 'painless') { + return ( + `boolean compare(Supplier s, def v) {return s.get() == v;}` + + `compare(() -> { ${scriptedField.script} }, params.value);` + ); + } else { + return `(${scriptedField.script}) == value`; + } +}; + +/** @deprecated + * @see src/plugins/data/public/es_query/filters/phrase_filter.ts + * Code was already moved into src/plugins/data/public. + * This method will be removed after moving 'es_query' into new platform + * */ +export function getPhraseScript(field, value) { + const convertedValue = getConvertedValueForField(field, value); + const script = buildInlineScriptForPhraseFilter(field); + + return { + script: { + source: script, + lang: field.lang, + params: { + value: convertedValue, + }, + }, + }; +} + +/** @deprecated + * @see src/plugins/data/public/es_query/filters/range_filter.ts + * Code was already moved into src/plugins/data/public. + * This method will be removed after moving 'kuery' into new platform + * */ +export function getRangeScript(field, params) { + const operators = { + gt: '>', + gte: '>=', + lte: '<=', + lt: '<', + }; + const comparators = { + gt: 'boolean gt(Supplier s, def v) {return s.get() > v}', + gte: 'boolean gte(Supplier s, def v) {return s.get() >= v}', + lte: 'boolean lte(Supplier s, def v) {return s.get() <= v}', + lt: 'boolean lt(Supplier s, def v) {return s.get() < v}', + }; + + const dateComparators = { + gt: 'boolean gt(Supplier s, def v) {return s.get().toInstant().isAfter(Instant.parse(v))}', + gte: 'boolean gte(Supplier s, def v) {return !s.get().toInstant().isBefore(Instant.parse(v))}', + lte: 'boolean lte(Supplier s, def v) {return !s.get().toInstant().isAfter(Instant.parse(v))}', + lt: 'boolean lt(Supplier s, def v) {return s.get().toInstant().isBefore(Instant.parse(v))}', + }; + + const knownParams = pick(params, (val, key) => { + return key in operators; + }); + let script = map(knownParams, (val, key) => { + return '(' + field.script + ')' + get(operators, key) + key; + }).join(' && '); + + // We must wrap painless scripts in a lambda in case they're more than a simple expression + if (field.lang === 'painless') { + const comp = field.type === 'date' ? dateComparators : comparators; + const currentComparators = reduce( + knownParams, + (acc, val, key) => acc.concat(get(comp, key)), + [] + ).join(' '); + + const comparisons = map(knownParams, (val, key) => { + return `${key}(() -> { ${field.script} }, params.${key})`; + }).join(' && '); + + script = `${currentComparators}${comparisons}`; + } + + return { + script: { + source: script, + params: knownParams, + lang: field.lang, + }, + }; +} diff --git a/src/legacy/core_plugins/data/public/filter/action/apply_filter_action.ts b/src/legacy/core_plugins/data/public/filter/action/apply_filter_action.ts index 5db3d779d12fa..8d2337264d02f 100644 --- a/src/legacy/core_plugins/data/public/filter/action/apply_filter_action.ts +++ b/src/legacy/core_plugins/data/public/filter/action/apply_filter_action.ts @@ -18,21 +18,20 @@ */ import { i18n } from '@kbn/i18n'; -import { Filter } from '@kbn/es-query'; import { CoreStart } from 'src/core/public'; import { IAction, createAction, IncompatibleActionError, } from '../../../../../../plugins/ui_actions/public'; -import { FilterManager } from '../../../../../../plugins/data/public'; +import { FilterManager, esFilters } from '../../../../../../plugins/data/public'; import { TimefilterContract, changeTimeFilter, extractTimeFilter } from '../../timefilter'; import { applyFiltersPopover } from '../apply_filters/apply_filters_popover'; import { IndexPatternsStart } from '../../index_patterns'; export const GLOBAL_APPLY_FILTER_ACTION = 'GLOBAL_APPLY_FILTER_ACTION'; interface ActionContext { - filters: Filter[]; + filters: esFilters.Filter[]; timeFieldName?: string; } @@ -64,7 +63,7 @@ export function createFilterAction( throw new IncompatibleActionError(); } - let selectedFilters: Filter[] = filters; + let selectedFilters: esFilters.Filter[] = filters; if (selectedFilters.length > 1) { const indexPatterns = await Promise.all( @@ -73,7 +72,7 @@ export function createFilterAction( }) ); - const filterSelectionPromise: Promise = new Promise(resolve => { + const filterSelectionPromise: Promise = new Promise(resolve => { const overlay = overlays.openModal( applyFiltersPopover( filters, @@ -82,7 +81,7 @@ export function createFilterAction( overlay.close(); resolve([]); }, - (filterSelection: Filter[]) => { + (filterSelection: esFilters.Filter[]) => { overlay.close(); resolve(filterSelection); } diff --git a/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filter_popover_content.tsx b/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filter_popover_content.tsx index 8fc6b33f3f68a..e9d05d6340e58 100644 --- a/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filter_popover_content.tsx +++ b/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filter_popover_content.tsx @@ -28,19 +28,18 @@ import { EuiModalHeaderTitle, EuiSwitch, } from '@elastic/eui'; -import { Filter } from '@kbn/es-query'; import { FormattedMessage } from '@kbn/i18n/react'; import React, { Component } from 'react'; import { IndexPattern } from '../../index_patterns'; import { getFilterDisplayText } from '../filter_bar/filter_editor/lib/get_filter_display_text'; -import { mapAndFlattenFilters } from '../../../../../../plugins/data/public'; +import { mapAndFlattenFilters, esFilters } from '../../../../../../plugins/data/public'; import { getDisplayValueFromFilter } from '../filter_bar/filter_editor/lib/get_display_value'; interface Props { - filters: Filter[]; + filters: esFilters.Filter[]; indexPatterns: IndexPattern[]; onCancel: () => void; - onSubmit: (filters: Filter[]) => void; + onSubmit: (filters: esFilters.Filter[]) => void; } interface State { @@ -58,7 +57,7 @@ export class ApplyFiltersPopoverContent extends Component { isFilterSelected: props.filters.map(() => true), }; } - private getLabel(filter: Filter) { + private getLabel(filter: esFilters.Filter) { const filterDisplayValue = getDisplayValueFromFilter(filter, this.props.indexPatterns); return getFilterDisplayText(filter, filterDisplayValue); } diff --git a/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filters_popover.tsx b/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filters_popover.tsx index 0687701429866..41f757e726c40 100644 --- a/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filters_popover.tsx +++ b/src/legacy/core_plugins/data/public/filter/apply_filters/apply_filters_popover.tsx @@ -18,15 +18,15 @@ */ import { EuiModal, EuiOverlayMask } from '@elastic/eui'; -import { Filter } from '@kbn/es-query'; import React, { Component } from 'react'; import { ApplyFiltersPopoverContent } from './apply_filter_popover_content'; import { IndexPattern } from '../../index_patterns/index_patterns'; +import { esFilters } from '../../../../../../plugins/data/public'; interface Props { - filters: Filter[]; + filters: esFilters.Filter[]; onCancel: () => void; - onSubmit: (filters: Filter[]) => void; + onSubmit: (filters: esFilters.Filter[]) => void; indexPatterns: IndexPattern[]; } @@ -56,9 +56,9 @@ export class ApplyFiltersPopover extends Component { } type cancelFunction = () => void; -type submitFunction = (filters: Filter[]) => void; +type submitFunction = (filters: esFilters.Filter[]) => void; export const applyFiltersPopover = ( - filters: Filter[], + filters: esFilters.Filter[], indexPatterns: IndexPattern[], onCancel: cancelFunction, onSubmit: submitFunction diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx index 8a8fb36ea24bf..333e1e328651d 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx @@ -18,16 +18,6 @@ */ import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiPopover } from '@elastic/eui'; -import { - buildEmptyFilter, - disableFilter, - enableFilter, - Filter, - pinFilter, - toggleFilterDisabled, - toggleFilterNegated, - unpinFilter, -} from '@kbn/es-query'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import classNames from 'classnames'; import React, { useState } from 'react'; @@ -38,10 +28,11 @@ import { FilterEditor } from './filter_editor'; import { FilterItem } from './filter_item'; import { FilterOptions } from './filter_options'; import { useKibana, KibanaContextProvider } from '../../../../../../plugins/kibana_react/public'; +import { esFilters } from '../../../../../../plugins/data/public'; interface Props { - filters: Filter[]; - onFiltersUpdated?: (filters: Filter[]) => void; + filters: esFilters.Filter[]; + onFiltersUpdated?: (filters: esFilters.Filter[]) => void; className: string; indexPatterns: IndexPattern[]; intl: InjectedIntl; @@ -87,7 +78,7 @@ function FilterBarUI(props: Props) { return content; } - function onFiltersUpdated(filters: Filter[]) { + function onFiltersUpdated(filters: esFilters.Filter[]) { if (props.onFiltersUpdated) { props.onFiltersUpdated(filters); } @@ -112,7 +103,7 @@ function FilterBarUI(props: Props) { const isPinned = uiSettings!.get('filters:pinnedByDefault'); const [indexPattern] = props.indexPatterns; const index = indexPattern && indexPattern.id; - const newFilter = buildEmptyFilter(isPinned, index); + const newFilter = esFilters.buildEmptyFilter(isPinned, index); const button = ( void; + onSubmit: (filter: esFilters.Filter) => void; onCancel: () => void; intl: InjectedIntl; } @@ -379,7 +379,9 @@ class FilterEditorUI extends Component { private getFieldFromFilter() { const indexPattern = this.getIndexPatternFromFilter(); - return indexPattern && getFieldFromFilter(this.props.filter as FieldFilter, indexPattern); + return ( + indexPattern && getFieldFromFilter(this.props.filter as esFilters.FieldFilter, indexPattern) + ); } private getSelectedOperator() { diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.test.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.test.ts index 734c5d00e58d5..dbff5096f2287 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.test.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.test.ts @@ -17,7 +17,6 @@ * under the License. */ -import { FilterStateStore, toggleFilterNegated } from '@kbn/es-query'; import { mockFields, mockIndexPattern } from '../../../../index_patterns'; import { IndexPattern, Field } from '../../../../index'; import { @@ -42,6 +41,7 @@ import { existsFilter } from './fixtures/exists_filter'; import { phraseFilter } from './fixtures/phrase_filter'; import { phrasesFilter } from './fixtures/phrases_filter'; import { rangeFilter } from './fixtures/range_filter'; +import { esFilters } from '../../../../../../../../plugins/data/public'; jest.mock('ui/new_platform'); @@ -81,7 +81,7 @@ describe('Filter editor utils', () => { }); it('should return "is not" for phrase filter', () => { - const negatedPhraseFilter = toggleFilterNegated(phraseFilter); + const negatedPhraseFilter = esFilters.toggleFilterNegated(phraseFilter); const operator = getOperatorFromFilter(negatedPhraseFilter); expect(operator).not.toBeUndefined(); expect(operator && operator.type).toBe('phrase'); @@ -96,7 +96,7 @@ describe('Filter editor utils', () => { }); it('should return "is not one of" for negated phrases filter', () => { - const negatedPhrasesFilter = toggleFilterNegated(phrasesFilter); + const negatedPhrasesFilter = esFilters.toggleFilterNegated(phrasesFilter); const operator = getOperatorFromFilter(negatedPhrasesFilter); expect(operator).not.toBeUndefined(); expect(operator && operator.type).toBe('phrases'); @@ -111,7 +111,7 @@ describe('Filter editor utils', () => { }); it('should return "is not between" for negated range filter', () => { - const negatedRangeFilter = toggleFilterNegated(rangeFilter); + const negatedRangeFilter = esFilters.toggleFilterNegated(rangeFilter); const operator = getOperatorFromFilter(negatedRangeFilter); expect(operator).not.toBeUndefined(); expect(operator && operator.type).toBe('range'); @@ -126,7 +126,7 @@ describe('Filter editor utils', () => { }); it('should return "does not exists" for negated exists filter', () => { - const negatedExistsFilter = toggleFilterNegated(existsFilter); + const negatedExistsFilter = esFilters.toggleFilterNegated(existsFilter); const operator = getOperatorFromFilter(negatedExistsFilter); expect(operator).not.toBeUndefined(); expect(operator && operator.type).toBe('exists'); @@ -246,7 +246,7 @@ describe('Filter editor utils', () => { it('should build phrase filters', () => { const params = 'foo'; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], @@ -268,7 +268,7 @@ describe('Filter editor utils', () => { it('should build phrases filters', () => { const params = ['foo', 'bar']; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], @@ -290,7 +290,7 @@ describe('Filter editor utils', () => { it('should build range filters', () => { const params = { from: 'foo', to: 'qux' }; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], @@ -311,7 +311,7 @@ describe('Filter editor utils', () => { it('should build exists filters', () => { const params = undefined; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], @@ -332,7 +332,7 @@ describe('Filter editor utils', () => { it('should include disabled state', () => { const params = undefined; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], @@ -348,7 +348,7 @@ describe('Filter editor utils', () => { it('should negate based on operator', () => { const params = undefined; const alias = 'bar'; - const state = FilterStateStore.APP_STATE; + const state = esFilters.FilterStateStore.APP_STATE; const filter = buildFilter( mockedIndexPattern, mockedFields[0], diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.ts index f0628f03c173e..b7d20526a6b92 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/filter_editor_utils.ts @@ -18,42 +18,30 @@ */ import dateMath from '@elastic/datemath'; -import { - buildExistsFilter, - buildPhraseFilter, - buildPhrasesFilter, - buildRangeFilter, - FieldFilter, - Filter, - FilterMeta, - FilterStateStore, - PhraseFilter, - PhrasesFilter, - RangeFilter, -} from '@kbn/es-query'; import { omit } from 'lodash'; import { Ipv4Address } from '../../../../../../../../plugins/kibana_utils/public'; import { Field, IndexPattern, isFilterable } from '../../../../index_patterns'; import { FILTER_OPERATORS, Operator } from './filter_operators'; +import { esFilters } from '../../../../../../../../plugins/data/public'; export function getIndexPatternFromFilter( - filter: Filter, + filter: esFilters.Filter, indexPatterns: IndexPattern[] ): IndexPattern | undefined { return indexPatterns.find(indexPattern => indexPattern.id === filter.meta.index); } -export function getFieldFromFilter(filter: FieldFilter, indexPattern: IndexPattern) { +export function getFieldFromFilter(filter: esFilters.FieldFilter, indexPattern: IndexPattern) { return indexPattern.fields.find(field => field.name === filter.meta.key); } -export function getOperatorFromFilter(filter: Filter) { +export function getOperatorFromFilter(filter: esFilters.Filter) { return FILTER_OPERATORS.find(operator => { return filter.meta.type === operator.type && filter.meta.negate === operator.negate; }); } -export function getQueryDslFromFilter(filter: Filter) { +export function getQueryDslFromFilter(filter: esFilters.Filter) { return omit(filter, ['$state', 'meta']); } @@ -67,16 +55,16 @@ export function getOperatorOptions(field: Field) { }); } -export function getFilterParams(filter: Filter) { +export function getFilterParams(filter: esFilters.Filter) { switch (filter.meta.type) { case 'phrase': - return (filter as PhraseFilter).meta.params.query; + return (filter as esFilters.PhraseFilter).meta.params.query; case 'phrases': - return (filter as PhrasesFilter).meta.params; + return (filter as esFilters.PhrasesFilter).meta.params; case 'range': return { - from: (filter as RangeFilter).meta.params.gte, - to: (filter as RangeFilter).meta.params.lt, + from: (filter as esFilters.RangeFilter).meta.params.gte, + to: (filter as esFilters.RangeFilter).meta.params.lt, }; } } @@ -133,8 +121,8 @@ export function buildFilter( disabled: boolean, params: any, alias: string | null, - store: FilterStateStore -): Filter { + store: esFilters.FilterStateStore +): esFilters.Filter { const filter = buildBaseFilter(indexPattern, field, operator, params); filter.meta.alias = alias; filter.meta.negate = operator.negate; @@ -148,17 +136,17 @@ function buildBaseFilter( field: Field, operator: Operator, params: any -): Filter { +): esFilters.Filter { switch (operator.type) { case 'phrase': - return buildPhraseFilter(field, params, indexPattern); + return esFilters.buildPhraseFilter(field, params, indexPattern); case 'phrases': - return buildPhrasesFilter(field, params, indexPattern); + return esFilters.buildPhrasesFilter(field, params, indexPattern); case 'range': const newParams = { gte: params.from, lt: params.to }; - return buildRangeFilter(field, newParams, indexPattern); + return esFilters.buildRangeFilter(field, newParams, indexPattern); case 'exists': - return buildExistsFilter(field, indexPattern); + return esFilters.buildExistsFilter(field, indexPattern); default: throw new Error(`Unknown operator type: ${operator.type}`); } @@ -170,10 +158,10 @@ export function buildCustomFilter( disabled: boolean, negate: boolean, alias: string | null, - store: FilterStateStore -): Filter { - const meta: FilterMeta = { index, type: 'custom', disabled, negate, alias }; - const filter: Filter = { ...queryDsl, meta }; + store: esFilters.FilterStateStore +): esFilters.Filter { + const meta: esFilters.FilterMeta = { index, type: 'custom', disabled, negate, alias }; + const filter: esFilters.Filter = { ...queryDsl, meta }; filter.$state = { store }; return filter; } diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/exists_filter.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/exists_filter.ts index a17f767006f3e..5af97818f9bfb 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/exists_filter.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/exists_filter.ts @@ -17,9 +17,9 @@ * under the License. */ -import { ExistsFilter, FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../../plugins/data/public'; -export const existsFilter: ExistsFilter = { +export const existsFilter: esFilters.ExistsFilter = { meta: { index: 'logstash-*', negate: false, @@ -29,6 +29,6 @@ export const existsFilter: ExistsFilter = { alias: null, }, $state: { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }, }; diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrase_filter.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrase_filter.ts index 77bb8e06c801a..b6c8b9905e6b3 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrase_filter.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrase_filter.ts @@ -17,9 +17,9 @@ * under the License. */ -import { FilterStateStore, PhraseFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../../plugins/data/public'; -export const phraseFilter: PhraseFilter = { +export const phraseFilter: esFilters.PhraseFilter = { meta: { negate: false, index: 'logstash-*', @@ -33,6 +33,6 @@ export const phraseFilter: PhraseFilter = { }, }, $state: { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }, }; diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrases_filter.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrases_filter.ts index e86c3ee1318e3..2e2ba4f798bdd 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrases_filter.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/phrases_filter.ts @@ -17,9 +17,9 @@ * under the License. */ -import { FilterStateStore, PhrasesFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../../plugins/data/public'; -export const phrasesFilter: PhrasesFilter = { +export const phrasesFilter: esFilters.PhrasesFilter = { meta: { index: 'logstash-*', type: 'phrases', @@ -31,6 +31,6 @@ export const phrasesFilter: PhrasesFilter = { alias: null, }, $state: { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }, }; diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/range_filter.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/range_filter.ts index 46a5181450fea..c6438e30ecec6 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/range_filter.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/fixtures/range_filter.ts @@ -17,9 +17,9 @@ * under the License. */ -import { FilterStateStore, RangeFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../../plugins/data/public'; -export const rangeFilter: RangeFilter = { +export const rangeFilter: esFilters.RangeFilter = { meta: { index: 'logstash-*', negate: false, @@ -34,7 +34,7 @@ export const rangeFilter: RangeFilter = { }, }, $state: { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }, range: {}, }; diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_display_value.ts b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_display_value.ts index 551b99d01b7da..d8af7b3e97ad2 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_display_value.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_display_value.ts @@ -18,7 +18,7 @@ */ import { get } from 'lodash'; -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../plugins/data/public'; import { IndexPattern } from '../../../../index_patterns/index_patterns'; import { Field } from '../../../../index_patterns/fields'; import { getIndexPatternFromFilter } from './filter_editor_utils'; @@ -33,7 +33,10 @@ function getValueFormatter(indexPattern?: IndexPattern, key?: string) { return format; } -export function getDisplayValueFromFilter(filter: Filter, indexPatterns: IndexPattern[]): string { +export function getDisplayValueFromFilter( + filter: esFilters.Filter, + indexPatterns: IndexPattern[] +): string { const indexPattern = getIndexPatternFromFilter(filter, indexPatterns); if (typeof filter.meta.value === 'function') { diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_filter_display_text.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_filter_display_text.tsx index 429381694ddf8..21abcd8510046 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_filter_display_text.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/lib/get_filter_display_text.tsx @@ -19,11 +19,11 @@ import React, { Fragment } from 'react'; import { EuiTextColor } from '@elastic/eui'; -import { Filter } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { existsOperator, isOneOfOperator } from './filter_operators'; +import { esFilters } from '../../../../../../../../plugins/data/public'; -export function getFilterDisplayText(filter: Filter, filterDisplayName: string) { +export function getFilterDisplayText(filter: esFilters.Filter, filterDisplayName: string) { const prefixText = filter.meta.negate ? ` ${i18n.translate('data.filter.filterBar.negatedFilterPrefix', { defaultMessage: 'NOT ', diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx index 2e98cbd306e9c..50c1672333801 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx @@ -18,13 +18,6 @@ */ import { EuiContextMenu, EuiPopover } from '@elastic/eui'; -import { - Filter, - isFilterPinned, - toggleFilterDisabled, - toggleFilterNegated, - toggleFilterPinned, -} from '@kbn/es-query'; import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import classNames from 'classnames'; import React, { Component } from 'react'; @@ -33,13 +26,14 @@ import { IndexPattern } from '../../index_patterns'; import { FilterEditor } from './filter_editor'; import { FilterView } from './filter_view'; import { getDisplayValueFromFilter } from './filter_editor/lib/get_display_value'; +import { esFilters } from '../../../../../../plugins/data/public'; interface Props { id: string; - filter: Filter; + filter: esFilters.Filter; indexPatterns: IndexPattern[]; className?: string; - onUpdate: (filter: Filter) => void; + onUpdate: (filter: esFilters.Filter) => void; onRemove: () => void; intl: InjectedIntl; uiSettings: UiSettingsClientContract; @@ -62,7 +56,7 @@ class FilterItemUI extends Component { 'globalFilterItem', { 'globalFilterItem-isDisabled': disabled, - 'globalFilterItem-isPinned': isFilterPinned(filter), + 'globalFilterItem-isPinned': esFilters.isFilterPinned(filter), 'globalFilterItem-isExcluded': negate, }, this.props.className @@ -91,7 +85,7 @@ class FilterItemUI extends Component { id: 0, items: [ { - name: isFilterPinned(filter) + name: esFilters.isFilterPinned(filter) ? this.props.intl.formatMessage({ id: 'data.filter.filterBar.unpinFilterButtonLabel', defaultMessage: 'Unpin', @@ -209,23 +203,23 @@ class FilterItemUI extends Component { }); }; - private onSubmit = (filter: Filter) => { + private onSubmit = (filter: esFilters.Filter) => { this.closePopover(); this.props.onUpdate(filter); }; private onTogglePinned = () => { - const filter = toggleFilterPinned(this.props.filter); + const filter = esFilters.toggleFilterPinned(this.props.filter); this.props.onUpdate(filter); }; private onToggleNegated = () => { - const filter = toggleFilterNegated(this.props.filter); + const filter = esFilters.toggleFilterNegated(this.props.filter); this.props.onUpdate(filter); }; private onToggleDisabled = () => { - const filter = toggleFilterDisabled(this.props.filter); + const filter = esFilters.toggleFilterDisabled(this.props.filter); this.props.onUpdate(filter); }; } diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_view/index.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_view/index.tsx index 1dc93335d42be..6421691c4ef41 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_view/index.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_view/index.tsx @@ -18,13 +18,13 @@ */ import { EuiBadge, useInnerText } from '@elastic/eui'; -import { Filter, isFilterPinned } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import React, { SFC } from 'react'; import { getFilterDisplayText } from '../filter_editor/lib/get_filter_display_text'; +import { esFilters } from '../../../../../../../plugins/data/public'; interface Props { - filter: Filter; + filter: esFilters.Filter; displayName: string; [propName: string]: any; } @@ -44,7 +44,7 @@ export const FilterView: SFC = ({ values: { innerText }, }); - if (isFilterPinned(filter)) { + if (esFilters.isFilterPinned(filter)) { title = `${i18n.translate('data.filter.filterBar.pinnedFilterPrefix', { defaultMessage: 'Pinned', })} ${title}`; diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts index aae9c0754a8d8..08d5955d3fae9 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts @@ -19,12 +19,11 @@ import sinon from 'sinon'; -import { FilterStateStore } from '@kbn/es-query'; import { FilterStateManager } from './filter_state_manager'; import { StubState } from './test_helpers/stub_state'; import { getFilter } from './test_helpers/get_stub_filter'; -import { FilterManager } from '../../../../../../plugins/data/public'; +import { FilterManager, esFilters } from '../../../../../../plugins/data/public'; import { coreMock } from '../../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); @@ -59,7 +58,7 @@ describe('filter_state_manager', () => { }); test('should NOT watch state until both app and global state are defined', done => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); globalStateStub.filters.push(f1); setTimeout(() => { @@ -72,8 +71,8 @@ describe('filter_state_manager', () => { appStateStub.save = sinon.stub(); globalStateStub.save = sinon.stub(); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); filterManager.setFilters([f1, f2]); @@ -109,7 +108,7 @@ describe('filter_state_manager', () => { done(); }); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, true, true, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, true, true, 'age', 34); globalStateStub.filters.push(f1); }); @@ -122,7 +121,7 @@ describe('filter_state_manager', () => { done(); }); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); appStateStub.filters.push(f1); }); @@ -130,8 +129,8 @@ describe('filter_state_manager', () => { appStateStub.save = sinon.stub(); globalStateStub.save = sinon.stub(); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); filterManager.setFilters([f1, f2]); @@ -143,8 +142,8 @@ describe('filter_state_manager', () => { appStateStub.save = sinon.stub(); globalStateStub.save = sinon.stub(); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); filterManager.addFilters([f1, f2]); @@ -160,7 +159,7 @@ describe('filter_state_manager', () => { ** And triggers *another* filter manager update. */ test('should NOT re-trigger filter manager', done => { - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.setFilters([f1]); const setFiltersSpy = sinon.spy(filterManager, 'setFilters'); diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.ts index af8722c37c703..61821b7ad45e9 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.ts @@ -17,11 +17,9 @@ * under the License. */ -import { FilterStateStore } from '@kbn/es-query'; - import _ from 'lodash'; import { State } from 'ui/state_management/state'; -import { FilterManager } from '../../../../../../plugins/data/public'; +import { FilterManager, esFilters } from '../../../../../../plugins/data/public'; type GetAppStateFunc = () => State | undefined | null; @@ -73,8 +71,8 @@ export class FilterStateManager { const newGlobalFilters = _.cloneDeep(globalFilters); const newAppFilters = _.cloneDeep(appFilters); - FilterManager.setFiltersStore(newAppFilters, FilterStateStore.APP_STATE); - FilterManager.setFiltersStore(newGlobalFilters, FilterStateStore.GLOBAL_STATE); + FilterManager.setFiltersStore(newAppFilters, esFilters.FilterStateStore.APP_STATE); + FilterManager.setFiltersStore(newGlobalFilters, esFilters.FilterStateStore.GLOBAL_STATE); this.filterManager.setFilters(newGlobalFilters.concat(newAppFilters)); }, 10); diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/get_stub_filter.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/get_stub_filter.ts index 20d9e236f49be..5238efe5efa59 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/get_stub_filter.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/get_stub_filter.ts @@ -17,15 +17,15 @@ * under the License. */ -import { Filter, FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../plugins/data/public'; export function getFilter( - store: FilterStateStore, + store: esFilters.FilterStateStore, disabled: boolean, negated: boolean, queryKey: string, queryValue: any -): Filter { +): esFilters.Filter { return { $state: { store, diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/stub_state.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/stub_state.ts index ab92016d1b9ab..f0a4bdef0229d 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/stub_state.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/test_helpers/stub_state.ts @@ -19,11 +19,11 @@ import sinon from 'sinon'; -import { Filter } from '@kbn/es-query'; import { State } from 'ui/state_management/state'; +import { esFilters } from '../../../../../../../plugins/data/public'; export class StubState implements State { - filters: Filter[]; + filters: esFilters.Filter[]; save: sinon.SinonSpy; constructor() { diff --git a/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx b/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx index c186edf9a3ac9..12cea46f158c1 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx +++ b/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx @@ -19,7 +19,6 @@ import React, { useState, useEffect } from 'react'; import { Subscription } from 'rxjs'; -import { Filter } from '@kbn/es-query'; import { CoreStart } from 'src/core/public'; import { DataPublicPluginStart } from 'src/plugins/data/public'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; @@ -27,6 +26,7 @@ import { KibanaContextProvider } from '../../../../../../../../src/plugins/kiban import { TimefilterSetup } from '../../../timefilter'; import { SearchBar } from '../../../'; import { SearchBarOwnProps } from '.'; +import { esFilters } from '../../../../../../../plugins/data/public'; interface StatefulSearchBarDeps { core: CoreStart; @@ -40,7 +40,7 @@ export type StatetfulSearchBarProps = SearchBarOwnProps & { }; const defaultFiltersUpdated = (data: DataPublicPluginStart) => { - return (filters: Filter[]) => { + return (filters: esFilters.Filter[]) => { data.query.filterManager.setFilters(filters); }; }; diff --git a/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.tsx b/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.tsx index c7f8b02caf853..d3a26239e1006 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.tsx +++ b/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.tsx @@ -18,7 +18,6 @@ */ import { compact } from 'lodash'; -import { Filter } from '@kbn/es-query'; import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import classNames from 'classnames'; import React, { Component } from 'react'; @@ -39,14 +38,15 @@ import { KibanaReactContextValue, } from '../../../../../../../plugins/kibana_react/public'; import { IDataPluginServices } from '../../../types'; +import { esFilters } from '../../../../../../../plugins/data/public'; interface SearchBarInjectedDeps { kibana: KibanaReactContextValue; intl: InjectedIntl; timeHistory: TimeHistoryContract; // Filter bar - onFiltersUpdated?: (filters: Filter[]) => void; - filters?: Filter[]; + onFiltersUpdated?: (filters: esFilters.Filter[]) => void; + filters?: esFilters.Filter[]; // Date picker dateRangeFrom?: string; dateRangeTo?: string; diff --git a/src/legacy/core_plugins/data/public/search/search_bar/index.tsx b/src/legacy/core_plugins/data/public/search/search_bar/index.tsx index 0c677bea98536..ebde9d60b0b51 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/index.tsx +++ b/src/legacy/core_plugins/data/public/search/search_bar/index.tsx @@ -17,9 +17,9 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { RefreshInterval, TimeRange } from 'src/plugins/data/public'; import { Query } from '../../query/query_bar'; +import { esFilters } from '../../../../../../plugins/data/public'; export * from './components'; @@ -36,6 +36,6 @@ export interface SavedQueryAttributes { title: string; description: string; query: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; timefilter?: SavedQueryTimeFilter; } diff --git a/src/legacy/core_plugins/data/public/search/search_bar/lib/saved_query_service.test.ts b/src/legacy/core_plugins/data/public/search/search_bar/lib/saved_query_service.test.ts index ac5fdb7fe99d5..415da8a2c32cc 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/lib/saved_query_service.test.ts +++ b/src/legacy/core_plugins/data/public/search/search_bar/lib/saved_query_service.test.ts @@ -19,7 +19,7 @@ import { SavedQueryAttributes } from '../index'; import { createSavedQueryService } from './saved_query_service'; -import { FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../plugins/data/public'; const savedQueryAttributes: SavedQueryAttributes = { title: 'foo', @@ -43,7 +43,7 @@ const savedQueryAttributesWithFilters: SavedQueryAttributes = { filters: [ { query: { match_all: {} }, - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, negate: false, diff --git a/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.test.ts b/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.test.ts index 5e16120f3b3c2..df3e33060b01f 100644 --- a/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.test.ts +++ b/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.test.ts @@ -16,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ -import { RangeFilter } from '@kbn/es-query'; import { changeTimeFilter } from './change_time_filter'; import { TimeRange } from 'src/plugins/data/public'; import { timefilterServiceMock } from '../timefilter_service.mock'; +import { esFilters } from '../../../../../../plugins/data/public'; const timefilterMock = timefilterServiceMock.createSetupContract(); const timefilter = timefilterMock.timefilter; @@ -42,7 +42,7 @@ describe('changeTimeFilter()', () => { test('should change the timefilter to match the range gt/lt', () => { const filter: any = { range: { '@timestamp': { gt, lt } } }; - changeTimeFilter(timefilter, filter as RangeFilter); + changeTimeFilter(timefilter, filter as esFilters.RangeFilter); const { to, from } = timefilter.getTime(); @@ -52,7 +52,7 @@ describe('changeTimeFilter()', () => { test('should change the timefilter to match the range gte/lte', () => { const filter: any = { range: { '@timestamp': { gte: gt, lte: lt } } }; - changeTimeFilter(timefilter, filter as RangeFilter); + changeTimeFilter(timefilter, filter as esFilters.RangeFilter); const { to, from } = timefilter.getTime(); diff --git a/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.ts b/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.ts index 4780ddb6b4b44..7943aab3c151f 100644 --- a/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.ts +++ b/src/legacy/core_plugins/data/public/timefilter/lib/change_time_filter.ts @@ -19,10 +19,10 @@ import moment from 'moment'; import { keys } from 'lodash'; -import { RangeFilter } from '@kbn/es-query'; import { TimefilterContract } from '../timefilter'; +import { esFilters } from '../../../../../../plugins/data/public'; -export function convertRangeFilterToTimeRange(filter: RangeFilter) { +export function convertRangeFilterToTimeRange(filter: esFilters.RangeFilter) { const key = keys(filter.range)[0]; const values = filter.range[key]; @@ -32,6 +32,6 @@ export function convertRangeFilterToTimeRange(filter: RangeFilter) { }; } -export function changeTimeFilter(timeFilter: TimefilterContract, filter: RangeFilter) { +export function changeTimeFilter(timeFilter: TimefilterContract, filter: esFilters.RangeFilter) { timeFilter.setTime(convertRangeFilterToTimeRange(filter)); } diff --git a/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.test.ts b/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.test.ts index d55c9babeed79..981c50844c4f3 100644 --- a/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.test.ts +++ b/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.test.ts @@ -17,15 +17,23 @@ * under the License. */ -import { Filter, buildRangeFilter, buildQueryFilter, buildPhraseFilter } from '@kbn/es-query'; import { extractTimeFilter } from './extract_time_filter'; +import { esFilters } from '../../../../../../plugins/data/public'; describe('filter manager utilities', () => { describe('extractTimeFilter()', () => { test('should detect timeFilter', async () => { - const filters: Filter[] = [ - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'logstash-*'), - buildRangeFilter({ name: 'time' }, { gt: 1388559600000, lt: 1388646000000 }, 'logstash-*'), + const filters: esFilters.Filter[] = [ + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'logstash-*', + '' + ), + esFilters.buildRangeFilter( + { name: 'time' }, + { gt: 1388559600000, lt: 1388646000000 }, + 'logstash-*' + ), ]; const result = await extractTimeFilter('time', filters); @@ -34,9 +42,13 @@ describe('filter manager utilities', () => { }); test("should not return timeFilter when name doesn't match", async () => { - const filters: Filter[] = [ - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'logstash-*'), - buildRangeFilter({ name: '@timestamp' }, { from: 1, to: 2 }, 'logstash-*'), + const filters: esFilters.Filter[] = [ + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'logstash-*', + '' + ), + esFilters.buildRangeFilter({ name: '@timestamp' }, { from: 1, to: 2 }, 'logstash-*', ''), ]; const result = await extractTimeFilter('time', filters); @@ -45,9 +57,13 @@ describe('filter manager utilities', () => { }); test('should not return a non range filter, even when names match', async () => { - const filters: Filter[] = [ - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'logstash-*'), - buildPhraseFilter({ name: 'time' }, 'banana', 'logstash-*'), + const filters: esFilters.Filter[] = [ + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'logstash-*', + '' + ), + esFilters.buildPhraseFilter({ name: 'time' }, 'banana', 'logstash-*'), ]; const result = await extractTimeFilter('time', filters); diff --git a/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.ts b/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.ts index 22bda5b21295e..4281610cb63e4 100644 --- a/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.ts +++ b/src/legacy/core_plugins/data/public/timefilter/lib/extract_time_filter.ts @@ -18,13 +18,13 @@ */ import { keys, partition } from 'lodash'; -import { Filter, isRangeFilter, RangeFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; -export function extractTimeFilter(timeFieldName: string, filters: Filter[]) { - const [timeRangeFilter, restOfFilters] = partition(filters, (obj: Filter) => { +export function extractTimeFilter(timeFieldName: string, filters: esFilters.Filter[]) { + const [timeRangeFilter, restOfFilters] = partition(filters, (obj: esFilters.Filter) => { let key; - if (isRangeFilter(obj)) { + if (esFilters.isRangeFilter(obj)) { key = keys(obj.range)[0]; } @@ -33,6 +33,6 @@ export function extractTimeFilter(timeFieldName: string, filters: Filter[]) { return { restOfFilters, - timeRangeFilter: timeRangeFilter[0] as RangeFilter | undefined, + timeRangeFilter: timeRangeFilter[0] as esFilters.RangeFilter | undefined, }; } diff --git a/src/legacy/core_plugins/expressions/public/np_ready/public/types.ts b/src/legacy/core_plugins/expressions/public/np_ready/public/types.ts index a8d89b4456693..9d7b4fb6d0480 100644 --- a/src/legacy/core_plugins/expressions/public/np_ready/public/types.ts +++ b/src/legacy/core_plugins/expressions/public/np_ready/public/types.ts @@ -17,10 +17,9 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { TimeRange } from '../../../../../../plugins/data/public'; import { Adapters } from '../../../../../../plugins/inspector/public'; import { Query } from '../../../../../../plugins/data/public'; -export { TimeRange, Adapters, Filter, Query }; +export { TimeRange, Adapters, Query }; export * from '../../../../../../plugins/expressions/public'; diff --git a/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.js b/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.js index 9f0ed1dfb5097..65b1d41fa8239 100644 --- a/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.js +++ b/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/phrase_filter_manager.js @@ -20,12 +20,8 @@ import _ from 'lodash'; import { FilterManager } from './filter_manager.js'; import { - buildPhraseFilter, - buildPhrasesFilter, - getPhraseFilterField, - getPhraseFilterValue, - isPhraseFilter, -} from '@kbn/es-query'; + esFilters, +} from '../../../../../../plugins/data/public'; export class PhraseFilterManager extends FilterManager { constructor(controlId, fieldName, indexPattern, queryFilter) { @@ -43,12 +39,12 @@ export class PhraseFilterManager extends FilterManager { createFilter(phrases) { let newFilter; if (phrases.length === 1) { - newFilter = buildPhraseFilter( + newFilter = esFilters.buildPhraseFilter( this.indexPattern.fields.getByName(this.fieldName), phrases[0], this.indexPattern); } else { - newFilter = buildPhrasesFilter( + newFilter = esFilters.buildPhrasesFilter( this.indexPattern.fields.getByName(this.fieldName), phrases, this.indexPattern); @@ -107,12 +103,12 @@ export class PhraseFilterManager extends FilterManager { } // single phrase filter - if (isPhraseFilter(kbnFilter)) { - if (getPhraseFilterField(kbnFilter) !== this.fieldName) { + if (esFilters.isPhraseFilter(kbnFilter)) { + if (esFilters.getPhraseFilterField(kbnFilter) !== this.fieldName) { return; } - return getPhraseFilterValue(kbnFilter); + return esFilters.getPhraseFilterValue(kbnFilter); } // single phrase filter from bool filter diff --git a/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/range_filter_manager.js b/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/range_filter_manager.js index 1c8f5e2aa5a3e..3a232fd8b543d 100644 --- a/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/range_filter_manager.js +++ b/src/legacy/core_plugins/input_control_vis/public/control/filter_manager/range_filter_manager.js @@ -19,7 +19,7 @@ import _ from 'lodash'; import { FilterManager } from './filter_manager.js'; -import { buildRangeFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; // Convert slider value into ES range filter function toRange(sliderValue) { @@ -55,7 +55,7 @@ export class RangeFilterManager extends FilterManager { * @return {object} range filter */ createFilter(value) { - const newFilter = buildRangeFilter( + const newFilter = esFilters.buildRangeFilter( this.indexPattern.fields.getByName(this.fieldName), toRange(value), this.indexPattern); diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.tsx b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.tsx index 7a0398e86a60d..5fa3a938ed9df 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.tsx +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.tsx @@ -35,7 +35,6 @@ import { } from 'ui/state_management/app_state'; import { KbnUrl } from 'ui/url/kbn_url'; -import { Filter } from '@kbn/es-query'; import { TimeRange } from 'src/plugins/data/public'; import { IndexPattern } from 'ui/index_patterns'; import { IPrivate } from 'ui/private'; @@ -46,6 +45,7 @@ import { Subscription } from 'rxjs'; import { ViewMode } from '../../../embeddable_api/public/np_ready/public'; import { SavedObjectDashboard } from './saved_dashboard/saved_dashboard'; import { DashboardAppState, SavedDashboardPanel, ConfirmModalFn } from './types'; +import { esFilters } from '../../../../../../src/plugins/data/public'; import { DashboardAppController } from './dashboard_app_controller'; @@ -55,7 +55,7 @@ export interface DashboardAppScope extends ng.IScope { screenTitle: string; model: { query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; timeRestore: boolean; title: string; description: string; @@ -81,9 +81,9 @@ export interface DashboardAppScope extends ng.IScope { isPaused: boolean; refreshInterval: any; }) => void; - onFiltersUpdated: (filters: Filter[]) => void; + onFiltersUpdated: (filters: esFilters.Filter[]) => void; onCancelApplyFilters: () => void; - onApplyFilters: (filters: Filter[]) => void; + onApplyFilters: (filters: esFilters.Filter[]) => void; onQuerySaved: (savedQuery: SavedQuery) => void; onSavedQueryUpdated: (savedQuery: SavedQuery) => void; onClearSavedQuery: () => void; diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx index abf7b22a6e48c..64c7560947681 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx @@ -48,7 +48,6 @@ import { } from 'ui/state_management/app_state'; import { KbnUrl } from 'ui/url/kbn_url'; -import { Filter } from '@kbn/es-query'; import { IndexPattern } from 'ui/index_patterns'; import { IPrivate } from 'ui/private'; import { Query, SavedQuery } from 'src/legacy/core_plugins/data/public'; @@ -59,6 +58,7 @@ import { npStart } from 'ui/new_platform'; import { SavedObjectFinder } from 'ui/saved_objects/components/saved_object_finder'; import { extractTimeFilter, changeTimeFilter } from '../../../data/public'; import { start as data } from '../../../data/public/legacy'; +import { esFilters } from '../../../../../plugins/data/public'; import { DashboardContainer, @@ -514,7 +514,7 @@ export class DashboardAppController { } ); - $scope.$watch('appState.$newFilters', (filters: Filter[] = []) => { + $scope.$watch('appState.$newFilters', (filters: esFilters.Filter[] = []) => { if (filters.length === 1) { $scope.onApplyFilters(filters); } diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts index 7c1fc771de349..8ffabe5add1c3 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts @@ -20,7 +20,6 @@ import { i18n } from '@kbn/i18n'; import _ from 'lodash'; -import { Filter } from '@kbn/es-query'; import { stateMonitorFactory, StateMonitor } from 'ui/state_management/state_monitor_factory'; import { Timefilter } from 'ui/timefilter'; import { AppStateClass as TAppStateClass } from 'ui/state_management/app_state'; @@ -29,6 +28,7 @@ import { Moment } from 'moment'; import { DashboardContainer } from 'src/legacy/core_plugins/dashboard_embeddable_container/public/np_ready/public'; import { ViewMode } from '../../../../../../src/plugins/embeddable/public'; +import { esFilters } from '../../../../../../src/plugins/data/public'; import { Query } from '../../../data/public'; import { getAppStateDefaults, migrateAppState } from './lib'; @@ -50,7 +50,7 @@ export class DashboardStateManager { public lastSavedDashboardFilters: { timeTo?: string | Moment; timeFrom?: string | Moment; - filterBars: Filter[]; + filterBars: esFilters.Filter[]; query: Query; }; private stateDefaults: DashboardAppStateDefaults; @@ -303,7 +303,7 @@ export class DashboardStateManager { return this.savedDashboard.timeRestore; } - public getLastSavedFilterBars(): Filter[] { + public getLastSavedFilterBars(): esFilters.Filter[] { return this.lastSavedDashboardFilters.filterBars; } @@ -461,7 +461,7 @@ export class DashboardStateManager { * Applies the current filter state to the dashboard. * @param filter An array of filter bar filters. */ - public applyFilters(query: Query, filters: Filter[]) { + public applyFilters(query: Query, filters: esFilters.Filter[]) { this.appState.query = query; this.savedDashboard.searchSource.setField('query', query); this.savedDashboard.searchSource.setField('filter', filters); diff --git a/src/legacy/core_plugins/kibana/public/dashboard/lib/filter_utils.ts b/src/legacy/core_plugins/kibana/public/dashboard/lib/filter_utils.ts index 1fd50081c58bd..19a0c32210737 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/lib/filter_utils.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/lib/filter_utils.ts @@ -19,7 +19,7 @@ import _ from 'lodash'; import moment, { Moment } from 'moment'; -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; /** * @typedef {Object} QueryFilter @@ -65,9 +65,9 @@ export class FilterUtils { * @param filters {Array.} * @returns {Array.} */ - public static cleanFiltersForComparison(filters: Filter[]) { + public static cleanFiltersForComparison(filters: esFilters.Filter[]) { return _.map(filters, filter => { - const f: Partial = _.omit(filter, ['$$hashKey', '$state']); + const f: Partial = _.omit(filter, ['$$hashKey', '$state']); if (f.meta) { // f.meta.value is the value displayed in the filter bar. // It may also be loaded differently and shouldn't be used in this comparison. diff --git a/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.test.ts b/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.test.ts index 1f503ee675407..ae3edae3b85d6 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.test.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.test.ts @@ -18,12 +18,12 @@ */ import { moveFiltersToQuery, Pre600FilterQuery } from './move_filters_to_query'; -import { Filter, FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; -const filter: Filter = { +const filter: esFilters.Filter = { meta: { disabled: false, negate: false, alias: '' }, query: {}, - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, }; const queryFilter: Pre600FilterQuery = { @@ -38,7 +38,7 @@ test('Migrates an old filter query into the query field', () => { expect(newSearchSource).toEqual({ filter: [ { - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { alias: '', disabled: false, diff --git a/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.ts b/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.ts index 153bdeba9d35f..8522495b9dedb 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/migrations/move_filters_to_query.ts @@ -18,7 +18,7 @@ */ import { Query } from 'src/legacy/core_plugins/data/public'; -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; export interface Pre600FilterQuery { // pre 6.0.0 global query:queryString:options were stored per dashboard and would @@ -30,18 +30,18 @@ export interface Pre600FilterQuery { export interface SearchSourcePre600 { // I encountered at least one export from 7.0.0-alpha that was missing the filter property in here. // The maps data in esarchives actually has it, but I don't know how/when they created it. - filter?: Array; + filter?: Array; } export interface SearchSource730 { - filter: Filter[]; + filter: esFilters.Filter[]; query: Query; highlightAll?: boolean; version?: boolean; } -function isQueryFilter(filter: Filter | { query: unknown }): filter is Pre600FilterQuery { - return filter.query && !(filter as Filter).meta; +function isQueryFilter(filter: esFilters.Filter | { query: unknown }): filter is Pre600FilterQuery { + return filter.query && !(filter as esFilters.Filter).meta; } export function moveFiltersToQuery( diff --git a/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.d.ts b/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.d.ts index 1231ca28ed014..5b860b0a2cc7c 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.d.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.d.ts @@ -19,10 +19,9 @@ import { SearchSource } from 'ui/courier'; import { SavedObject } from 'ui/saved_objects/saved_object'; -import moment from 'moment'; import { RefreshInterval } from 'src/plugins/data/public'; import { Query } from 'src/legacy/core_plugins/data/public'; -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; export interface SavedObjectDashboard extends SavedObject { id?: string; @@ -41,5 +40,5 @@ export interface SavedObjectDashboard extends SavedObject { destroy: () => void; refreshInterval?: RefreshInterval; getQuery(): Query; - getFilters(): Filter[]; + getFilters(): esFilters.Filter[]; } diff --git a/src/legacy/core_plugins/kibana/public/dashboard/types.ts b/src/legacy/core_plugins/kibana/public/dashboard/types.ts index ccccc89004e36..5aaca7b62094f 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/types.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/types.ts @@ -18,7 +18,6 @@ */ import { AppState } from 'ui/state_management/app_state'; -import { Filter } from '@kbn/es-query'; import { Query } from 'src/legacy/core_plugins/data/public'; import { AppState as TAppState } from 'ui/state_management/app_state'; import { ViewMode } from 'src/plugins/embeddable/public'; @@ -30,6 +29,7 @@ import { RawSavedDashboardPanel640To720, RawSavedDashboardPanel730ToLatest, } from './migrations/types'; +import { esFilters } from '../../../../../plugins/data/public'; export type NavAction = (anchorElement?: any) => void; @@ -110,7 +110,7 @@ export interface DashboardAppStateParameters { useMargins: boolean; }; query: Query | string; - filters: Filter[]; + filters: esFilters.Filter[]; viewMode: ViewMode; savedQuery?: string; } diff --git a/src/legacy/core_plugins/kibana/public/discover/angular/context/api/context.ts b/src/legacy/core_plugins/kibana/public/discover/angular/context/api/context.ts index 268f176f2c61e..3314bbbf189c4 100644 --- a/src/legacy/core_plugins/kibana/public/discover/angular/context/api/context.ts +++ b/src/legacy/core_plugins/kibana/public/discover/angular/context/api/context.ts @@ -17,7 +17,6 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { IndexPatterns, IndexPattern, getServices } from '../../../kibana_services'; import { reverseSortDir, SortDirection } from './utils/sorting'; import { extractNanos, convertIsoToMillis } from './utils/date_conversion'; @@ -25,6 +24,7 @@ import { fetchHitsInInterval } from './utils/fetch_hits_in_interval'; import { generateIntervals } from './utils/generate_intervals'; import { getEsQuerySearchAfter } from './utils/get_es_query_search_after'; import { getEsQuerySort } from './utils/get_es_query_sort'; +import { esFilters } from '../../../../../../../../plugins/data/public'; export type SurrDocType = 'successors' | 'predecessors'; export interface EsHitRecord { @@ -67,7 +67,7 @@ function fetchContextProvider(indexPatterns: IndexPatterns) { tieBreakerField: string, sortDir: SortDirection, size: number, - filters: Filter[] + filters: esFilters.Filter[] ) { if (typeof anchor !== 'object' || anchor === null) { return []; @@ -112,7 +112,7 @@ function fetchContextProvider(indexPatterns: IndexPatterns) { return documents; } - async function createSearchSource(indexPattern: IndexPattern, filters: Filter[]) { + async function createSearchSource(indexPattern: IndexPattern, filters: esFilters.Filter[]) { return new SearchSource() .setParent(false) .setField('index', indexPattern) diff --git a/src/legacy/core_plugins/kibana/public/discover/angular/doc_table/components/table_row.js b/src/legacy/core_plugins/kibana/public/discover/angular/doc_table/components/table_row.js index 355d9defbb63d..6f5a94442e977 100644 --- a/src/legacy/core_plugins/kibana/public/discover/angular/doc_table/components/table_row.js +++ b/src/legacy/core_plugins/kibana/public/discover/angular/doc_table/components/table_row.js @@ -26,10 +26,10 @@ import { noWhiteSpace } from '../../../../../common/utils/no_white_space'; import openRowHtml from './table_row/open.html'; import detailsHtml from './table_row/details.html'; import { getServices } from '../../../kibana_services'; -import { disableFilter } from '@kbn/es-query'; import { dispatchRenderComplete } from '../../../../../../../../plugins/kibana_utils/public'; import cellTemplateHtml from '../components/table_row/cell.html'; import truncateByHeightTemplateHtml from '../components/table_row/truncate_by_height.html'; +import { esFilters } from '../../../../../../../../plugins/data/public'; const module = getServices().uiModules.get('app/discover'); @@ -117,7 +117,7 @@ module.directive('kbnTableRow', function ($compile, $httpParamSerializer, kbnUrl const hash = $httpParamSerializer({ _a: rison.encode({ columns: $scope.columns, - filters: ($scope.filters || []).map(disableFilter), + filters: ($scope.filters || []).map(esFilters.disableFilter), }), }); return `${path}?${hash}`; diff --git a/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts b/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts index e777501d35ca0..31b28d21fe8d8 100644 --- a/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts +++ b/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts @@ -19,12 +19,12 @@ import _ from 'lodash'; import * as Rx from 'rxjs'; import { Subscription } from 'rxjs'; -import { Filter, FilterStateStore } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { TExecuteTriggerActions } from 'src/plugins/ui_actions/public'; import { TimeRange, onlyDisabledFiltersChanged } from '../../../../../../plugins/data/public'; import { setup as data } from '../../../../data/public/legacy'; import { Query, getTime } from '../../../../data/public'; +import { esFilters } from '../../../../../../plugins/data/public'; import { APPLY_FILTER_TRIGGER, Container, @@ -75,7 +75,7 @@ export interface FilterManager { values: string | string[], operation: string, index: number - ) => Filter[]; + ) => esFilters.Filter[]; } interface SearchEmbeddableConfig { @@ -105,7 +105,7 @@ export class SearchEmbeddable extends Embeddable private abortController?: AbortController; private prevTimeRange?: TimeRange; - private prevFilters?: Filter[]; + private prevFilters?: esFilters.Filter[]; private prevQuery?: Query; constructor( @@ -248,7 +248,7 @@ export class SearchEmbeddable extends Embeddable let filters = this.filterGen.generate(field, value, operator, indexPattern.id); filters = filters.map(filter => ({ ...filter, - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, })); await this.executeTriggerActions(APPLY_FILTER_TRIGGER, { diff --git a/src/legacy/core_plugins/kibana/public/discover/embeddable/types.ts b/src/legacy/core_plugins/kibana/public/discover/embeddable/types.ts index db8d2afc7aff3..5473ec0e7b8b4 100644 --- a/src/legacy/core_plugins/kibana/public/discover/embeddable/types.ts +++ b/src/legacy/core_plugins/kibana/public/discover/embeddable/types.ts @@ -19,16 +19,16 @@ import { TimeRange } from 'src/plugins/data/public'; import { Query } from 'src/legacy/core_plugins/data/public'; -import { Filter } from '@kbn/es-query'; import { EmbeddableInput, EmbeddableOutput, IEmbeddable } from 'src/plugins/embeddable/public'; import { StaticIndexPattern } from '../kibana_services'; import { SavedSearch } from '../types'; import { SortOrder } from '../angular/doc_table/components/table_header/helpers'; +import { esFilters } from '../../../../../../plugins/data/public'; export interface SearchInput extends EmbeddableInput { timeRange: TimeRange; query?: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; hidePanelTitles?: boolean; columns?: string[]; sort?: SortOrder[]; diff --git a/src/legacy/core_plugins/kibana/public/visualize/embeddable/visualize_embeddable.ts b/src/legacy/core_plugins/kibana/public/visualize/embeddable/visualize_embeddable.ts index ef9c9a00f980b..318686b26f6f2 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/embeddable/visualize_embeddable.ts +++ b/src/legacy/core_plugins/kibana/public/visualize/embeddable/visualize_embeddable.ts @@ -21,8 +21,11 @@ import _ from 'lodash'; import { EmbeddedVisualizeHandler } from 'ui/visualize/loader/embedded_visualize_handler'; import { Subscription } from 'rxjs'; import * as Rx from 'rxjs'; -import { Filter } from '@kbn/es-query'; -import { TimeRange, onlyDisabledFiltersChanged } from '../../../../../../plugins/data/public'; +import { + TimeRange, + onlyDisabledFiltersChanged, + esFilters, +} from '../../../../../../plugins/data/public'; import { Query } from '../../../../data/public'; import { VISUALIZE_EMBEDDABLE_TYPE } from './constants'; @@ -55,7 +58,7 @@ export interface VisualizeEmbeddableConfiguration { export interface VisualizeInput extends EmbeddableInput { timeRange?: TimeRange; query?: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; vis?: { colors?: { [key: string]: string }; }; @@ -79,7 +82,7 @@ export class VisualizeEmbeddable extends Embeddable agg.buckets.some(bucket => bucket.key === '__missing__') ) { filters.push( - buildExistsFilter( + esFilters.buildExistsFilter( aggWithOtherBucket.params.field, aggWithOtherBucket.params.field.indexPattern ) @@ -232,7 +233,7 @@ export const mergeOtherBucketAggResponse = ( ); const requestFilterTerms = getOtherAggTerms(requestAgg, key, otherAgg); - const phraseFilter = buildPhrasesFilter( + const phraseFilter = esFilters.buildPhrasesFilter( otherAgg.params.field, requestFilterTerms, otherAgg.params.field.indexPattern @@ -243,7 +244,7 @@ export const mergeOtherBucketAggResponse = ( if (aggResultBuckets.some(bucket => bucket.key === '__missing__')) { bucket.filters.push( - buildExistsFilter(otherAgg.params.field, otherAgg.params.field.indexPattern) + esFilters.buildExistsFilter(otherAgg.params.field, otherAgg.params.field.indexPattern) ); } aggResultBuckets.push(bucket); diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.test.ts index f67fa55b27859..9426df7d34c29 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.test.ts @@ -18,19 +18,19 @@ */ import moment from 'moment'; -import { RangeFilter } from '@kbn/es-query'; import { createFilterDateHistogram } from './date_histogram'; import { intervalOptions } from '../_interval_options'; import { AggConfigs } from '../../agg_configs'; import { IBucketDateHistogramAggConfig } from '../date_histogram'; import { BUCKET_TYPES } from '../bucket_agg_types'; +import { esFilters } from '../../../../../../plugins/data/public'; jest.mock('ui/new_platform'); describe('AggConfig Filters', () => { describe('date_histogram', () => { let agg: IBucketDateHistogramAggConfig; - let filter: RangeFilter; + let filter: esFilters.RangeFilter; let bucketStart: any; let field: any; diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.ts index 8c6140cc4b37a..f91a92eab1c33 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/date_histogram.ts @@ -18,8 +18,8 @@ */ import moment from 'moment'; -import { buildRangeFilter } from '@kbn/es-query'; import { IBucketDateHistogramAggConfig } from '../date_histogram'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterDateHistogram = ( agg: IBucketDateHistogramAggConfig, @@ -28,7 +28,7 @@ export const createFilterDateHistogram = ( const start = moment(key); const interval = agg.buckets.getInterval(); - return buildRangeFilter( + return esFilters.buildRangeFilter( agg.params.field, { gte: start.toISOString(), diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.ts index cd4b0ffc215b0..01689d954a072 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/date_range.ts @@ -17,16 +17,16 @@ * under the License. */ -import { buildRangeFilter, RangeFilterParams } from '@kbn/es-query'; import moment from 'moment'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { DateRangeKey } from '../date_range'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterDateRange = (agg: IBucketAggConfig, { from, to }: DateRangeKey) => { - const filter: RangeFilterParams = {}; + const filter: esFilters.RangeFilterParams = {}; if (from) filter.gte = moment(from).toISOString(); if (to) filter.lt = moment(to).toISOString(); if (to && from) filter.format = 'strict_date_optional_time'; - return buildRangeFilter(agg.params.field, filter, agg.getIndexPattern()); + return esFilters.buildRangeFilter(agg.params.field, filter, agg.getIndexPattern()); }; diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/filters.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/filters.ts index bf30b333056bc..6b614514580b6 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/filters.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/filters.ts @@ -18,8 +18,8 @@ */ import { get } from 'lodash'; -import { buildQueryFilter } from '@kbn/es-query'; import { IBucketAggConfig } from '../_bucket_agg_type'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterFilters = (aggConfig: IBucketAggConfig, key: string) => { // have the aggConfig write agg dsl params @@ -28,6 +28,6 @@ export const createFilterFilters = (aggConfig: IBucketAggConfig, key: string) => const indexPattern = aggConfig.getIndexPattern(); if (filter && indexPattern && indexPattern.id) { - return buildQueryFilter(filter.query, indexPattern.id, key); + return esFilters.buildQueryFilter(filter.query, indexPattern.id, key); } }; diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.ts index 37d5c6bc8adc1..fc587fa9ecdb6 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/histogram.ts @@ -17,14 +17,14 @@ * under the License. */ -import { buildRangeFilter, RangeFilterParams } from '@kbn/es-query'; import { IBucketAggConfig } from '../_bucket_agg_type'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterHistogram = (aggConfig: IBucketAggConfig, key: string) => { const value = parseInt(key, 10); - const params: RangeFilterParams = { gte: value, lt: value + aggConfig.params.interval }; + const params: esFilters.RangeFilterParams = { gte: value, lt: value + aggConfig.params.interval }; - return buildRangeFilter( + return esFilters.buildRangeFilter( aggConfig.params.field, params, aggConfig.getIndexPattern(), diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.ts index 83769578725f2..803f6d97ae42d 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/ip_range.ts @@ -17,13 +17,13 @@ * under the License. */ -import { buildRangeFilter, RangeFilterParams } from '@kbn/es-query'; import { CidrMask } from '../../../utils/cidr_mask'; import { IBucketAggConfig } from '../_bucket_agg_type'; import { IpRangeKey } from '../ip_range'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterIpRange = (aggConfig: IBucketAggConfig, key: IpRangeKey) => { - let range: RangeFilterParams; + let range: esFilters.RangeFilterParams; if (key.type === 'mask') { range = new CidrMask(key.mask).getRange(); @@ -34,7 +34,7 @@ export const createFilterIpRange = (aggConfig: IBucketAggConfig, key: IpRangeKey }; } - return buildRangeFilter( + return esFilters.buildRangeFilter( aggConfig.params.field, { gte: range.from, lte: range.to }, aggConfig.getIndexPattern() diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/range.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/range.ts index cf2c83884651a..929827c6e3fec 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/range.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/range.ts @@ -17,11 +17,11 @@ * under the License. */ -import { buildRangeFilter } from '@kbn/es-query'; import { IBucketAggConfig } from '../_bucket_agg_type'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterRange = (aggConfig: IBucketAggConfig, params: any) => { - return buildRangeFilter( + return esFilters.buildRangeFilter( aggConfig.params.field, params, aggConfig.getIndexPattern(), diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/terms.test.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/terms.test.ts index b00e939eac8d8..42f8349d5a2a3 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/terms.test.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/terms.test.ts @@ -16,10 +16,11 @@ * specific language governing permissions and limitations * under the License. */ -import { ExistsFilter, Filter } from '@kbn/es-query'; + import { createFilterTerms } from './terms'; import { AggConfigs } from '../../agg_configs'; import { BUCKET_TYPES } from '../bucket_agg_types'; +import { esFilters } from '../../../../../../plugins/data/public'; jest.mock('ui/new_platform'); @@ -48,7 +49,7 @@ describe('AggConfig Filters', () => { { type: BUCKET_TYPES.TERMS, schema: 'segment', params: { field: 'field' } }, ]); - const filter = createFilterTerms(aggConfigs.aggs[0], 'apache', {}) as Filter; + const filter = createFilterTerms(aggConfigs.aggs[0], 'apache', {}) as esFilters.Filter; expect(filter).toHaveProperty('query'); expect(filter.query).toHaveProperty('match_phrase'); @@ -63,14 +64,14 @@ describe('AggConfig Filters', () => { { type: BUCKET_TYPES.TERMS, schema: 'segment', params: { field: 'field' } }, ]); - const filterFalse = createFilterTerms(aggConfigs.aggs[0], '', {}) as Filter; + const filterFalse = createFilterTerms(aggConfigs.aggs[0], '', {}) as esFilters.Filter; expect(filterFalse).toHaveProperty('query'); expect(filterFalse.query).toHaveProperty('match_phrase'); expect(filterFalse.query.match_phrase).toHaveProperty('field'); expect(filterFalse.query.match_phrase.field).toBeFalsy(); - const filterTrue = createFilterTerms(aggConfigs.aggs[0], '1', {}) as Filter; + const filterTrue = createFilterTerms(aggConfigs.aggs[0], '1', {}) as esFilters.Filter; expect(filterTrue).toHaveProperty('query'); expect(filterTrue.query).toHaveProperty('match_phrase'); @@ -82,7 +83,11 @@ describe('AggConfig Filters', () => { const aggConfigs = getAggConfigs([ { type: BUCKET_TYPES.TERMS, schema: 'segment', params: { field: 'field' } }, ]); - const filter = createFilterTerms(aggConfigs.aggs[0], '__missing__', {}) as ExistsFilter; + const filter = createFilterTerms( + aggConfigs.aggs[0], + '__missing__', + {} + ) as esFilters.ExistsFilter; expect(filter).toHaveProperty('exists'); expect(filter.exists).toHaveProperty('field', 'field'); @@ -98,7 +103,7 @@ describe('AggConfig Filters', () => { const [filter] = createFilterTerms(aggConfigs.aggs[0], '__other__', { terms: ['apache'], - }) as Filter[]; + }) as esFilters.Filter[]; expect(filter).toHaveProperty('query'); expect(filter.query).toHaveProperty('bool'); diff --git a/src/legacy/ui/public/agg_types/buckets/create_filter/terms.ts b/src/legacy/ui/public/agg_types/buckets/create_filter/terms.ts index e5d4406c752c7..5bd770e672786 100644 --- a/src/legacy/ui/public/agg_types/buckets/create_filter/terms.ts +++ b/src/legacy/ui/public/agg_types/buckets/create_filter/terms.ts @@ -17,8 +17,8 @@ * under the License. */ -import { Filter, buildPhraseFilter, buildPhrasesFilter, buildExistsFilter } from '@kbn/es-query'; import { IBucketAggConfig } from '../_bucket_agg_type'; +import { esFilters } from '../../../../../../plugins/data/public'; export const createFilterTerms = (aggConfig: IBucketAggConfig, key: string, params: any) => { const field = aggConfig.params.field; @@ -27,20 +27,20 @@ export const createFilterTerms = (aggConfig: IBucketAggConfig, key: string, para if (key === '__other__') { const terms = params.terms; - const phraseFilter = buildPhrasesFilter(field, terms, indexPattern); + const phraseFilter = esFilters.buildPhrasesFilter(field, terms, indexPattern); phraseFilter.meta.negate = true; - const filters: Filter[] = [phraseFilter]; + const filters: esFilters.Filter[] = [phraseFilter]; if (terms.some((term: string) => term === '__missing__')) { - filters.push(buildExistsFilter(field, indexPattern)); + filters.push(esFilters.buildExistsFilter(field, indexPattern)); } return filters; } else if (key === '__missing__') { - const existsFilter = buildExistsFilter(field, indexPattern); + const existsFilter = esFilters.buildExistsFilter(field, indexPattern); existsFilter.meta.negate = true; return existsFilter; } - return buildPhraseFilter(field, key, indexPattern); + return esFilters.buildPhraseFilter(field, key, indexPattern); }; diff --git a/src/legacy/ui/public/agg_types/buckets/date_histogram.ts b/src/legacy/ui/public/agg_types/buckets/date_histogram.ts index 4c2e67f758a7e..e86d561a1c79b 100644 --- a/src/legacy/ui/public/agg_types/buckets/date_histogram.ts +++ b/src/legacy/ui/public/agg_types/buckets/date_histogram.ts @@ -32,7 +32,6 @@ import { ScaleMetricsParamEditor } from '../../vis/editors/default/controls/scal import { dateHistogramInterval } from '../../../../core_plugins/data/public'; import { writeParams } from '../agg_params'; import { AggConfigs } from '../agg_configs'; -import { AggConfig } from '../agg_config'; import { isMetricAggType } from '../metrics/metric_agg_type'; import { KBN_FIELD_TYPES } from '../../../../../plugins/data/common'; @@ -189,7 +188,7 @@ export const dateHistogramBucketAgg = new BucketAggType isMetricAggType(a.type)); - const all = _.every(metrics, (a: AggConfig) => { + const all = _.every(metrics, (a: IBucketAggConfig) => { const { type } = a; if (isMetricAggType(type)) { diff --git a/src/legacy/ui/public/agg_types/buckets/date_range.ts b/src/legacy/ui/public/agg_types/buckets/date_range.ts index dd7f0cb972ae2..4de6002e2e374 100644 --- a/src/legacy/ui/public/agg_types/buckets/date_range.ts +++ b/src/legacy/ui/public/agg_types/buckets/date_range.ts @@ -21,9 +21,8 @@ import moment from 'moment-timezone'; import { i18n } from '@kbn/i18n'; import { npStart } from 'ui/new_platform'; import { BUCKET_TYPES } from './bucket_agg_types'; -import { BucketAggType } from './_bucket_agg_type'; +import { BucketAggType, IBucketAggConfig } from './_bucket_agg_type'; import { createFilterDateRange } from './create_filter/date_range'; -import { AggConfig } from '../agg_config'; import { FieldFormat } from '../../../../../plugins/data/common/field_formats'; import { DateRangesParamEditor } from '../../vis/editors/default/controls/date_ranges'; @@ -64,7 +63,7 @@ export const dateRangeBucketAgg = new BucketAggType({ name: 'field', type: 'field', filterFieldTypes: KBN_FIELD_TYPES.DATE, - default(agg: AggConfig) { + default(agg: IBucketAggConfig) { return agg.getIndexPattern().timeFieldName; }, }, @@ -83,7 +82,7 @@ export const dateRangeBucketAgg = new BucketAggType({ default: undefined, // Implimentation method is the same as that of date_histogram serialize: () => undefined, - write: (agg: AggConfig, output: Record) => { + write: (agg: IBucketAggConfig, output: Record) => { const field = agg.getParam('field'); let tz = agg.getParam('time_zone'); diff --git a/src/legacy/ui/public/agg_types/buckets/geo_hash.ts b/src/legacy/ui/public/agg_types/buckets/geo_hash.ts index 555aa94b636b8..1716891231b83 100644 --- a/src/legacy/ui/public/agg_types/buckets/geo_hash.ts +++ b/src/legacy/ui/public/agg_types/buckets/geo_hash.ts @@ -26,7 +26,6 @@ import { IsFilteredByCollarParamEditor } from '../../vis/editors/default/control import { PrecisionParamEditor } from '../../vis/editors/default/controls/precision'; import { geohashColumns } from '../../utils/decode_geo_hash'; import { AggGroupNames } from '../../vis/editors/default/agg_groups'; -import { AggConfig } from '../agg_config'; import { KBN_FIELD_TYPES } from '../../../../../plugins/data/common'; // @ts-ignore @@ -143,7 +142,7 @@ export const geoHashBucketAgg = new BucketAggType({ }, ], getRequestAggs(agg) { - const aggs: AggConfig[] = []; + const aggs: IBucketAggConfig[] = []; const params = agg.params; if (params.isFilteredByCollar && agg.getField()) { diff --git a/src/legacy/ui/public/agg_types/buckets/histogram.ts b/src/legacy/ui/public/agg_types/buckets/histogram.ts index 74a2da4a0eb67..fba2f47010c34 100644 --- a/src/legacy/ui/public/agg_types/buckets/histogram.ts +++ b/src/legacy/ui/public/agg_types/buckets/histogram.ts @@ -28,7 +28,6 @@ import { NumberIntervalParamEditor } from '../../vis/editors/default/controls/nu import { MinDocCountParamEditor } from '../../vis/editors/default/controls/min_doc_count'; import { HasExtendedBoundsParamEditor } from '../../vis/editors/default/controls/has_extended_bounds'; import { ExtendedBoundsParamEditor } from '../../vis/editors/default/controls/extended_bounds'; -import { AggConfig } from '../agg_config'; import { KBN_FIELD_TYPES } from '../../../../../plugins/data/common'; import { BUCKET_TYPES } from './bucket_agg_types'; @@ -177,7 +176,7 @@ export const histogramBucketAgg = new BucketAggType({ name: 'min_doc_count', default: false, editorComponent: MinDocCountParamEditor, - write(aggConfig: AggConfig, output: Record) { + write(aggConfig: IBucketAggConfig, output: Record) { if (aggConfig.params.min_doc_count) { output.params.min_doc_count = 0; } else { @@ -198,14 +197,14 @@ export const histogramBucketAgg = new BucketAggType({ max: '', }, editorComponent: ExtendedBoundsParamEditor, - write(aggConfig: AggConfig, output: Record) { + write(aggConfig: IBucketAggConfig, output: Record) { const { min, max } = aggConfig.params.extended_bounds; if (aggConfig.params.has_extended_bounds && (min || min === 0) && (max || max === 0)) { output.params.extended_bounds = { min, max }; } }, - shouldShow: (aggConfig: AggConfig) => aggConfig.params.has_extended_bounds, + shouldShow: (aggConfig: IBucketAggConfig) => aggConfig.params.has_extended_bounds, }, ], }); diff --git a/src/legacy/ui/public/agg_types/buckets/migrate_include_exclude_format.ts b/src/legacy/ui/public/agg_types/buckets/migrate_include_exclude_format.ts index 2bf0930d37684..e4527ff87f48c 100644 --- a/src/legacy/ui/public/agg_types/buckets/migrate_include_exclude_format.ts +++ b/src/legacy/ui/public/agg_types/buckets/migrate_include_exclude_format.ts @@ -18,7 +18,6 @@ */ import { isString, isObject } from 'lodash'; -import { AggConfig } from 'ui/agg_types'; import { IBucketAggConfig, BucketAggType, BucketAggParam } from './_bucket_agg_type'; export const isType = (type: string) => { @@ -32,12 +31,16 @@ export const isType = (type: string) => { export const isStringType = isType('string'); export const migrateIncludeExcludeFormat = { - serialize(this: BucketAggParam, value: any, agg: AggConfig) { + serialize(this: BucketAggParam, value: any, agg: IBucketAggConfig) { if (this.shouldShow && !this.shouldShow(agg)) return; if (!value || isString(value)) return value; else return value.pattern; }, - write(this: BucketAggType, aggConfig: AggConfig, output: Record) { + write( + this: BucketAggType, + aggConfig: IBucketAggConfig, + output: Record + ) { const value = aggConfig.getParam(this.name); if (isObject(value)) { diff --git a/src/legacy/ui/public/courier/search_source/search_source.js b/src/legacy/ui/public/courier/search_source/search_source.js index ed8d15d61c1db..729de41ed77db 100644 --- a/src/legacy/ui/public/courier/search_source/search_source.js +++ b/src/legacy/ui/public/courier/search_source/search_source.js @@ -71,13 +71,13 @@ import _ from 'lodash'; import angular from 'angular'; -import { buildEsQuery, getEsQueryConfig } from '@kbn/es-query'; +import { getEsQueryConfig, buildEsQuery } from '@kbn/es-query'; import { normalizeSortRequest } from './_normalize_sort_request'; import { fetchSoon } from '../fetch'; import { fieldWildcardFilter } from '../../field_wildcard'; -import { getHighlightRequest } from '../../../../../plugins/data/common/field_formats'; +import { getHighlightRequest } from '../../../../../plugins/data/public'; import { npSetup } from 'ui/new_platform'; import chrome from '../../chrome'; import { RequestFailure } from '../fetch/errors'; diff --git a/src/legacy/ui/public/filter_manager/__tests__/filter_generator.js b/src/legacy/ui/public/filter_manager/__tests__/filter_generator.js index ed7e25704d5a5..5b6455bf20847 100644 --- a/src/legacy/ui/public/filter_manager/__tests__/filter_generator.js +++ b/src/legacy/ui/public/filter_manager/__tests__/filter_generator.js @@ -24,8 +24,8 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import { getFilterGenerator } from '..'; import { FilterBarQueryFilterProvider } from '../../filter_manager/query_filter'; -import { uniqFilters } from '../../../../../plugins/data/public'; -import { getPhraseScript } from '@kbn/es-query'; +import { uniqFilters, esFilters } from '../../../../../plugins/data/public'; + let queryFilter; let filterGen; let appState; @@ -137,14 +137,14 @@ describe('Filter Manager', function () { filterGen.add(scriptedField, 1, '+', 'myIndex'); checkAddFilters(1, [{ meta: { index: 'myIndex', negate: false, field: 'scriptedField' }, - script: getPhraseScript(scriptedField, 1) + script: esFilters.getPhraseScript(scriptedField, 1) }], 4); expect(appState.filters).to.have.length(3); filterGen.add(scriptedField, 1, '-', 'myIndex'); checkAddFilters(1, [{ meta: { index: 'myIndex', negate: true, disabled: false, field: 'scriptedField' }, - script: getPhraseScript(scriptedField, 1) + script: esFilters.getPhraseScript(scriptedField, 1) }], 5); expect(appState.filters).to.have.length(3); }); diff --git a/src/legacy/ui/public/filter_manager/filter_generator.js b/src/legacy/ui/public/filter_manager/filter_generator.js index f119a95833668..e11e0ff6653a7 100644 --- a/src/legacy/ui/public/filter_manager/filter_generator.js +++ b/src/legacy/ui/public/filter_manager/filter_generator.js @@ -18,7 +18,7 @@ */ import _ from 'lodash'; -import { getPhraseFilterField, getPhraseFilterValue, getPhraseScript, isPhraseFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../plugins/data/public'; // Adds a filter to a passed state export function getFilterGenerator(queryFilter) { @@ -42,8 +42,8 @@ export function getFilterGenerator(queryFilter) { return filter.exists.field === value; } - if (isPhraseFilter(filter)) { - return getPhraseFilterField(filter) === fieldName && getPhraseFilterValue(filter) === value; + if (esFilters.isPhraseFilter(filter)) { + return esFilters.getPhraseFilterField(filter) === fieldName && esFilters.getPhraseFilterValue(filter) === value; } if (filter.script) { @@ -73,7 +73,7 @@ export function getFilterGenerator(queryFilter) { if (field.scripted) { filter = { meta: { negate, index, field: fieldName }, - script: getPhraseScript(field, value) + script: esFilters.getPhraseScript(field, value) }; } else { filter = { meta: { negate, index }, query: { match_phrase: {} } }; diff --git a/src/legacy/ui/public/vis/vis_filters/brush_event.js b/src/legacy/ui/public/vis/vis_filters/brush_event.js index 90cbaf7c048ee..17ab302a20cb1 100644 --- a/src/legacy/ui/public/vis/vis_filters/brush_event.js +++ b/src/legacy/ui/public/vis/vis_filters/brush_event.js @@ -19,7 +19,7 @@ import _ from 'lodash'; import moment from 'moment'; -import { buildRangeFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../plugins/data/public'; export function onBrushEvent(event) { const isNumber = event.data.ordered; @@ -56,7 +56,7 @@ export function onBrushEvent(event) { }; } - const newFilter = buildRangeFilter( + const newFilter = esFilters.buildRangeFilter( field, range, indexPattern, diff --git a/src/legacy/ui/public/vis/vis_filters/vis_filters.js b/src/legacy/ui/public/vis/vis_filters/vis_filters.js index 9343585fa9508..e879d040125f1 100644 --- a/src/legacy/ui/public/vis/vis_filters/vis_filters.js +++ b/src/legacy/ui/public/vis/vis_filters/vis_filters.js @@ -20,8 +20,8 @@ import _ from 'lodash'; import { pushFilterBarFilters } from '../push_filters'; import { onBrushEvent } from './brush_event'; -import { uniqFilters } from '../../../../../plugins/data/public'; -import { toggleFilterNegated } from '@kbn/es-query'; +import { uniqFilters, esFilters } from '../../../../../plugins/data/public'; + /** * For terms aggregations on `__other__` buckets, this assembles a list of applicable filter * terms based on a specific cell in the tabified data. @@ -94,7 +94,7 @@ const createFiltersFromEvent = (event) => { if (filter) { filter.forEach(f => { if (event.negate) { - f = toggleFilterNegated(f); + f = esFilters.toggleFilterNegated(f); } filters.push(f); }); diff --git a/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.ts b/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.ts index bb9f5832ac4e5..fb16e095b3418 100644 --- a/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.ts +++ b/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.ts @@ -22,7 +22,6 @@ import { debounce, forEach, get, isEqual } from 'lodash'; import * as Rx from 'rxjs'; import { share } from 'rxjs/operators'; import { i18n } from '@kbn/i18n'; -import { Filter } from '@kbn/es-query'; import { toastNotifications } from 'ui/notify'; // @ts-ignore untyped dependency import { AggConfigs } from 'ui/agg_types/agg_configs'; @@ -44,6 +43,7 @@ import { VisFiltersProvider } from '../../vis/vis_filters'; import { PipelineDataLoader } from './pipeline_data_loader'; import { visualizationLoader } from './visualization_loader'; import { Query } from '../../../../core_plugins/data/public'; +import { esFilters } from '../../../../../plugins/data/public'; import { DataAdapter, RequestAdapter } from '../../inspector/adapters'; @@ -67,7 +67,7 @@ export interface RequestHandlerParams { aggs: AggConfigs; timeRange?: TimeRange; query?: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; forceFetch: boolean; queryFilter: QueryFilter; uiState?: PersistedState; diff --git a/src/legacy/ui/public/visualize/loader/types.ts b/src/legacy/ui/public/visualize/loader/types.ts index 87183d839e637..525ec35834ecd 100644 --- a/src/legacy/ui/public/visualize/loader/types.ts +++ b/src/legacy/ui/public/visualize/loader/types.ts @@ -17,7 +17,6 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { TimeRange } from 'src/plugins/data/public'; import { Query } from 'src/legacy/core_plugins/data/public'; import { SavedObject } from 'ui/saved_objects/saved_object'; @@ -26,6 +25,7 @@ import { SearchSource } from '../../courier'; import { PersistedState } from '../../persisted_state'; import { AppState } from '../../state_management/app_state'; import { Vis } from '../../vis'; +import { esFilters } from '../../../../../plugins/data/public'; export interface VisSavedObject extends SavedObject { vis: Vis; @@ -68,7 +68,7 @@ export interface VisualizeLoaderParams { /** * Specifies the filters that should be applied to that visualization. */ - filters?: Filter[]; + filters?: esFilters.Filter[]; /** * The query that should apply to that visualization. */ diff --git a/src/legacy/ui/public/visualize/loader/utils/query_geohash_bounds.ts b/src/legacy/ui/public/visualize/loader/utils/query_geohash_bounds.ts index ec612f7dd0373..9f3aa190917d7 100644 --- a/src/legacy/ui/public/visualize/loader/utils/query_geohash_bounds.ts +++ b/src/legacy/ui/public/visualize/loader/utils/query_geohash_bounds.ts @@ -22,13 +22,13 @@ import { get } from 'lodash'; import { toastNotifications } from 'ui/notify'; import { AggConfig } from 'ui/vis'; -import { Filter } from '@kbn/es-query'; import { Query } from 'src/legacy/core_plugins/data/public'; import { timefilter } from 'ui/timefilter'; import { Vis } from '../../../vis'; +import { esFilters } from '../../../../../../plugins/data/public'; interface QueryGeohashBoundsParams { - filters?: Filter[]; + filters?: esFilters.Filter[]; query?: Query; } @@ -76,7 +76,7 @@ export async function queryGeohashBounds(vis: Vis, params: QueryGeohashBoundsPar const useTimeFilter = !!indexPattern.timeFieldName; if (useTimeFilter) { const filter = timefilter.createFilter(indexPattern); - if (filter) activeFilters.push((filter as any) as Filter); + if (filter) activeFilters.push((filter as any) as esFilters.Filter); } return activeFilters; }); diff --git a/src/plugins/dashboard_embeddable_container/public/embeddable/dashboard_container.tsx b/src/plugins/dashboard_embeddable_container/public/embeddable/dashboard_container.tsx index 36aaecb45ad49..8b258f3558438 100644 --- a/src/plugins/dashboard_embeddable_container/public/embeddable/dashboard_container.tsx +++ b/src/plugins/dashboard_embeddable_container/public/embeddable/dashboard_container.tsx @@ -20,7 +20,6 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { I18nProvider } from '@kbn/i18n/react'; -import { Filter } from '@kbn/es-query'; import { RefreshInterval, TimeRange, Query } from '../../../data/public'; import { CoreStart } from '../../../../core/public'; import { IUiActionsStart } from '../ui_actions_plugin'; @@ -38,6 +37,7 @@ import { createPanelState } from './panel'; import { DashboardPanelState } from './types'; import { DashboardViewport } from './viewport/dashboard_viewport'; import { Start as InspectorStartContract } from '../../../inspector/public'; +import { esFilters } from '../../../../plugins/data/public'; import { KibanaContextProvider, KibanaReactContext, @@ -46,7 +46,7 @@ import { export interface DashboardContainerInput extends ContainerInput { viewMode: ViewMode; - filters: Filter[]; + filters: esFilters.Filter[]; query: Query; timeRange: TimeRange; refreshConfig?: RefreshInterval; @@ -65,7 +65,7 @@ interface IndexSignature { } export interface InheritedChildInput extends IndexSignature { - filters: Filter[]; + filters: esFilters.Filter[]; query: Query; timeRange: TimeRange; refreshConfig?: RefreshInterval; diff --git a/src/plugins/data/common/es_query/__tests__/fields_mock.ts b/src/plugins/data/common/es_query/__tests__/fields_mock.ts new file mode 100644 index 0000000000000..83fdf588af00c --- /dev/null +++ b/src/plugins/data/common/es_query/__tests__/fields_mock.ts @@ -0,0 +1,320 @@ +/* + * 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. + */ + +export const fields = [ + { + name: 'bytes', + type: 'number', + esTypes: ['long'], + count: 10, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'ssl', + type: 'boolean', + esTypes: ['boolean'], + count: 20, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '@timestamp', + type: 'date', + esTypes: ['date'], + count: 30, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'time', + type: 'date', + esTypes: ['date'], + count: 30, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '@tags', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'utc_time', + type: 'date', + esTypes: ['date'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'phpmemory', + type: 'number', + esTypes: ['integer'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'ip', + type: 'ip', + esTypes: ['ip'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'request_body', + type: 'attachment', + esTypes: ['attachment'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'point', + type: 'geo_point', + esTypes: ['geo_point'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'area', + type: 'geo_shape', + esTypes: ['geo_shape'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'hashed', + type: 'murmur3', + esTypes: ['murmur3'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + }, + { + name: 'geo.coordinates', + type: 'geo_point', + esTypes: ['geo_point'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'extension', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'machine.os', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'machine.os.raw', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + subType: { multi: { parent: 'machine.os' } }, + }, + { + name: 'geo.src', + type: 'string', + esTypes: ['keyword'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: '_id', + type: 'string', + esTypes: ['_id'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: '_type', + type: 'string', + esTypes: ['_type'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: '_source', + type: '_source', + esTypes: ['_source'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'non-filterable', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: false, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'non-sortable', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: false, + aggregatable: false, + readFromDocValues: false, + }, + { + name: 'custom_user_field', + type: 'conflict', + esTypes: ['long', 'text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: true, + readFromDocValues: true, + }, + { + name: 'script string', + type: 'string', + count: 0, + scripted: true, + script: "'i am a string'", + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script number', + type: 'number', + count: 0, + scripted: true, + script: '1234', + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script date', + type: 'date', + count: 0, + scripted: true, + script: '1234', + lang: 'painless', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'script murmur3', + type: 'murmur3', + count: 0, + scripted: true, + script: '1234', + lang: 'expression', + searchable: true, + aggregatable: true, + readFromDocValues: false, + }, + { + name: 'nestedField.child', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + subType: { nested: { path: 'nestedField' } }, + }, + { + name: 'nestedField.nestedChild.doublyNestedChild', + type: 'string', + esTypes: ['text'], + count: 0, + scripted: false, + searchable: true, + aggregatable: false, + readFromDocValues: false, + subType: { nested: { path: 'nestedField.nestedChild' } }, + }, +]; + +export const getField = (name: string) => fields.find(field => field.name === name); diff --git a/packages/kbn-es-query/src/filters/lib/custom_filter.ts b/src/plugins/data/common/es_query/filters/custom_filter.ts similarity index 100% rename from packages/kbn-es-query/src/filters/lib/custom_filter.ts rename to src/plugins/data/common/es_query/filters/custom_filter.ts diff --git a/packages/kbn-es-query/src/filters/lib/exists_filter.ts b/src/plugins/data/common/es_query/filters/exists_filter.ts similarity index 81% rename from packages/kbn-es-query/src/filters/lib/exists_filter.ts rename to src/plugins/data/common/es_query/filters/exists_filter.ts index 5843c25c43cff..9125048e5f6cd 100644 --- a/packages/kbn-es-query/src/filters/lib/exists_filter.ts +++ b/src/plugins/data/common/es_query/filters/exists_filter.ts @@ -18,6 +18,7 @@ */ import { Filter, FilterMeta } from './meta_filter'; +import { IndexPattern, Field } from './types'; export type ExistsFilterMeta = FilterMeta; @@ -31,3 +32,14 @@ export type ExistsFilter = Filter & { }; export const isExistsFilter = (filter: any): filter is ExistsFilter => filter && filter.exists; + +export const buildExistsFilter = (field: Field, indexPattern: IndexPattern) => { + return { + meta: { + index: indexPattern.id, + }, + exists: { + field: field.name, + }, + } as ExistsFilter; +}; diff --git a/packages/kbn-es-query/src/filters/lib/geo_bounding_box_filter.ts b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts similarity index 100% rename from packages/kbn-es-query/src/filters/lib/geo_bounding_box_filter.ts rename to src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts diff --git a/packages/kbn-es-query/src/filters/lib/geo_polygon_filter.ts b/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts similarity index 100% rename from packages/kbn-es-query/src/filters/lib/geo_polygon_filter.ts rename to src/plugins/data/common/es_query/filters/geo_polygon_filter.ts diff --git a/packages/kbn-es-query/src/filters/lib/phrases_filter.ts b/src/plugins/data/common/es_query/filters/index.ts similarity index 66% rename from packages/kbn-es-query/src/filters/lib/phrases_filter.ts rename to src/plugins/data/common/es_query/filters/index.ts index 213afb409a0a6..e28ce9ba74975 100644 --- a/packages/kbn-es-query/src/filters/lib/phrases_filter.ts +++ b/src/plugins/data/common/es_query/filters/index.ts @@ -17,16 +17,16 @@ * under the License. */ -import { Filter, FilterMeta } from './meta_filter'; +export * from './custom_filter'; +export * from './exists_filter'; +export * from './geo_bounding_box_filter'; +export * from './geo_polygon_filter'; +export * from './match_all_filter'; +export * from './meta_filter'; +export * from './missing_filter'; +export * from './phrase_filter'; +export * from './phrases_filter'; +export * from './query_string_filter'; +export * from './range_filter'; -export type PhrasesFilterMeta = FilterMeta & { - params: string[]; // The unformatted values - field?: string; -}; - -export type PhrasesFilter = Filter & { - meta: PhrasesFilterMeta; -}; - -export const isPhrasesFilter = (filter: any): filter is PhrasesFilter => - filter && filter.meta.type === 'phrases'; +export * from './types'; diff --git a/packages/kbn-es-query/src/filters/lib/match_all_filter.ts b/src/plugins/data/common/es_query/filters/match_all_filter.ts similarity index 100% rename from packages/kbn-es-query/src/filters/lib/match_all_filter.ts rename to src/plugins/data/common/es_query/filters/match_all_filter.ts diff --git a/packages/kbn-es-query/src/filters/lib/meta_filter.ts b/src/plugins/data/common/es_query/filters/meta_filter.ts similarity index 75% rename from packages/kbn-es-query/src/filters/lib/meta_filter.ts rename to src/plugins/data/common/es_query/filters/meta_filter.ts index 8f6aef782cea2..9adfdc4eedcb3 100644 --- a/packages/kbn-es-query/src/filters/lib/meta_filter.ts +++ b/src/plugins/data/common/es_query/filters/meta_filter.ts @@ -55,7 +55,7 @@ export interface LatLon { lon: number; } -export function buildEmptyFilter(isPinned: boolean, index?: string): Filter { +export const buildEmptyFilter = (isPinned: boolean, index?: string): Filter => { const meta: FilterMeta = { disabled: false, negate: false, @@ -65,43 +65,43 @@ export function buildEmptyFilter(isPinned: boolean, index?: string): Filter { const $state: FilterState = { store: isPinned ? FilterStateStore.GLOBAL_STATE : FilterStateStore.APP_STATE, }; + return { meta, $state }; -} +}; -export function isFilterPinned(filter: Filter) { +export const isFilterPinned = (filter: Filter) => { return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; -} +}; -export function toggleFilterDisabled(filter: Filter) { +export const toggleFilterDisabled = (filter: Filter) => { const disabled = !filter.meta.disabled; const meta = { ...filter.meta, disabled }; + return { ...filter, meta }; -} +}; -export function toggleFilterNegated(filter: Filter) { +export const toggleFilterNegated = (filter: Filter) => { const negate = !filter.meta.negate; const meta = { ...filter.meta, negate }; + return { ...filter, meta }; -} +}; -export function toggleFilterPinned(filter: Filter) { +export const toggleFilterPinned = (filter: Filter) => { const store = isFilterPinned(filter) ? FilterStateStore.APP_STATE : FilterStateStore.GLOBAL_STATE; const $state = { ...filter.$state, store }; + return { ...filter, $state }; -} +}; -export function enableFilter(filter: Filter) { - return !filter.meta.disabled ? filter : toggleFilterDisabled(filter); -} +export const enableFilter = (filter: Filter) => + !filter.meta.disabled ? filter : toggleFilterDisabled(filter); -export function disableFilter(filter: Filter) { - return filter.meta.disabled ? filter : toggleFilterDisabled(filter); -} +export const disableFilter = (filter: Filter) => + filter.meta.disabled ? filter : toggleFilterDisabled(filter); -export function pinFilter(filter: Filter) { - return isFilterPinned(filter) ? filter : toggleFilterPinned(filter); -} +export const pinFilter = (filter: Filter) => + isFilterPinned(filter) ? filter : toggleFilterPinned(filter); -export function unpinFilter(filter: Filter) { - return !isFilterPinned(filter) ? filter : toggleFilterPinned(filter); -} +export const unpinFilter = (filter: Filter) => + !isFilterPinned(filter) ? filter : toggleFilterPinned(filter); diff --git a/packages/kbn-es-query/src/filters/lib/missing_filter.ts b/src/plugins/data/common/es_query/filters/missing_filter.ts similarity index 100% rename from packages/kbn-es-query/src/filters/lib/missing_filter.ts rename to src/plugins/data/common/es_query/filters/missing_filter.ts diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.test.ts b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts new file mode 100644 index 0000000000000..ec13e28c583d1 --- /dev/null +++ b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts @@ -0,0 +1,97 @@ +/* + * 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 { buildInlineScriptForPhraseFilter, buildPhraseFilter } from './phrase_filter'; +import { IndexPattern } from './types'; +import { getField } from '../__tests__/fields_mock'; + +describe('Phrase filter builder', () => { + let indexPattern: IndexPattern; + + beforeEach(() => { + indexPattern = { + id: 'id', + }; + }); + + it('should be a function', () => { + expect(typeof buildPhraseFilter).toBe('function'); + }); + + it('should return a match query filter when passed a standard field', () => { + const field = getField('bytes'); + + expect(buildPhraseFilter(field, 5, indexPattern)).toEqual({ + meta: { + index: 'id', + }, + query: { + match_phrase: { + bytes: 5, + }, + }, + }); + }); + + it('should return a script filter when passed a scripted field', () => { + const field = getField('script number'); + + expect(buildPhraseFilter(field, 5, indexPattern)).toEqual({ + meta: { + index: 'id', + field: 'script number', + }, + script: { + script: { + lang: 'expression', + params: { + value: 5, + }, + source: '(1234) == value', + }, + }, + }); + }); +}); + +describe('buildInlineScriptForPhraseFilter', () => { + it('should wrap painless scripts in a lambda', () => { + const field = { + lang: 'painless', + script: 'return foo;', + }; + + const expected = + `boolean compare(Supplier s, def v) {return s.get() == v;}` + + `compare(() -> { return foo; }, params.value);`; + + expect(buildInlineScriptForPhraseFilter(field)).toBe(expected); + }); + + it('should create a simple comparison for other langs', () => { + const field = { + lang: 'expression', + script: 'doc[bytes].value', + }; + + const expected = `(doc[bytes].value) == value`; + + expect(buildInlineScriptForPhraseFilter(field)).toBe(expected); + }); +}); diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.ts b/src/plugins/data/common/es_query/filters/phrase_filter.ts new file mode 100644 index 0000000000000..15c5c9d4ad2e6 --- /dev/null +++ b/src/plugins/data/common/es_query/filters/phrase_filter.ts @@ -0,0 +1,144 @@ +/* + * 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 { get, isPlainObject } from 'lodash'; +import { Filter, FilterMeta } from './meta_filter'; +import { IndexPattern, Field } from './types'; + +export type PhraseFilterMeta = FilterMeta & { + params?: { + query: string; // The unformatted value + }; + script?: { + script: { + source?: any; + lang?: string; + params: any; + }; + }; + field?: any; + index?: any; +}; + +export type PhraseFilter = Filter & { + meta: PhraseFilterMeta; +}; + +type PhraseFilterValue = string | number | boolean; + +export const isPhraseFilter = (filter: any): filter is PhraseFilter => { + const isMatchPhraseQuery = filter && filter.query && filter.query.match_phrase; + + const isDeprecatedMatchPhraseQuery = + filter && + filter.query && + filter.query.match && + Object.values(filter.query.match).find((params: any) => params.type === 'phrase'); + + return !!(isMatchPhraseQuery || isDeprecatedMatchPhraseQuery); +}; + +export const isScriptedPhraseFilter = (filter: any): filter is PhraseFilter => + Boolean(get(filter, 'script.script.params.value')); + +export const getPhraseFilterField = (filter: PhraseFilter) => { + const queryConfig = filter.query.match_phrase || filter.query.match; + return Object.keys(queryConfig)[0]; +}; + +export const getPhraseFilterValue = (filter: PhraseFilter): PhraseFilterValue => { + const queryConfig = filter.query.match_phrase || filter.query.match; + const queryValue = Object.values(queryConfig)[0] as any; + return isPlainObject(queryValue) ? queryValue.query : queryValue; +}; + +export const buildPhraseFilter = ( + field: Field, + value: any, + indexPattern: IndexPattern +): PhraseFilter => { + const convertedValue = getConvertedValueForField(field, value); + + if (field.scripted) { + return { + meta: { index: indexPattern.id, field: field.name } as PhraseFilterMeta, + script: getPhraseScript(field, value), + } as PhraseFilter; + } else { + return { + meta: { index: indexPattern.id }, + query: { + match_phrase: { + [field.name]: convertedValue, + }, + }, + } as PhraseFilter; + } +}; + +export const getPhraseScript = (field: Field, value: string) => { + const convertedValue = getConvertedValueForField(field, value); + const script = buildInlineScriptForPhraseFilter(field); + + return { + script: { + source: script, + lang: field.lang, + params: { + value: convertedValue, + }, + }, + }; +}; + +// See https://github.com/elastic/elasticsearch/issues/20941 and https://github.com/elastic/kibana/issues/8677 +// and https://github.com/elastic/elasticsearch/pull/22201 +// for the reason behind this change. Aggs now return boolean buckets with a key of 1 or 0. +export const getConvertedValueForField = (field: Field, value: any) => { + if (typeof value !== 'boolean' && field.type === 'boolean') { + if ([1, 'true'].includes(value)) { + return true; + } else if ([0, 'false'].includes(value)) { + return false; + } else { + throw new Error(`${value} is not a valid boolean value for boolean field ${field.name}`); + } + } + return value; +}; + +/** + * Takes a scripted field and returns an inline script appropriate for use in a script query. + * Handles lucene expression and Painless scripts. Other langs aren't guaranteed to generate valid + * scripts. + * + * @param {object} scriptedField A Field object representing a scripted field + * @returns {string} The inline script string + */ +export const buildInlineScriptForPhraseFilter = (scriptedField: any) => { + // We must wrap painless scripts in a lambda in case they're more than a simple expression + if (scriptedField.lang === 'painless') { + return ( + `boolean compare(Supplier s, def v) {return s.get() == v;}` + + `compare(() -> { ${scriptedField.script} }, params.value);` + ); + } else { + return `(${scriptedField.script}) == value`; + } +}; diff --git a/packages/kbn-es-query/src/filters/phrases.js b/src/plugins/data/common/es_query/filters/phrases_filter.ts similarity index 51% rename from packages/kbn-es-query/src/filters/phrases.js rename to src/plugins/data/common/es_query/filters/phrases_filter.ts index f02b3763f37bb..e4606695c0f6a 100644 --- a/packages/kbn-es-query/src/filters/phrases.js +++ b/src/plugins/data/common/es_query/filters/phrases_filter.ts @@ -17,47 +17,54 @@ * under the License. */ -import { getPhraseScript } from './phrase'; +import { Filter, FilterMeta } from './meta_filter'; +import { Field, IndexPattern } from './types'; +import { getPhraseScript } from './phrase_filter'; + +export type PhrasesFilterMeta = FilterMeta & { + params: string[]; // The unformatted values + field?: string; +}; + +export type PhrasesFilter = Filter & { + meta: PhrasesFilterMeta; +}; + +export const isPhrasesFilter = (filter: any): filter is PhrasesFilter => + filter && filter.meta.type === 'phrases'; // Creates a filter where the given field matches one or more of the given values // params should be an array of values -export function buildPhrasesFilter(field, params, indexPattern) { +export const buildPhrasesFilter = (field: Field, params: any, indexPattern: IndexPattern) => { const index = indexPattern.id; const type = 'phrases'; const key = field.name; - const value = params - .map(value => format(field, value)) - .join(', '); - const filter = { - meta: { index, type, key, value, params } - }; + const format = (f: Field, value: any) => + f && f.format && f.format.convert ? f.format.convert(value) : value; + + const value = params.map((v: any) => format(field, v)).join(', '); let should; if (field.scripted) { - should = params.map((value) => ({ - script: getPhraseScript(field, value) + should = params.map((v: any) => ({ + script: getPhraseScript(field, v), })); } else { - should = params.map((value) => ({ + should = params.map((v: any) => ({ match_phrase: { - [field.name]: value - } + [field.name]: v, + }, })); } - filter.query = { - bool: { - should, - minimum_should_match: 1 - } - }; - - return filter; -} - -function format(field, value) { - return field && field.format && field.format.convert - ? field.format.convert(value) - : value; -} + return { + meta: { index, type, key, value, params }, + query: { + bool: { + should, + minimum_should_match: 1, + }, + }, + } as PhrasesFilter; +}; diff --git a/packages/kbn-es-query/src/filters/query.js b/src/plugins/data/common/es_query/filters/query_string_filter.test.ts similarity index 56% rename from packages/kbn-es-query/src/filters/query.js rename to src/plugins/data/common/es_query/filters/query_string_filter.test.ts index ded877231bf67..839e4f6359257 100644 --- a/packages/kbn-es-query/src/filters/query.js +++ b/src/plugins/data/common/es_query/filters/query_string_filter.test.ts @@ -17,18 +17,31 @@ * under the License. */ -// Creates a filter corresponding to a raw Elasticsearch query DSL object -export function buildQueryFilter(query, index, alias) { - const filter = { - query: query, - meta: { - index, - } - }; +import { buildQueryFilter } from './query_string_filter'; +import { IndexPattern } from './types'; - if (alias) { - filter.meta.alias = alias; - } +describe('Phrase filter builder', () => { + let indexPattern: IndexPattern; - return filter; -} + beforeEach(() => { + indexPattern = { + id: 'id', + }; + }); + + it('should be a function', () => { + expect(typeof buildQueryFilter).toBe('function'); + }); + + it('should return a query filter when passed a standard field', () => { + expect(buildQueryFilter({ foo: 'bar' }, indexPattern.id, '')).toEqual({ + meta: { + alias: '', + index: 'id', + }, + query: { + foo: 'bar', + }, + }); + }); +}); diff --git a/packages/kbn-es-query/src/filters/lib/query_string_filter.ts b/src/plugins/data/common/es_query/filters/query_string_filter.ts similarity index 78% rename from packages/kbn-es-query/src/filters/lib/query_string_filter.ts rename to src/plugins/data/common/es_query/filters/query_string_filter.ts index 3b3b97fafba9b..901dc724aa4e4 100644 --- a/packages/kbn-es-query/src/filters/lib/query_string_filter.ts +++ b/src/plugins/data/common/es_query/filters/query_string_filter.ts @@ -18,6 +18,7 @@ */ import { Filter, FilterMeta } from './meta_filter'; +import { IndexPattern } from './types'; export type QueryStringFilterMeta = FilterMeta; @@ -32,3 +33,17 @@ export type QueryStringFilter = Filter & { export const isQueryStringFilter = (filter: any): filter is QueryStringFilter => filter && filter.query && filter.query.query_string; + +// Creates a filter corresponding to a raw Elasticsearch query DSL object +export const buildQueryFilter = ( + query: QueryStringFilter['query'], + index: IndexPattern, + alias: string +) => + ({ + query, + meta: { + index, + alias, + }, + } as QueryStringFilter); diff --git a/src/plugins/data/common/es_query/filters/range_filter.test.ts b/src/plugins/data/common/es_query/filters/range_filter.test.ts new file mode 100644 index 0000000000000..9008dc2a67294 --- /dev/null +++ b/src/plugins/data/common/es_query/filters/range_filter.test.ts @@ -0,0 +1,174 @@ +/* + * 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 { each } from 'lodash'; +import { buildRangeFilter, RangeFilter } from './range_filter'; +import { IndexPattern, Field } from './types'; +import { getField } from '../__tests__/fields_mock'; + +describe('Range filter builder', () => { + let indexPattern: IndexPattern; + + beforeEach(() => { + indexPattern = { + id: 'id', + }; + }); + + it('should be a function', () => { + expect(typeof buildRangeFilter).toBe('function'); + }); + + it('should return a range filter when passed a standard field', () => { + const field = getField('bytes'); + + expect(buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern)).toEqual({ + meta: { + index: 'id', + params: {}, + }, + range: { + bytes: { + gte: 1, + lte: 3, + }, + }, + }); + }); + + it('should return a script filter when passed a scripted field', () => { + const field = getField('script number'); + + expect(buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern)).toEqual({ + meta: { + field: 'script number', + index: 'id', + params: {}, + }, + script: { + script: { + lang: 'expression', + source: '(' + field!.script + ')>=gte && (' + field!.script + ')<=lte', + params: { + value: '>=1 <=3', + gte: 1, + lte: 3, + }, + }, + }, + }); + }); + + it('should wrap painless scripts in comparator lambdas', () => { + const field = getField('script date'); + const expected = + `boolean gte(Supplier s, def v) {return !s.get().toInstant().isBefore(Instant.parse(v))} ` + + `boolean lte(Supplier s, def v) {return !s.get().toInstant().isAfter(Instant.parse(v))}` + + `gte(() -> { ${field!.script} }, params.gte) && ` + + `lte(() -> { ${field!.script} }, params.lte)`; + + const rangeFilter = buildRangeFilter(field, { gte: 1, lte: 3 }, indexPattern); + + expect(rangeFilter.script!.script.source).toBe(expected); + }); + + it('should throw an error when gte and gt, or lte and lt are both passed', () => { + const field = getField('script number'); + + expect(() => { + buildRangeFilter(field, { gte: 1, gt: 3 }, indexPattern); + }).toThrowError(); + + expect(() => { + buildRangeFilter(field, { lte: 1, lt: 3 }, indexPattern); + }).toThrowError(); + }); + + it('to use the right operator for each of gte, gt, lt and lte', () => { + const field = getField('script number'); + + each({ gte: '>=', gt: '>', lte: '<=', lt: '<' }, (operator: string, key: any) => { + const params = { + [key]: 5, + }; + + const filter = buildRangeFilter(field, params, indexPattern); + const script = filter.script!.script; + + expect(script.source).toBe('(' + field!.script + ')' + operator + key); + expect(script.params[key]).toBe(5); + expect(script.params.value).toBe(operator + 5); + }); + }); + + describe('when given params where one side is infinite', () => { + let field: Field; + let filter: RangeFilter; + + beforeEach(() => { + field = getField('script number'); + filter = buildRangeFilter(field, { gte: 0, lt: Infinity }, indexPattern); + }); + + describe('returned filter', () => { + it('is a script filter', () => { + expect(filter).toHaveProperty('script'); + }); + + it('contain a param for the finite side', () => { + expect(filter.script!.script.params).toHaveProperty('gte', 0); + }); + + it('does not contain a param for the infinite side', () => { + expect(filter.script!.script.params).not.toHaveProperty('lt'); + }); + + it('does not contain a script condition for the infinite side', () => { + const script = field!.script; + + expect(filter.script!.script.source).toEqual(`(${script})>=gte`); + }); + }); + }); + + describe('when given params where both sides are infinite', () => { + let field: Field; + let filter: RangeFilter; + + beforeEach(() => { + field = getField('script number'); + filter = buildRangeFilter(field, { gte: -Infinity, lt: Infinity }, indexPattern); + }); + + describe('returned filter', () => { + it('is a match_all filter', () => { + expect(filter).not.toHaveProperty('script'); + expect(filter).toHaveProperty('match_all'); + }); + + it('does not contain params', () => { + expect(filter).not.toHaveProperty('params'); + }); + + it('meta field is set to field name', () => { + expect(filter.meta.field).toEqual('script number'); + }); + }); + }); +}); diff --git a/packages/kbn-es-query/src/filters/range.js b/src/plugins/data/common/es_query/filters/range_filter.ts similarity index 51% rename from packages/kbn-es-query/src/filters/range.js rename to src/plugins/data/common/es_query/filters/range_filter.ts index 357f9209c50de..d7931f191e52b 100644 --- a/packages/kbn-es-query/src/filters/range.js +++ b/src/plugins/data/common/es_query/filters/range_filter.ts @@ -16,9 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +import { map, reduce, mapValues, get, keys, pick } from 'lodash'; +import { Filter, FilterMeta } from './meta_filter'; +import { Field, IndexPattern } from './types'; -import _ from 'lodash'; const OPERANDS_IN_RANGE = 2; + const operators = { gt: '>', gte: '>=', @@ -39,33 +42,85 @@ const dateComparators = { lt: 'boolean lt(Supplier s, def v) {return s.get().toInstant().isBefore(Instant.parse(v))}', }; -function formatValue(field, params) { - return _.map(params, (val, key) => operators[key] + format(field, val)).join(' '); +export interface RangeFilterParams { + from?: number | string; + to?: number | string; + gt?: number | string; + lt?: number | string; + gte?: number | string; + lte?: number | string; + format?: string; } +const hasRangeKeys = (params: RangeFilterParams) => + Boolean( + keys(params).find((key: string) => ['gte', 'gt', 'lte', 'lt', 'from', 'to'].includes(key)) + ); + +export type RangeFilterMeta = FilterMeta & { + params: RangeFilterParams; + field?: any; + formattedValue?: string; +}; + +export type RangeFilter = Filter & { + meta: RangeFilterMeta; + script?: { + script: { + params: any; + lang: string; + source: any; + }; + }; + match_all?: any; + range: { [key: string]: RangeFilterParams }; +}; + +export const isRangeFilter = (filter: any): filter is RangeFilter => filter && filter.range; + +export const isScriptedRangeFilter = (filter: any): filter is RangeFilter => { + const params: RangeFilterParams = get(filter, 'script.script.params', {}); + + return hasRangeKeys(params); +}; + +const formatValue = (field: Field, params: any[]) => + map(params, (val: any, key: string) => get(operators, key) + format(field, val)).join(' '); + +const format = (field: Field, value: any) => + field && field.format && field.format.convert ? field.format.convert(value) : value; + // Creates a filter where the value for the given field is in the given range // params should be an object containing `lt`, `lte`, `gt`, and/or `gte` -export function buildRangeFilter(field, params, indexPattern, formattedValue) { - const filter = { meta: { index: indexPattern.id } }; - if (formattedValue) filter.meta.formattedValue = formattedValue; +export const buildRangeFilter = ( + field: Field, + params: RangeFilterParams, + indexPattern: IndexPattern, + formattedValue?: string +): RangeFilter => { + const filter: any = { meta: { index: indexPattern.id, params: {} } }; + + if (formattedValue) { + filter.meta.formattedValue = formattedValue; + } - params = _.mapValues(params, (value) => { - return (field.type === 'number') ? parseFloat(value) : value; - }); + params = mapValues(params, value => (field.type === 'number' ? parseFloat(value) : value)); if ('gte' in params && 'gt' in params) throw new Error('gte and gt are mutually exclusive'); if ('lte' in params && 'lt' in params) throw new Error('lte and lt are mutually exclusive'); - const totalInfinite = ['gt', 'lt'].reduce((totalInfinite, op) => { + const totalInfinite = ['gt', 'lt'].reduce((acc: number, op: any) => { const key = op in params ? op : `${op}e`; - const isInfinite = Math.abs(params[key]) === Infinity; + const isInfinite = Math.abs(get(params, key)) === Infinity; if (isInfinite) { - totalInfinite++; + acc++; + + // @ts-ignore delete params[key]; } - return totalInfinite; + return acc; }, 0); if (totalInfinite === OPERANDS_IN_RANGE) { @@ -81,25 +136,29 @@ export function buildRangeFilter(field, params, indexPattern, formattedValue) { filter.range[field.name] = params; } - return filter; -} + return filter as RangeFilter; +}; -export function getRangeScript(field, params) { - const knownParams = _.pick(params, (val, key) => { - return key in operators; - }); - let script = _.map(knownParams, function (val, key) { - return '(' + field.script + ')' + operators[key] + key; - }).join(' && '); +export const getRangeScript = (field: IndexPattern, params: RangeFilterParams) => { + const knownParams = pick(params, (val, key: any) => key in operators); + let script = map( + knownParams, + (val: any, key: string) => '(' + field.script + ')' + get(operators, key) + key + ).join(' && '); // We must wrap painless scripts in a lambda in case they're more than a simple expression if (field.lang === 'painless') { const comp = field.type === 'date' ? dateComparators : comparators; - const currentComparators = _.reduce(knownParams, (acc, val, key) => acc.concat(comp[key]), []).join(' '); + const currentComparators = reduce( + knownParams, + (acc, val, key) => acc.concat(get(comp, key)), + [] + ).join(' '); - const comparisons = _.map(knownParams, function (val, key) { - return `${key}(() -> { ${field.script} }, params.${key})`; - }).join(' && '); + const comparisons = map( + knownParams, + (val, key) => `${key}(() -> { ${field.script} }, params.${key})` + ).join(' && '); script = `${currentComparators}${comparisons}`; } @@ -108,14 +167,7 @@ export function getRangeScript(field, params) { script: { source: script, params: knownParams, - lang: field.lang - } + lang: field.lang, + }, }; -} - -function format(field, value) { - return field && field.format && field.format.convert - ? field.format.convert(value) - : value; -} - +}; diff --git a/src/plugins/data/common/es_query/filters/types.ts b/src/plugins/data/common/es_query/filters/types.ts new file mode 100644 index 0000000000000..2814735061999 --- /dev/null +++ b/src/plugins/data/common/es_query/filters/types.ts @@ -0,0 +1,57 @@ +/* + * 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 { ExistsFilter } from './exists_filter'; +import { GeoBoundingBoxFilter } from './geo_bounding_box_filter'; +import { GeoPolygonFilter } from './geo_polygon_filter'; +import { PhrasesFilter } from './phrases_filter'; +import { PhraseFilter } from './phrase_filter'; +import { RangeFilter } from './range_filter'; +import { MatchAllFilter } from './match_all_filter'; +import { MissingFilter } from './missing_filter'; + +// Any filter associated with a field (used in the filter bar/editor) +export type FieldFilter = + | ExistsFilter + | GeoBoundingBoxFilter + | GeoPolygonFilter + | PhraseFilter + | PhrasesFilter + | RangeFilter + | MatchAllFilter + | MissingFilter; + +export enum FILTERS { + CUSTOM = 'custom', + PHRASES = 'phrases', + PHRASE = 'phrase', + EXISTS = 'exists', + MATCH_ALL = 'match_all', + MISSING = 'missing', + QUERY_STRING = 'query_string', + RANGE = 'range', + GEO_BOUNDING_BOX = 'geo_bounding_box', + GEO_POLYGON = 'geo_polygon', +} + +// We can't import the real types from the data plugin, so need to either duplicate +// them here or figure out another solution, perhaps housing them in this package +// will be replaces after Fieds / IndexPattern will be moved into new platform +export type Field = any; +export type IndexPattern = any; diff --git a/packages/kbn-es-query/src/filters/index.js b/src/plugins/data/common/es_query/index.ts similarity index 84% rename from packages/kbn-es-query/src/filters/index.js rename to src/plugins/data/common/es_query/index.ts index d7d092eabd8a2..88e14a43cfaae 100644 --- a/packages/kbn-es-query/src/filters/index.js +++ b/src/plugins/data/common/es_query/index.ts @@ -16,10 +16,6 @@ * specific language governing permissions and limitations * under the License. */ +import * as esFilters from './filters'; -export * from './exists'; -export * from './phrase'; -export * from './phrases'; -export * from './query'; -export * from './range'; -export * from './lib'; +export { esFilters }; diff --git a/src/plugins/data/common/index.ts b/src/plugins/data/common/index.ts index dca7897bd2766..42b5a03fcc926 100644 --- a/src/plugins/data/common/index.ts +++ b/src/plugins/data/common/index.ts @@ -20,5 +20,6 @@ export * from './query'; export * from './field_formats'; export * from './kbn_field_types'; +export * from './es_query'; export * from './types'; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 51f26a4bd7f31..32153df69f367 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -34,5 +34,4 @@ export * from './types'; export { IRequestTypesMap, IResponseTypesMap } from './search'; export * from './search'; - export * from './query'; diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts index 5092e9e55c2b4..5bee3f7d10428 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts @@ -21,10 +21,10 @@ import _ from 'lodash'; import sinon from 'sinon'; import { Subscription } from 'rxjs'; -import { Filter, FilterStateStore } from '@kbn/es-query'; import { FilterManager } from './filter_manager'; import { getFilter } from './test_helpers/get_stub_filter'; import { getFiltersArray } from './test_helpers/get_filters_array'; +import { esFilters } from '../../../common/es_query'; import { coreMock } from '../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); @@ -39,7 +39,7 @@ describe('filter_manager', () => { let updateListener: sinon.SinonSpy; let filterManager: FilterManager; - let readyFilters: Filter[]; + let readyFilters: esFilters.Filter[]; beforeEach(() => { updateListener = sinon.stub(); @@ -82,7 +82,7 @@ describe('filter_manager', () => { test('app state should be set', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.setFilters([f1]); expect(filterManager.getAppFilters()).toHaveLength(1); expect(filterManager.getGlobalFilters()).toHaveLength(0); @@ -96,7 +96,7 @@ describe('filter_manager', () => { test('global state should be set', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); filterManager.setFilters([f1]); expect(filterManager.getAppFilters()).toHaveLength(0); expect(filterManager.getGlobalFilters()).toHaveLength(1); @@ -110,8 +110,8 @@ describe('filter_manager', () => { test('both states should be set', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); filterManager.setFilters([f1, f2]); expect(filterManager.getAppFilters()).toHaveLength(1); expect(filterManager.getGlobalFilters()).toHaveLength(1); @@ -128,8 +128,8 @@ describe('filter_manager', () => { test('set state should override previous state', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); filterManager.setFilters([f1]); filterManager.setFilters([f2]); @@ -150,7 +150,7 @@ describe('filter_manager', () => { test('changing a disabled filter should fire only update event', async function() { const updateStub = jest.fn(); const fetchStub = jest.fn(); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, true, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, true, false, 'age', 34); filterManager.setFilters([f1]); @@ -175,7 +175,7 @@ describe('filter_manager', () => { describe('add filters', () => { test('app state should accept a single filter', async function() { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.addFilters(f1); const appFilters = filterManager.getAppFilters(); expect(appFilters).toHaveLength(1); @@ -185,8 +185,8 @@ describe('filter_manager', () => { }); test('app state should accept array', async () => { - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'female'); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'female'); filterManager.addFilters([f1]); filterManager.addFilters([f2]); const appFilters = filterManager.getAppFilters(); @@ -197,7 +197,7 @@ describe('filter_manager', () => { test('global state should accept a single filer', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); filterManager.addFilters(f1); expect(filterManager.getAppFilters()).toHaveLength(0); const globalFilters = filterManager.getGlobalFilters(); @@ -207,8 +207,14 @@ describe('filter_manager', () => { }); test('global state should be accept array', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'gender', 'female'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter( + esFilters.FilterStateStore.GLOBAL_STATE, + false, + false, + 'gender', + 'female' + ); filterManager.addFilters([f1, f2]); expect(filterManager.getAppFilters()).toHaveLength(0); const globalFilters = filterManager.getGlobalFilters(); @@ -218,8 +224,14 @@ describe('filter_manager', () => { test('add multiple filters at once', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'gender', 'female'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter( + esFilters.FilterStateStore.GLOBAL_STATE, + false, + false, + 'gender', + 'female' + ); filterManager.addFilters([f1, f2]); expect(filterManager.getAppFilters()).toHaveLength(0); expect(filterManager.getGlobalFilters()).toHaveLength(2); @@ -228,8 +240,8 @@ describe('filter_manager', () => { test('add same filter to global and app', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.addFilters([f1, f2]); // FILTER SHOULD BE ADDED ONLY ONCE, TO GLOBAL @@ -240,8 +252,8 @@ describe('filter_manager', () => { test('add same filter with different values to global and app', async () => { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.addFilters([f1, f2]); // FILTER SHOULD BE ADDED TWICE @@ -251,7 +263,7 @@ describe('filter_manager', () => { }); test('add filter with no state, and force pin', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); f1.$state = undefined; filterManager.addFilters([f1], true); @@ -260,12 +272,12 @@ describe('filter_manager', () => { const f1Output = filterManager.getFilters()[0]; expect(f1Output.$state).toBeDefined(); if (f1Output.$state) { - expect(f1Output.$state.store).toBe(FilterStateStore.GLOBAL_STATE); + expect(f1Output.$state.store).toBe(esFilters.FilterStateStore.GLOBAL_STATE); } }); test('add filter with no state, and dont force pin', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 38); f1.$state = undefined; filterManager.addFilters([f1], false); @@ -274,7 +286,7 @@ describe('filter_manager', () => { const f1Output = filterManager.getFilters()[0]; expect(f1Output.$state).toBeDefined(); if (f1Output.$state) { - expect(f1Output.$state.store).toBe(FilterStateStore.APP_STATE); + expect(f1Output.$state.store).toBe(esFilters.FilterStateStore.APP_STATE); } }); @@ -286,11 +298,11 @@ describe('filter_manager', () => { // global filters should be listed first let res = filterManager.getFilters(); expect(res).toHaveLength(2); - expect(res[0].$state && res[0].$state.store).toEqual(FilterStateStore.GLOBAL_STATE); + expect(res[0].$state && res[0].$state.store).toEqual(esFilters.FilterStateStore.GLOBAL_STATE); expect(res[0].meta.disabled).toEqual(filters[1].meta.disabled); expect(res[0].query).toEqual(filters[1].query); - expect(res[1].$state && res[1].$state.store).toEqual(FilterStateStore.APP_STATE); + expect(res[1].$state && res[1].$state.store).toEqual(esFilters.FilterStateStore.APP_STATE); expect(res[1].meta.disabled).toEqual(filters[0].meta.disabled); expect(res[1].query).toEqual(filters[0].query); @@ -310,7 +322,7 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); _.each(res, function(filter) { - expect(filter.$state && filter.$state.store).toBe(FilterStateStore.GLOBAL_STATE); + expect(filter.$state && filter.$state.store).toBe(esFilters.FilterStateStore.GLOBAL_STATE); }); }); @@ -393,7 +405,7 @@ describe('filter_manager', () => { }); test('should de-dupe global filters being set', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); const f2 = _.cloneDeep(f1); filterManager.setFilters([f1, f2]); expect(filterManager.getAppFilters()).toHaveLength(0); @@ -402,7 +414,7 @@ describe('filter_manager', () => { }); test('should de-dupe app filters being set', async () => { - const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); + const f1 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'age', 34); const f2 = _.cloneDeep(f1); filterManager.setFilters([f1, f2]); expect(filterManager.getAppFilters()).toHaveLength(1); @@ -417,7 +429,7 @@ describe('filter_manager', () => { const appFilter = _.cloneDeep(readyFilters[idx]); appFilter.meta.negate = true; appFilter.$state = { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }; filterManager.addFilters(appFilter); const res = filterManager.getFilters(); @@ -434,7 +446,7 @@ describe('filter_manager', () => { const appFilter = _.cloneDeep(readyFilters[1]); appFilter.meta.negate = true; appFilter.$state = { - store: FilterStateStore.APP_STATE, + store: esFilters.FilterStateStore.APP_STATE, }; filterManager.addFilters(appFilter, false); @@ -443,7 +455,7 @@ describe('filter_manager', () => { expect(res).toHaveLength(3); expect( res.filter(function(filter) { - return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; + return filter.$state && filter.$state.store === esFilters.FilterStateStore.GLOBAL_STATE; }).length ).toBe(3); }); @@ -496,8 +508,8 @@ describe('filter_manager', () => { }); test('remove on full should clean and fire events', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); filterManager.setFilters([f1, f2]); updateSubscription = filterManager.getUpdates$().subscribe(updateListener); @@ -507,9 +519,9 @@ describe('filter_manager', () => { }); test('remove non existing filter should do nothing and not fire events', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); - const f3 = getFilter(FilterStateStore.APP_STATE, false, false, 'country', 'US'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); + const f3 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'country', 'US'); filterManager.setFilters([f1, f2]); expect(filterManager.getFilters()).toHaveLength(2); @@ -520,9 +532,9 @@ describe('filter_manager', () => { }); test('remove existing filter should remove and fire events', async () => { - const f1 = getFilter(FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); - const f2 = getFilter(FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); - const f3 = getFilter(FilterStateStore.APP_STATE, false, false, 'country', 'US'); + const f1 = getFilter(esFilters.FilterStateStore.GLOBAL_STATE, false, false, 'age', 34); + const f2 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'gender', 'FEMALE'); + const f3 = getFilter(esFilters.FilterStateStore.APP_STATE, false, false, 'country', 'US'); filterManager.setFilters([f1, f2, f3]); expect(filterManager.getFilters()).toHaveLength(3); diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.ts b/src/plugins/data/public/query/filter_manager/filter_manager.ts index 66b65a40926cb..f691398fb91d3 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.ts @@ -17,8 +17,6 @@ * under the License. */ -import { Filter, isFilterPinned, FilterStateStore } from '@kbn/es-query'; - import _ from 'lodash'; import { Subject } from 'rxjs'; @@ -29,9 +27,10 @@ import { mapAndFlattenFilters } from './lib/map_and_flatten_filters'; import { uniqFilters } from './lib/uniq_filters'; import { onlyDisabledFiltersChanged } from './lib/only_disabled'; import { PartitionedFilters } from './types'; +import { esFilters } from '../../../common/es_query'; export class FilterManager { - private filters: Filter[] = []; + private filters: esFilters.Filter[] = []; private updated$: Subject = new Subject(); private fetch$: Subject = new Subject(); private uiSettings: UiSettingsClientContract; @@ -40,7 +39,7 @@ export class FilterManager { this.uiSettings = uiSettings; } - private mergeIncomingFilters(partitionedFilters: PartitionedFilters): Filter[] { + private mergeIncomingFilters(partitionedFilters: PartitionedFilters): esFilters.Filter[] { const globalFilters = partitionedFilters.globalFilters; const appFilters = partitionedFilters.appFilters; @@ -61,23 +60,26 @@ export class FilterManager { return FilterManager.mergeFilters(appFilters, globalFilters); } - private static mergeFilters(appFilters: Filter[], globalFilters: Filter[]): Filter[] { + private static mergeFilters( + appFilters: esFilters.Filter[], + globalFilters: esFilters.Filter[] + ): esFilters.Filter[] { return uniqFilters(appFilters.reverse().concat(globalFilters.reverse())).reverse(); } - private static partitionFilters(filters: Filter[]): PartitionedFilters { - const [globalFilters, appFilters] = _.partition(filters, isFilterPinned); + private static partitionFilters(filters: esFilters.Filter[]): PartitionedFilters { + const [globalFilters, appFilters] = _.partition(filters, esFilters.isFilterPinned); return { globalFilters, appFilters, }; } - private handleStateUpdate(newFilters: Filter[]) { + private handleStateUpdate(newFilters: esFilters.Filter[]) { // global filters should always be first - newFilters.sort(({ $state: a }: Filter, { $state: b }: Filter): number => { - return a!.store === FilterStateStore.GLOBAL_STATE && - b!.store !== FilterStateStore.GLOBAL_STATE + newFilters.sort(({ $state: a }: esFilters.Filter, { $state: b }: esFilters.Filter): number => { + return a!.store === esFilters.FilterStateStore.GLOBAL_STATE && + b!.store !== esFilters.FilterStateStore.GLOBAL_STATE ? -1 : 1; }); @@ -124,7 +126,7 @@ export class FilterManager { /* Setters */ - public addFilters(filters: Filter[] | Filter, pinFilterStatus?: boolean) { + public addFilters(filters: esFilters.Filter[] | esFilters.Filter, pinFilterStatus?: boolean) { if (!Array.isArray(filters)) { filters = [filters]; } @@ -139,7 +141,10 @@ export class FilterManager { // Set the store of all filters. For now. // In the future, all filters should come in with filter state store already set. - const store = pinFilterStatus ? FilterStateStore.GLOBAL_STATE : FilterStateStore.APP_STATE; + const store = pinFilterStatus + ? esFilters.FilterStateStore.GLOBAL_STATE + : esFilters.FilterStateStore.APP_STATE; + FilterManager.setFiltersStore(filters, store); const mappedFilters = mapAndFlattenFilters(filters); @@ -154,14 +159,14 @@ export class FilterManager { this.handleStateUpdate(newFilters); } - public setFilters(newFilters: Filter[]) { + public setFilters(newFilters: esFilters.Filter[]) { const mappedFilters = mapAndFlattenFilters(newFilters); const newPartitionedFilters = FilterManager.partitionFilters(mappedFilters); const mergedFilters = this.mergeIncomingFilters(newPartitionedFilters); this.handleStateUpdate(mergedFilters); } - public removeFilter(filter: Filter) { + public removeFilter(filter: esFilters.Filter) { const filterIndex = _.findIndex(this.filters, item => { return _.isEqual(item.meta, filter.meta) && _.isEqual(item.query, filter.query); }); @@ -177,8 +182,8 @@ export class FilterManager { this.setFilters([]); } - public static setFiltersStore(filters: Filter[], store: FilterStateStore) { - _.map(filters, (filter: Filter) => { + public static setFiltersStore(filters: esFilters.Filter[], store: esFilters.FilterStateStore) { + _.map(filters, (filter: esFilters.Filter) => { // Override status only for filters that didn't have state in the first place. if (filter.$state === undefined) { filter.$state = { store }; diff --git a/src/plugins/data/public/query/filter_manager/lib/compare_filters.test.ts b/src/plugins/data/public/query/filter_manager/lib/compare_filters.test.ts index e8244feb988b6..6bde6b528d07b 100644 --- a/src/plugins/data/public/query/filter_manager/lib/compare_filters.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/compare_filters.test.ts @@ -16,42 +16,48 @@ * specific language governing permissions and limitations * under the License. */ -import { buildQueryFilter, buildEmptyFilter, FilterStateStore } from '@kbn/es-query'; + import { compareFilters } from './compare_filters'; +import { esFilters } from '../../../../common/es_query'; describe('filter manager utilities', () => { describe('compare filters', () => { test('should compare filters', () => { - const f1 = buildQueryFilter( + const f1 = esFilters.buildQueryFilter( { _type: { match: { query: 'apache', type: 'phrase' } } }, - 'index' + 'index', + '' ); - const f2 = buildEmptyFilter(true); + const f2 = esFilters.buildEmptyFilter(true); expect(compareFilters(f1, f2)).toBeFalsy(); }); test('should compare duplicates', () => { - const f1 = buildQueryFilter( + const f1 = esFilters.buildQueryFilter( { _type: { match: { query: 'apache', type: 'phrase' } } }, - 'index' + 'index', + '' ); - const f2 = buildQueryFilter( + const f2 = esFilters.buildQueryFilter( { _type: { match: { query: 'apache', type: 'phrase' } } }, - 'index' + 'index', + '' ); expect(compareFilters(f1, f2)).toBeTruthy(); }); test('should compare duplicates, ignoring meta attributes', () => { - const f1 = buildQueryFilter( + const f1 = esFilters.buildQueryFilter( { _type: { match: { query: 'apache', type: 'phrase' } } }, - 'index1' + 'index1', + '' ); - const f2 = buildQueryFilter( + const f2 = esFilters.buildQueryFilter( { _type: { match: { query: 'apache', type: 'phrase' } } }, - 'index2' + 'index2', + '' ); expect(compareFilters(f1, f2)).toBeTruthy(); @@ -59,12 +65,20 @@ describe('filter manager utilities', () => { test('should compare duplicates, ignoring $state attributes', () => { const f1 = { - $state: { store: FilterStateStore.APP_STATE }, - ...buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), + $state: { store: esFilters.FilterStateStore.APP_STATE }, + ...esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), }; const f2 = { - $state: { store: FilterStateStore.GLOBAL_STATE }, - ...buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), + $state: { store: esFilters.FilterStateStore.GLOBAL_STATE }, + ...esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), }; expect(compareFilters(f1, f2)).toBeTruthy(); diff --git a/src/plugins/data/public/query/filter_manager/lib/compare_filters.ts b/src/plugins/data/public/query/filter_manager/lib/compare_filters.ts index 44bc333ae2b4f..2a7cbe6e3303b 100644 --- a/src/plugins/data/public/query/filter_manager/lib/compare_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/compare_filters.ts @@ -17,8 +17,8 @@ * under the License. */ -import { Filter, FilterMeta } from '@kbn/es-query'; import { defaults, isEqual, omit } from 'lodash'; +import { esFilters } from '../../../../common/es_query'; /** * Compare two filters to see if they match @@ -29,10 +29,14 @@ import { defaults, isEqual, omit } from 'lodash'; * * @returns {bool} Filters are the same */ -export const compareFilters = (first: Filter, second: Filter, comparatorOptions: any = {}) => { +export const compareFilters = ( + first: esFilters.Filter, + second: esFilters.Filter, + comparatorOptions: any = {} +) => { let comparators: any = {}; - const mapFilter = (filter: Filter) => { - const cleaned: FilterMeta = omit(filter, excludedAttributes); + const mapFilter = (filter: esFilters.Filter) => { + const cleaned: esFilters.FilterMeta = omit(filter, excludedAttributes); if (comparators.negate) cleaned.negate = filter.meta && Boolean(filter.meta.negate); if (comparators.disabled) cleaned.disabled = filter.meta && Boolean(filter.meta.disabled); diff --git a/src/plugins/data/public/query/filter_manager/lib/dedup_filters.test.ts b/src/plugins/data/public/query/filter_manager/lib/dedup_filters.test.ts index 75bd9d5dfbd81..9b493add0886c 100644 --- a/src/plugins/data/public/query/filter_manager/lib/dedup_filters.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/dedup_filters.test.ts @@ -17,19 +17,27 @@ * under the License. */ -import { Filter, buildRangeFilter, FilterStateStore, buildQueryFilter } from '@kbn/es-query'; import { dedupFilters } from './dedup_filters'; +import { esFilters } from '../../../../common/es_query'; describe('filter manager utilities', () => { describe('dedupFilters(existing, filters)', () => { test('should return only filters which are not in the existing', () => { - const existing: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index'), - buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), + const existing: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index', ''), + esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), ]; - const filters: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index'), - buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), + const filters: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index', ''), + esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), ]; const results = dedupFilters(existing, filters); @@ -38,16 +46,24 @@ describe('filter manager utilities', () => { }); test('should ignore the disabled attribute when comparing ', () => { - const existing: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index'), + const existing: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index', ''), { - ...buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), + ...esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index1', + '' + ), meta: { disabled: true, negate: false, alias: null }, }, ]; - const filters: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index'), - buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), + const filters: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index', ''), + esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index1', + '' + ), ]; const results = dedupFilters(existing, filters); @@ -56,18 +72,26 @@ describe('filter manager utilities', () => { }); test('should ignore $state attribute', () => { - const existing: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index'), + const existing: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 0, to: 1024 }, 'index', ''), { - ...buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), - $state: { store: FilterStateStore.APP_STATE }, + ...esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), + $state: { store: esFilters.FilterStateStore.APP_STATE }, }, ]; - const filters: Filter[] = [ - buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index'), + const filters: esFilters.Filter[] = [ + esFilters.buildRangeFilter({ name: 'bytes' }, { from: 1024, to: 2048 }, 'index', ''), { - ...buildQueryFilter({ match: { _term: { query: 'apache', type: 'phrase' } } }, 'index'), - $state: { store: FilterStateStore.GLOBAL_STATE }, + ...esFilters.buildQueryFilter( + { match: { _term: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), + $state: { store: esFilters.FilterStateStore.GLOBAL_STATE }, }, ]; const results = dedupFilters(existing, filters); diff --git a/src/plugins/data/public/query/filter_manager/lib/dedup_filters.ts b/src/plugins/data/public/query/filter_manager/lib/dedup_filters.ts index 9565cbd80b779..6d6f49cb5e833 100644 --- a/src/plugins/data/public/query/filter_manager/lib/dedup_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/dedup_filters.ts @@ -17,9 +17,9 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { filter, find } from 'lodash'; import { compareFilters } from './compare_filters'; +import { esFilters } from '../../../../../../plugins/data/public'; /** * Combine 2 filter collections, removing duplicates @@ -31,8 +31,8 @@ import { compareFilters } from './compare_filters'; * @returns {object} An array of filters that were not in existing */ export const dedupFilters = ( - existingFilters: Filter[], - filters: Filter[], + existingFilters: esFilters.Filter[], + filters: esFilters.Filter[], comparatorOptions: any = {} ) => { if (!Array.isArray(filters)) { @@ -41,8 +41,8 @@ export const dedupFilters = ( return filter( filters, - (f: Filter) => - !find(existingFilters, (existingFilter: Filter) => + (f: esFilters.Filter) => + !find(existingFilters, (existingFilter: esFilters.Filter) => compareFilters(existingFilter, f, comparatorOptions) ) ); diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts index c0c509634aba2..dfe3a093c6614 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts @@ -18,8 +18,8 @@ */ import sinon from 'sinon'; -import { Filter, buildEmptyFilter } from '@kbn/es-query'; import { generateMappingChain } from './generate_mapping_chain'; +import { esFilters } from '../../../../../../plugins/data/public'; describe('filter manager utilities', () => { let mapping: any; @@ -32,7 +32,7 @@ describe('filter manager utilities', () => { describe('generateMappingChain()', () => { test('should create a chaining function which calls the next function if the error is thrown', async () => { - const filter: Filter = buildEmptyFilter(true); + const filter = esFilters.buildEmptyFilter(true); mapping.throws(filter); next.returns('good'); @@ -45,7 +45,7 @@ describe('filter manager utilities', () => { }); test('should create a chaining function which DOES NOT call the next function if the result is returned', async () => { - const filter: Filter = buildEmptyFilter(true); + const filter = esFilters.buildEmptyFilter(true); mapping.returns('good'); next.returns('bad'); @@ -57,7 +57,7 @@ describe('filter manager utilities', () => { }); test('should resolve result for the mapping function', async () => { - const filter: Filter = buildEmptyFilter(true); + const filter = esFilters.buildEmptyFilter(true); mapping.returns({ key: 'test', value: 'example' }); @@ -70,7 +70,7 @@ describe('filter manager utilities', () => { test('should call the mapping function with the argument to the chain', async () => { // @ts-ignore - const filter: Filter = { test: 'example' }; + const filter: esFilters.Filter = { test: 'example' }; mapping.returns({ key: 'test', value: 'example' }); @@ -84,7 +84,7 @@ describe('filter manager utilities', () => { }); test('should resolve result for the next function', async () => { - const filter: Filter = buildEmptyFilter(true); + const filter = esFilters.buildEmptyFilter(true); mapping.throws(filter); next.returns({ key: 'test', value: 'example' }); @@ -98,7 +98,7 @@ describe('filter manager utilities', () => { }); test('should throw an error if no functions match', async done => { - const filter: Filter = buildEmptyFilter(true); + const filter = esFilters.buildEmptyFilter(true); mapping.throws(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.ts b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.ts index 760270edd7170..b6764389e0db9 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.ts @@ -16,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; const noop = () => { throw new Error('No mappings have been found for filter.'); }; export const generateMappingChain = (fn: Function, next: Function = noop) => { - return (filter: Filter) => { + return (filter: esFilters.Filter) => { try { return fn(filter); } catch (result) { diff --git a/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.test.ts b/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.test.ts index fce2aa0373ebe..9a0d0d93698f6 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.test.ts @@ -17,14 +17,14 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { mapAndFlattenFilters } from './map_and_flatten_filters'; +import { esFilters } from '../../../../../data/public'; describe('filter manager utilities', () => { describe('mapAndFlattenFilters()', () => { let filters: unknown; - function getDisplayName(filter: Filter) { + function getDisplayName(filter: esFilters.Filter) { return typeof filter.meta.value === 'function' ? filter.meta.value() : filter.meta.value; } @@ -45,7 +45,7 @@ describe('filter manager utilities', () => { }); test('should map and flatten the filters', () => { - const results = mapAndFlattenFilters(filters as Filter[]); + const results = mapAndFlattenFilters(filters as esFilters.Filter[]); expect(results).toHaveLength(5); expect(results[0]).toHaveProperty('meta'); diff --git a/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.ts b/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.ts index b350c3957b142..5326d59f3e32b 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_and_flatten_filters.ts @@ -18,9 +18,9 @@ */ import { compact, flatten } from 'lodash'; -import { Filter } from '@kbn/es-query'; import { mapFilter } from './map_filter'; +import { esFilters } from '../../../../../data/public'; -export const mapAndFlattenFilters = (filters: Filter[]) => { - return compact(flatten(filters)).map((item: Filter) => mapFilter(item)); +export const mapAndFlattenFilters = (filters: esFilters.Filter[]) => { + return compact(flatten(filters)).map((item: esFilters.Filter) => mapFilter(item)); }; diff --git a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts index c1d4ebfd3f7fc..0d115125451ee 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts @@ -17,11 +17,11 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { mapFilter } from './map_filter'; +import { esFilters } from '../../../../../data/public'; describe('filter manager utilities', () => { - function getDisplayName(filter: Filter) { + function getDisplayName(filter: esFilters.Filter) { return typeof filter.meta.value === 'function' ? filter.meta.value() : filter.meta.value; } @@ -31,7 +31,7 @@ describe('filter manager utilities', () => { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } }, }; - const after = mapFilter(before as Filter); + const after = mapFilter(before as esFilters.Filter); expect(after).toHaveProperty('meta'); expect(after.meta).toHaveProperty('key', '_type'); @@ -43,7 +43,7 @@ describe('filter manager utilities', () => { test('should map exists filters', async () => { const before: any = { meta: { index: 'logstash-*' }, exists: { field: '@timestamp' } }; - const after = mapFilter(before as Filter); + const after = mapFilter(before as esFilters.Filter); expect(after).toHaveProperty('meta'); expect(after.meta).toHaveProperty('key', '@timestamp'); @@ -55,7 +55,7 @@ describe('filter manager utilities', () => { test('should map missing filters', async () => { const before: any = { meta: { index: 'logstash-*' }, missing: { field: '@timestamp' } }; - const after = mapFilter(before as Filter); + const after = mapFilter(before as esFilters.Filter); expect(after).toHaveProperty('meta'); expect(after.meta).toHaveProperty('key', '@timestamp'); @@ -67,7 +67,7 @@ describe('filter manager utilities', () => { test('should map json filter', async () => { const before: any = { meta: { index: 'logstash-*' }, query: { match_all: {} } }; - const after = mapFilter(before as Filter); + const after = mapFilter(before as esFilters.Filter); expect(after).toHaveProperty('meta'); expect(after.meta).toHaveProperty('key', 'query'); @@ -81,7 +81,7 @@ describe('filter manager utilities', () => { const before: any = { meta: { index: 'logstash-*' } }; try { - mapFilter(before as Filter); + mapFilter(before as esFilters.Filter); } catch (e) { expect(e).toBeInstanceOf(Error); expect(e.message).toBe('No mappings have been found for filter.'); diff --git a/src/plugins/data/public/query/filter_manager/lib/map_filter.ts b/src/plugins/data/public/query/filter_manager/lib/map_filter.ts index cda9591e40b33..2dc855caabfd3 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_filter.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_filter.ts @@ -17,7 +17,6 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { reduceRight } from 'lodash'; import { mapMatchAll } from './mappers/map_match_all'; @@ -31,8 +30,9 @@ import { mapGeoBoundingBox } from './mappers/map_geo_bounding_box'; import { mapGeoPolygon } from './mappers/map_geo_polygon'; import { mapDefault } from './mappers/map_default'; import { generateMappingChain } from './generate_mapping_chain'; +import { esFilters } from '../../../../../data/public'; -export function mapFilter(filter: Filter) { +export function mapFilter(filter: esFilters.Filter) { /** Mappers **/ // Each mapper is a simple promise function that test if the mapper can diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.test.ts index acb6e89711033..f10766901e5b7 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.test.ts @@ -16,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import { CustomFilter, buildEmptyFilter, buildQueryFilter } from '@kbn/es-query'; + import { mapDefault } from './map_default'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapDefault()', () => { test('should return the key and value for matching filters', async () => { - const filter: CustomFilter = buildQueryFilter({ match_all: {} }, 'index'); + const filter = esFilters.buildQueryFilter({ match_all: {} }, 'index', ''); const result = mapDefault(filter); expect(result).toHaveProperty('key', 'query'); @@ -30,7 +31,7 @@ describe('filter manager utilities', () => { }); test('should return undefined if there is no valid key', async () => { - const filter = buildEmptyFilter(true) as CustomFilter; + const filter = esFilters.buildEmptyFilter(true); try { mapDefault(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts index 70c191879c22e..fd84c5c742589 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts @@ -17,15 +17,15 @@ * under the License. */ -import { Filter, FILTERS } from '@kbn/es-query'; import { find, keys, get } from 'lodash'; +import { esFilters } from '../../../../../common/es_query'; -export const mapDefault = (filter: Filter) => { +export const mapDefault = (filter: esFilters.Filter) => { const metaProperty = /(^\$|meta)/; const key = find(keys(filter), item => !item.match(metaProperty)); if (key) { - const type = FILTERS.CUSTOM; + const type = esFilters.FILTERS.CUSTOM; const value = JSON.stringify(get(filter, key, {})); return { type, key, value }; diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts index c352d3e2b9a73..ff0ed4f4e4d94 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts @@ -16,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -import { ExistsFilter, buildEmptyFilter, buildExistsFilter } from '@kbn/es-query'; + import { mapExists } from './map_exists'; import { mapQueryString } from './map_query_string'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapExists()', () => { test('should return the key and value for matching filters', async () => { - const filter: ExistsFilter = buildExistsFilter({ name: '_type' }, 'index'); + const filter = esFilters.buildExistsFilter({ name: '_type' }, 'index'); const result = mapExists(filter); expect(result).toHaveProperty('key', '_type'); @@ -31,7 +32,7 @@ describe('filter manager utilities', () => { }); test('should return undefined for none matching', async done => { - const filter = buildEmptyFilter(true) as ExistsFilter; + const filter = esFilters.buildEmptyFilter(true); try { mapQueryString(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.ts index d539219a1ca24..63665bdd88ccb 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.ts @@ -17,14 +17,14 @@ * under the License. */ -import { Filter, isExistsFilter, FILTERS } from '@kbn/es-query'; import { get } from 'lodash'; +import { esFilters } from '../../../../../common/es_query'; -export const mapExists = (filter: Filter) => { - if (isExistsFilter(filter)) { +export const mapExists = (filter: esFilters.Filter) => { + if (esFilters.isExistsFilter(filter)) { return { - type: FILTERS.EXISTS, - value: FILTERS.EXISTS, + type: esFilters.FILTERS.EXISTS, + value: esFilters.FILTERS.EXISTS, key: get(filter, 'exists.field'), }; } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts index c3c99e6f6c4a3..5fca4a652bad8 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts @@ -18,7 +18,7 @@ */ import { mapGeoBoundingBox } from './map_geo_bounding_box'; -import { Filter, GeoBoundingBoxFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapGeoBoundingBox()', () => { @@ -34,7 +34,7 @@ describe('filter manager utilities', () => { bottom_right: { lat: 15, lon: 20 }, }, }, - } as GeoBoundingBoxFilter; + } as esFilters.GeoBoundingBoxFilter; const result = mapGeoBoundingBox(filter); @@ -63,7 +63,8 @@ describe('filter manager utilities', () => { bottom_right: { lat: 15, lon: 20 }, }, }, - } as GeoBoundingBoxFilter; + } as esFilters.GeoBoundingBoxFilter; + const result = mapGeoBoundingBox(filter); expect(result).toHaveProperty('key', 'point'); @@ -82,7 +83,7 @@ describe('filter manager utilities', () => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, - } as Filter; + } as esFilters.Filter; try { mapGeoBoundingBox(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts index 1f9b8cd842509..091e9a3f34000 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts @@ -16,16 +16,10 @@ * specific language governing permissions and limitations * under the License. */ -import { - GeoBoundingBoxFilter, - Filter, - FILTERS, - isGeoBoundingBoxFilter, - FilterValueFormatter, -} from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; const getFormattedValueFn = (params: any) => { - return (formatter?: FilterValueFormatter) => { + return (formatter?: esFilters.FilterValueFormatter) => { const corners = formatter ? { topLeft: formatter.convert(params.top_left), @@ -40,20 +34,20 @@ const getFormattedValueFn = (params: any) => { }; }; -const getParams = (filter: GeoBoundingBoxFilter) => { +const getParams = (filter: esFilters.GeoBoundingBoxFilter) => { const key = Object.keys(filter.geo_bounding_box).filter(k => k !== 'ignore_unmapped')[0]; const params = filter.geo_bounding_box[key]; return { key, params, - type: FILTERS.GEO_BOUNDING_BOX, + type: esFilters.FILTERS.GEO_BOUNDING_BOX, value: getFormattedValueFn(params), }; }; -export const mapGeoBoundingBox = (filter: Filter) => { - if (!isGeoBoundingBoxFilter(filter)) { +export const mapGeoBoundingBox = (filter: esFilters.Filter) => { + if (!esFilters.isGeoBoundingBoxFilter(filter)) { throw filter; } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts index ee4f9b295d682..3afa3891a24bb 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts @@ -16,23 +16,28 @@ * specific language governing permissions and limitations * under the License. */ + import { mapGeoPolygon } from './map_geo_polygon'; -import { GeoPolygonFilter, Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { - describe('mapGeoPolygon()', () => { - test('should return the key and value for matching filters with bounds', async () => { - const filter = { - meta: { - index: 'logstash-*', - }, - geo_polygon: { - point: { - points: [{ lat: 5, lon: 10 }, { lat: 15, lon: 20 }], - }, + let filter: esFilters.GeoPolygonFilter; + + beforeEach(() => { + filter = { + meta: { + index: 'logstash-*', + }, + geo_polygon: { + point: { + points: [{ lat: 5, lon: 10 }, { lat: 15, lon: 20 }], }, - } as GeoPolygonFilter; + }, + } as esFilters.GeoPolygonFilter; + }); + describe('mapGeoPolygon()', () => { + test('should return the key and value for matching filters with bounds', async () => { const result = mapGeoPolygon(filter); expect(result).toHaveProperty('key', 'point'); @@ -48,17 +53,6 @@ describe('filter manager utilities', () => { }); test('should return the key and value even when using ignore_unmapped', async () => { - const filter = { - meta: { - index: 'logstash-*', - }, - geo_polygon: { - ignore_unmapped: true, - point: { - points: [{ lat: 5, lon: 10 }, { lat: 15, lon: 20 }], - }, - }, - } as GeoPolygonFilter; const result = mapGeoPolygon(filter); expect(result).toHaveProperty('key', 'point'); @@ -74,15 +68,15 @@ describe('filter manager utilities', () => { }); test('should return undefined for none matching', async done => { - const filter = { + const wrongFilter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, - } as Filter; + } as esFilters.Filter; try { - mapGeoPolygon(filter); + mapGeoPolygon(wrongFilter); } catch (e) { - expect(e).toBe(filter); + expect(e).toBe(wrongFilter); done(); } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts index 03ce4130d0c97..a7881b4a145a1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts @@ -16,38 +16,33 @@ * specific language governing permissions and limitations * under the License. */ -import { - GeoPolygonFilter, - Filter, - FILTERS, - isGeoPolygonFilter, - FilterValueFormatter, -} from '@kbn/es-query'; + +import { esFilters } from '../../../../../common/es_query'; const POINTS_SEPARATOR = ', '; const getFormattedValueFn = (points: string[]) => { - return (formatter?: FilterValueFormatter) => { + return (formatter?: esFilters.FilterValueFormatter) => { return points .map((point: string) => (formatter ? formatter.convert(point) : JSON.stringify(point))) .join(POINTS_SEPARATOR); }; }; -function getParams(filter: GeoPolygonFilter) { +function getParams(filter: esFilters.GeoPolygonFilter) { const key = Object.keys(filter.geo_polygon).filter(k => k !== 'ignore_unmapped')[0]; const params = filter.geo_polygon[key]; return { key, params, - type: FILTERS.GEO_POLYGON, + type: esFilters.FILTERS.GEO_POLYGON, value: getFormattedValueFn(params.points || []), }; } -export function mapGeoPolygon(filter: Filter) { - if (!isGeoPolygonFilter(filter)) { +export function mapGeoPolygon(filter: esFilters.Filter) { + if (!esFilters.isGeoPolygonFilter(filter)) { throw filter; } return getParams(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts index 2f0641598a2ce..4fc6d0b492414 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts @@ -16,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -import { MatchAllFilter } from '@kbn/es-query'; + import { mapMatchAll } from './map_match_all'; +import { esFilters } from '../../../../../common/es_query'; describe('filter_manager/lib', () => { describe('mapMatchAll()', () => { - let filter: MatchAllFilter; + let filter: esFilters.MatchAllFilter; beforeEach(() => { filter = { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.ts index a1387e6dbe457..4e93b1d41e9a8 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.ts @@ -16,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter, FILTERS, isMatchAllFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; -export const mapMatchAll = (filter: Filter) => { - if (isMatchAllFilter(filter)) { +export const mapMatchAll = (filter: esFilters.Filter) => { + if (esFilters.isMatchAllFilter(filter)) { return { - type: FILTERS.MATCH_ALL, + type: esFilters.FILTERS.MATCH_ALL, key: filter.meta.field, value: filter.meta.formattedValue || 'all', }; diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts index ca23f25826906..1847eb37ca42f 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts @@ -16,15 +16,16 @@ * specific language governing permissions and limitations * under the License. */ -import { MissingFilter, buildEmptyFilter, ExistsFilter } from '@kbn/es-query'; + import { mapMissing } from './map_missing'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapMissing()', () => { test('should return the key and value for matching filters', async () => { - const filter: MissingFilter = { + const filter: esFilters.MissingFilter = { missing: { field: '_type' }, - ...buildEmptyFilter(true), + ...esFilters.buildEmptyFilter(true), }; const result = mapMissing(filter); @@ -33,7 +34,7 @@ describe('filter manager utilities', () => { }); test('should return undefined for none matching', async done => { - const filter = buildEmptyFilter(true) as ExistsFilter; + const filter = esFilters.buildEmptyFilter(true); try { mapMissing(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.ts index 861a84ed61646..51dee89ad884b 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.ts @@ -16,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter, FILTERS, isMissingFilter } from '@kbn/es-query'; -export const mapMissing = (filter: Filter) => { - if (isMissingFilter(filter)) { +import { esFilters } from '../../../../../common/es_query'; + +export const mapMissing = (filter: esFilters.Filter) => { + if (esFilters.isMissingFilter(filter)) { return { - type: FILTERS.MISSING, - value: FILTERS.MISSING, + type: esFilters.FILTERS.MISSING, + value: esFilters.FILTERS.MISSING, key: filter.missing.field, }; } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts index c95a2529add14..05372d37264b0 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts @@ -17,7 +17,7 @@ * under the License. */ import { mapPhrase } from './map_phrase'; -import { PhraseFilter, Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapPhrase()', () => { @@ -25,11 +25,13 @@ describe('filter manager utilities', () => { const filter = { meta: { index: 'logstash-*' }, query: { match: { _type: { query: 'apache', type: 'phrase' } } }, - } as PhraseFilter; + } as esFilters.PhraseFilter; + const result = mapPhrase(filter); expect(result).toHaveProperty('value'); expect(result).toHaveProperty('key', '_type'); + if (result.value) { const displayName = result.value(); expect(displayName).toBe('apache'); @@ -40,7 +42,7 @@ describe('filter manager utilities', () => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, - } as Filter; + } as esFilters.Filter; try { mapPhrase(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.ts index efa348c9ad320..b6e9c2007db97 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.ts @@ -18,45 +18,36 @@ */ import { get } from 'lodash'; -import { - PhraseFilter, - Filter, - FILTERS, - isPhraseFilter, - isScriptedPhraseFilter, - getPhraseFilterField, - getPhraseFilterValue, - FilterValueFormatter, -} from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; -const getScriptedPhraseValue = (filter: PhraseFilter) => +const getScriptedPhraseValue = (filter: esFilters.PhraseFilter) => get(filter, ['script', 'script', 'params', 'value']); const getFormattedValueFn = (value: any) => { - return (formatter?: FilterValueFormatter) => { + return (formatter?: esFilters.FilterValueFormatter) => { return formatter ? formatter.convert(value) : value; }; }; -const getParams = (filter: PhraseFilter) => { +const getParams = (filter: esFilters.PhraseFilter) => { const scriptedPhraseValue = getScriptedPhraseValue(filter); const isScriptedFilter = Boolean(scriptedPhraseValue); - const key = isScriptedFilter ? filter.meta.field || '' : getPhraseFilterField(filter); - const query = scriptedPhraseValue || getPhraseFilterValue(filter); + const key = isScriptedFilter ? filter.meta.field || '' : esFilters.getPhraseFilterField(filter); + const query = scriptedPhraseValue || esFilters.getPhraseFilterValue(filter); const params = { query }; return { key, params, - type: FILTERS.PHRASE, + type: esFilters.FILTERS.PHRASE, value: getFormattedValueFn(query), }; }; -export const isMapPhraseFilter = (filter: any): filter is PhraseFilter => - isPhraseFilter(filter) || isScriptedPhraseFilter(filter); +export const isMapPhraseFilter = (filter: any): filter is esFilters.PhraseFilter => + esFilters.isPhraseFilter(filter) || esFilters.isScriptedPhraseFilter(filter); -export const mapPhrase = (filter: Filter) => { +export const mapPhrase = (filter: esFilters.Filter) => { if (!isMapPhraseFilter(filter)) { throw filter; } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrases.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrases.ts index c17ff11d49fd4..7240d87d02b5a 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrases.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrases.ts @@ -17,10 +17,10 @@ * under the License. */ -import { Filter, isPhrasesFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; -export const mapPhrases = (filter: Filter) => { - if (!isPhrasesFilter(filter)) { +export const mapPhrases = (filter: esFilters.Filter) => { + if (!esFilters.isPhrasesFilter(filter)) { throw filter; } diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts index 4b1a5d39c405d..c60e7d3454fe0 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts @@ -17,27 +17,28 @@ * under the License. */ -import { QueryStringFilter, buildQueryFilter, buildEmptyFilter } from '@kbn/es-query'; import { mapQueryString } from './map_query_string'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapQueryString()', () => { test('should return the key and value for matching filters', async () => { - const filter: QueryStringFilter = buildQueryFilter( + const filter = esFilters.buildQueryFilter( { query_string: { query: 'foo:bar' } }, - 'index' + 'index', + '' ); - const result = mapQueryString(filter); + const result = mapQueryString(filter as esFilters.Filter); expect(result).toHaveProperty('key', 'query'); expect(result).toHaveProperty('value', 'foo:bar'); }); test('should return undefined for none matching', async done => { - const filter = buildEmptyFilter(true) as QueryStringFilter; + const filter = esFilters.buildEmptyFilter(true); try { - mapQueryString(filter); + mapQueryString(filter as esFilters.Filter); } catch (e) { expect(e).toBe(filter); done(); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.ts index 94da8074edd04..20c3555639a3e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.ts @@ -16,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter, FILTERS, isQueryStringFilter } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; -export const mapQueryString = (filter: Filter) => { - if (isQueryStringFilter(filter)) { +export const mapQueryString = (filter: esFilters.Filter) => { + if (esFilters.isQueryStringFilter(filter)) { return { - type: FILTERS.QUERY_STRING, + type: esFilters.FILTERS.QUERY_STRING, key: 'query', value: filter.query.query_string.query, }; diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts index 12d2919e2d47b..c0d5773d6f2c1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts @@ -18,30 +18,15 @@ */ import { mapRange } from './map_range'; -import { RangeFilter, Filter, FilterMeta } from '@kbn/es-query'; +import { esFilters } from '../../../../../common/es_query'; describe('filter manager utilities', () => { describe('mapRange()', () => { test('should return the key and value for matching filters with gt/lt', async () => { const filter = { - meta: { index: 'logstash-*' } as FilterMeta, + meta: { index: 'logstash-*' } as esFilters.FilterMeta, range: { bytes: { lt: 2048, gt: 1024 } }, - } as RangeFilter; - const result = mapRange(filter); - - expect(result).toHaveProperty('key', 'bytes'); - expect(result).toHaveProperty('value'); - if (result.value) { - const displayName = result.value(); - expect(displayName).toBe('1024 to 2048'); - } - }); - - test('should return the key and value for matching filters with gte/lte', async () => { - const filter = { - meta: { index: 'logstash-*' } as FilterMeta, - range: { bytes: { lte: 2048, gte: 1024 } }, - } as RangeFilter; + } as esFilters.RangeFilter; const result = mapRange(filter); expect(result).toHaveProperty('key', 'bytes'); @@ -56,7 +41,7 @@ describe('filter manager utilities', () => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, - } as Filter; + } as esFilters.Filter; try { mapRange(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.ts index 76f9d3621e171..51fb970f5f03e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.ts @@ -17,18 +17,11 @@ * under the License. */ -import { - Filter, - RangeFilter, - FILTERS, - isRangeFilter, - isScriptedRangeFilter, - FilterValueFormatter, -} from '@kbn/es-query'; import { get, has } from 'lodash'; +import { esFilters } from '../../../../../common/es_query'; const getFormattedValueFn = (left: any, right: any) => { - return (formatter?: FilterValueFormatter) => { + return (formatter?: esFilters.FilterValueFormatter) => { let displayValue = `${left} to ${right}`; if (formatter) { const convert = formatter.getConverterFor('text'); @@ -38,11 +31,12 @@ const getFormattedValueFn = (left: any, right: any) => { }; }; -const getFirstRangeKey = (filter: RangeFilter) => filter.range && Object.keys(filter.range)[0]; -const getRangeByKey = (filter: RangeFilter, key: string) => get(filter, ['range', key]); +const getFirstRangeKey = (filter: esFilters.RangeFilter) => + filter.range && Object.keys(filter.range)[0]; +const getRangeByKey = (filter: esFilters.RangeFilter, key: string) => get(filter, ['range', key]); -function getParams(filter: RangeFilter) { - const isScriptedRange = isScriptedRangeFilter(filter); +function getParams(filter: esFilters.RangeFilter) { + const isScriptedRange = esFilters.isScriptedRangeFilter(filter); const key: string = (isScriptedRange ? filter.meta.field : getFirstRangeKey(filter)) || ''; const params: any = isScriptedRange ? get(filter, 'script.script.params') @@ -56,13 +50,13 @@ function getParams(filter: RangeFilter) { const value = getFormattedValueFn(left, right); - return { type: FILTERS.RANGE, key, value, params }; + return { type: esFilters.FILTERS.RANGE, key, value, params }; } -export const isMapRangeFilter = (filter: any): filter is RangeFilter => - isRangeFilter(filter) || isScriptedRangeFilter(filter); +export const isMapRangeFilter = (filter: any): filter is esFilters.RangeFilter => + esFilters.isRangeFilter(filter) || esFilters.isScriptedRangeFilter(filter); -export const mapRange = (filter: Filter) => { +export const mapRange = (filter: esFilters.Filter) => { if (!isMapRangeFilter(filter)) { throw filter; } diff --git a/src/plugins/data/public/query/filter_manager/lib/only_disabled.test.ts b/src/plugins/data/public/query/filter_manager/lib/only_disabled.test.ts index 3fedcf97a625a..b9731797c9ee3 100644 --- a/src/plugins/data/public/query/filter_manager/lib/only_disabled.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/only_disabled.test.ts @@ -17,8 +17,8 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { onlyDisabledFiltersChanged } from './only_disabled'; +import { esFilters } from '../../../../../data/public'; describe('filter manager utilities', () => { describe('onlyDisabledFiltersChanged()', () => { @@ -27,20 +27,20 @@ describe('filter manager utilities', () => { { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } }, - ] as Filter[]; - const newFilters = [{ meta: { disabled: true } }] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [{ meta: { disabled: true } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(true); }); test('should return false if there are no old filters', () => { - const newFilters = [{ meta: { disabled: false } }] as Filter[]; + const newFilters = [{ meta: { disabled: false } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, undefined)).toBe(false); }); test('should return false if there are no new filters', () => { - const filters = [{ meta: { disabled: false } }] as Filter[]; + const filters = [{ meta: { disabled: false } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(undefined, filters)).toBe(false); }); @@ -50,8 +50,8 @@ describe('filter manager utilities', () => { { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } }, - ] as Filter[]; - const newFilters = [{ meta: { disabled: false } }] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [{ meta: { disabled: false } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); @@ -61,8 +61,8 @@ describe('filter manager utilities', () => { { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } }, - ] as Filter[]; - const newFilters = [{ meta: { disabled: false } }] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [{ meta: { disabled: false } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); @@ -72,8 +72,8 @@ describe('filter manager utilities', () => { { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } }, - ] as Filter[]; - const newFilters = [{ meta: { disabled: true } }] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [{ meta: { disabled: true } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); @@ -83,8 +83,8 @@ describe('filter manager utilities', () => { { meta: { disabled: true } }, { meta: { disabled: true } }, { meta: { disabled: true } }, - ] as Filter[]; - const newFilters = [] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(true); }); @@ -94,8 +94,8 @@ describe('filter manager utilities', () => { { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: false } }, - ] as Filter[]; - const newFilters = [] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); @@ -104,11 +104,11 @@ describe('filter manager utilities', () => { const filters = [ { meta: { disabled: true, negate: false } }, { meta: { disabled: true, negate: false } }, - ] as Filter[]; + ] as esFilters.Filter[]; const newFilters = [ { meta: { disabled: true, negate: true } }, { meta: { disabled: true, negate: true } }, - ] as Filter[]; + ] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(true); }); @@ -118,8 +118,8 @@ describe('filter manager utilities', () => { { meta: { disabled: false } }, { meta: { disabled: false } }, { meta: { disabled: true } }, - ] as Filter[]; - const newFilters = [{ meta: { disabled: false } }] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [{ meta: { disabled: false } }] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); @@ -129,15 +129,15 @@ describe('filter manager utilities', () => { { meta: { disabled: true } }, { meta: { disabled: false } }, { meta: { disabled: true } }, - ] as Filter[]; - const newFilters = [] as Filter[]; + ] as esFilters.Filter[]; + const newFilters = [] as esFilters.Filter[]; expect(onlyDisabledFiltersChanged(newFilters, filters)).toBe(false); }); test('should not throw with null filters', () => { - const filters = [null, { meta: { disabled: true } }] as Filter[]; - const newFilters = [] as Filter[]; + const filters = [null, { meta: { disabled: true } }] as esFilters.Filter[]; + const newFilters = [] as esFilters.Filter[]; expect(() => { onlyDisabledFiltersChanged(newFilters, filters); diff --git a/src/plugins/data/public/query/filter_manager/lib/only_disabled.ts b/src/plugins/data/public/query/filter_manager/lib/only_disabled.ts index 9c0b5f43acb3e..0fb6894a297a1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/only_disabled.ts +++ b/src/plugins/data/public/query/filter_manager/lib/only_disabled.ts @@ -17,17 +17,20 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { filter, isEqual } from 'lodash'; +import { esFilters } from '../../../../../../plugins/data/public'; -const isEnabled = (f: Filter) => f && f.meta && !f.meta.disabled; +const isEnabled = (f: esFilters.Filter) => f && f.meta && !f.meta.disabled; /** * Checks to see if only disabled filters have been changed * * @returns {bool} Only disabled filters */ -export const onlyDisabledFiltersChanged = (newFilters?: Filter[], oldFilters?: Filter[]) => { +export const onlyDisabledFiltersChanged = ( + newFilters?: esFilters.Filter[], + oldFilters?: esFilters.Filter[] +) => { // If it's the same - compare only enabled filters const newEnabledFilters = filter(newFilters || [], isEnabled); const oldEnabledFilters = filter(oldFilters || [], isEnabled); diff --git a/src/plugins/data/public/query/filter_manager/lib/uniq_filters.test.ts b/src/plugins/data/public/query/filter_manager/lib/uniq_filters.test.ts index 86f059913cd96..08eeabc1497e3 100644 --- a/src/plugins/data/public/query/filter_manager/lib/uniq_filters.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/uniq_filters.test.ts @@ -16,15 +16,24 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter, buildQueryFilter, FilterStateStore } from '@kbn/es-query'; + import { uniqFilters } from './uniq_filters'; +import { esFilters } from '../../../../../data/public'; describe('filter manager utilities', () => { describe('niqFilter', () => { test('should filter out dups', () => { - const before: Filter[] = [ - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), + const before: esFilters.Filter[] = [ + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), ]; const results = uniqFilters(before); @@ -32,9 +41,17 @@ describe('filter manager utilities', () => { }); test('should filter out duplicates, ignoring meta attributes', () => { - const before: Filter[] = [ - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index1'), - buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index2'), + const before: esFilters.Filter[] = [ + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index1', + '' + ), + esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index2', + '' + ), ]; const results = uniqFilters(before); @@ -42,14 +59,22 @@ describe('filter manager utilities', () => { }); test('should filter out duplicates, ignoring $state attributes', () => { - const before: Filter[] = [ + const before: esFilters.Filter[] = [ { - $state: { store: FilterStateStore.APP_STATE }, - ...buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), + $state: { store: esFilters.FilterStateStore.APP_STATE }, + ...esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), }, { - $state: { store: FilterStateStore.GLOBAL_STATE }, - ...buildQueryFilter({ _type: { match: { query: 'apache', type: 'phrase' } } }, 'index'), + $state: { store: esFilters.FilterStateStore.GLOBAL_STATE }, + ...esFilters.buildQueryFilter( + { _type: { match: { query: 'apache', type: 'phrase' } } }, + 'index', + '' + ), }, ]; const results = uniqFilters(before); diff --git a/src/plugins/data/public/query/filter_manager/lib/uniq_filters.ts b/src/plugins/data/public/query/filter_manager/lib/uniq_filters.ts index 12e793253371e..e96c52e6db3de 100644 --- a/src/plugins/data/public/query/filter_manager/lib/uniq_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/uniq_filters.ts @@ -16,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter } from '@kbn/es-query'; import { each, union } from 'lodash'; import { dedupFilters } from './dedup_filters'; +import { esFilters } from '../../../../../data/public'; /** * Remove duplicate filters from an array of filters @@ -28,10 +28,10 @@ import { dedupFilters } from './dedup_filters'; * @returns {object} The original filters array with duplicates removed */ -export const uniqFilters = (filters: Filter[], comparatorOptions: any = {}) => { - let results: Filter[] = []; +export const uniqFilters = (filters: esFilters.Filter[], comparatorOptions: any = {}) => { + let results: esFilters.Filter[] = []; - each(filters, (filter: Filter) => { + each(filters, (filter: esFilters.Filter) => { results = union(results, dedupFilters(results, [filter]), comparatorOptions); }); diff --git a/src/plugins/data/public/query/filter_manager/test_helpers/get_filters_array.ts b/src/plugins/data/public/query/filter_manager/test_helpers/get_filters_array.ts index 27f627b477c35..aa047647c5751 100644 --- a/src/plugins/data/public/query/filter_manager/test_helpers/get_filters_array.ts +++ b/src/plugins/data/public/query/filter_manager/test_helpers/get_filters_array.ts @@ -17,9 +17,9 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; -export function getFiltersArray(): Filter[] { +export function getFiltersArray(): esFilters.Filter[] { return [ { query: { match: { extension: { query: 'jpg', type: 'phrase' } } }, diff --git a/src/plugins/data/public/query/filter_manager/test_helpers/get_stub_filter.ts b/src/plugins/data/public/query/filter_manager/test_helpers/get_stub_filter.ts index 20d9e236f49be..adc72c961b08b 100644 --- a/src/plugins/data/public/query/filter_manager/test_helpers/get_stub_filter.ts +++ b/src/plugins/data/public/query/filter_manager/test_helpers/get_stub_filter.ts @@ -17,15 +17,15 @@ * under the License. */ -import { Filter, FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../../../plugins/data/public'; export function getFilter( - store: FilterStateStore, + store: esFilters.FilterStateStore, disabled: boolean, negated: boolean, queryKey: string, queryValue: any -): Filter { +): esFilters.Filter { return { $state: { store, diff --git a/src/plugins/data/public/query/filter_manager/types.ts b/src/plugins/data/public/query/filter_manager/types.ts index e74b48b722cc4..0b3dbca2d6e0a 100644 --- a/src/plugins/data/public/query/filter_manager/types.ts +++ b/src/plugins/data/public/query/filter_manager/types.ts @@ -17,9 +17,9 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../plugins/data/public'; export interface PartitionedFilters { - globalFilters: Filter[]; - appFilters: Filter[]; + globalFilters: esFilters.Filter[]; + appFilters: esFilters.Filter[]; } diff --git a/src/plugins/data/public/query/index.tsx b/src/plugins/data/public/query/index.tsx index 44b371b6adf19..42647b9d98201 100644 --- a/src/plugins/data/public/query/index.tsx +++ b/src/plugins/data/public/query/index.tsx @@ -18,5 +18,4 @@ */ export * from './query_service'; - export * from './filter_manager'; diff --git a/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts b/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts index 99cfb2ea13d07..e2592b70397f3 100644 --- a/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts +++ b/src/plugins/embeddable/public/lib/actions/apply_filter_action.ts @@ -18,16 +18,16 @@ */ import { i18n } from '@kbn/i18n'; -import { Filter } from '@kbn/es-query'; import { IAction, createAction, IncompatibleActionError } from '../ui_actions'; import { IEmbeddable, EmbeddableInput } from '../embeddables'; +import { esFilters } from '../../../../../plugins/data/public'; export const APPLY_FILTER_ACTION = 'APPLY_FILTER_ACTION'; -type RootEmbeddable = IEmbeddable; +type RootEmbeddable = IEmbeddable; interface ActionContext { embeddable: IEmbeddable; - filters: Filter[]; + filters: esFilters.Filter[]; } async function isCompatible(context: ActionContext) { diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_action.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_action.test.tsx index 802be5bf1282e..47113ffc59561 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_action.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_action.test.tsx @@ -20,7 +20,6 @@ import { ViewMode, EmbeddableOutput, isErrorEmbeddable } from '../../../../'; import { AddPanelAction } from './add_panel_action'; import { EmbeddableFactory } from '../../../../embeddables'; -import { Filter, FilterStateStore } from '@kbn/es-query'; import { FILTERABLE_EMBEDDABLE, FilterableEmbeddable, @@ -32,6 +31,7 @@ import { GetEmbeddableFactory } from '../../../../types'; // eslint-disable-next-line import { coreMock } from '../../../../../../../../core/public/mocks'; import { ContactCardEmbeddable } from '../../../../test_samples'; +import { esFilters } from '../../../../../../../../plugins/data/public'; const embeddableFactories = new Map(); embeddableFactories.set(FILTERABLE_EMBEDDABLE, new FilterableEmbeddableFactory()); @@ -51,8 +51,8 @@ beforeEach(async () => { () => null ); - const derivedFilter: Filter = { - $state: { store: FilterStateStore.APP_STATE }, + const derivedFilter: esFilters.Filter = { + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, alias: 'name', negate: false }, query: { match: {} }, }; diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/inspect_panel_action.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/inspect_panel_action.test.tsx index 550f9706a634b..8d9beec940acc 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/inspect_panel_action.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/inspect_panel_action.test.tsx @@ -28,7 +28,6 @@ import { } from '../../../test_samples'; // eslint-disable-next-line import { inspectorPluginMock } from 'src/plugins/inspector/public/mocks'; -import { FilterStateStore } from '@kbn/es-query'; import { EmbeddableFactory, EmbeddableOutput, @@ -37,6 +36,7 @@ import { } from '../../../embeddables'; import { GetEmbeddableFactory } from '../../../types'; import { of } from '../../../../tests/helpers'; +import { esFilters } from '../../../../../../../plugins/data/public'; const setup = async () => { const embeddableFactories = new Map(); @@ -48,7 +48,7 @@ const setup = async () => { panels: {}, filters: [ { - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, alias: 'name', negate: false }, query: { match: {} }, }, diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/remove_panel_action.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/remove_panel_action.test.tsx index 22e3be89f1ae9..684a8c45a4e89 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/remove_panel_action.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/remove_panel_action.test.tsx @@ -17,7 +17,6 @@ * under the License. */ -import { Filter, FilterStateStore } from '@kbn/es-query'; import { EmbeddableOutput, isErrorEmbeddable } from '../../../'; import { RemovePanelAction } from './remove_panel_action'; import { EmbeddableFactory } from '../../../embeddables'; @@ -30,6 +29,7 @@ import { FilterableEmbeddableFactory } from '../../../test_samples/embeddables/f import { FilterableContainer } from '../../../test_samples/embeddables/filterable_container'; import { GetEmbeddableFactory, ViewMode } from '../../../types'; import { ContactCardEmbeddable } from '../../../test_samples/embeddables/contact_card/contact_card_embeddable'; +import { esFilters } from '../../../../../../../plugins/data/public'; const embeddableFactories = new Map(); embeddableFactories.set(FILTERABLE_EMBEDDABLE, new FilterableEmbeddableFactory()); @@ -39,8 +39,8 @@ let container: FilterableContainer; let embeddable: FilterableEmbeddable; beforeEach(async () => { - const derivedFilter: Filter = { - $state: { store: FilterStateStore.APP_STATE }, + const derivedFilter: esFilters.Filter = { + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, alias: 'name', negate: false }, query: { match: {} }, }; diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container.tsx index eaef8048a6fbf..de708b778c3c7 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_container.tsx @@ -16,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -import { Filter } from '@kbn/es-query'; + import { Container, ContainerInput } from '../../containers'; import { GetEmbeddableFactory } from '../../types'; +import { esFilters } from '../../../../../data/public'; export const FILTERABLE_CONTAINER = 'FILTERABLE_CONTAINER'; export interface FilterableContainerInput extends ContainerInput { - filters: Filter[]; + filters: esFilters.Filter[]; } /** @@ -33,7 +34,7 @@ export interface FilterableContainerInput extends ContainerInput { */ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions export type InheritedChildrenInput = { - filters: Filter[]; + filters: esFilters.Filter[]; id?: string; }; diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable.tsx index f6885ca25b437..56aa7688f37a6 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/filterable_embeddable.tsx @@ -17,14 +17,14 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { IContainer } from '../../containers'; import { EmbeddableOutput, EmbeddableInput, Embeddable } from '../../embeddables'; +import { esFilters } from '../../../../../data/public'; export const FILTERABLE_EMBEDDABLE = 'FILTERABLE_EMBEDDABLE'; export interface FilterableEmbeddableInput extends EmbeddableInput { - filters: Filter[]; + filters: esFilters.Filter[]; } export class FilterableEmbeddable extends Embeddable { diff --git a/src/plugins/embeddable/public/tests/apply_filter_action.test.ts b/src/plugins/embeddable/public/tests/apply_filter_action.test.ts index 52500acc3dc59..0721acb1a1fba 100644 --- a/src/plugins/embeddable/public/tests/apply_filter_action.test.ts +++ b/src/plugins/embeddable/public/tests/apply_filter_action.test.ts @@ -32,7 +32,7 @@ import { } from '../lib/test_samples'; // eslint-disable-next-line import { inspectorPluginMock } from 'src/plugins/inspector/public/mocks'; -import { FilterStateStore } from '@kbn/es-query'; +import { esFilters } from '../../../../plugins/data/public'; test('ApplyFilterAction applies the filter to the root of the container tree', async () => { const { doStart } = testPlugin(); @@ -76,7 +76,7 @@ test('ApplyFilterAction applies the filter to the root of the container tree', a } const filter: any = { - $state: { store: FilterStateStore.APP_STATE }, + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, negate: false, diff --git a/src/plugins/embeddable/public/tests/container.test.ts b/src/plugins/embeddable/public/tests/container.test.ts index 3bdbcbad857d6..f97c26a41b901 100644 --- a/src/plugins/embeddable/public/tests/container.test.ts +++ b/src/plugins/embeddable/public/tests/container.test.ts @@ -26,7 +26,6 @@ import { FILTERABLE_EMBEDDABLE, } from '../lib/test_samples/embeddables/filterable_embeddable'; import { ERROR_EMBEDDABLE_TYPE } from '../lib/embeddables/error_embeddable'; -import { Filter, FilterStateStore } from '@kbn/es-query'; import { FilterableEmbeddableFactory } from '../lib/test_samples/embeddables/filterable_embeddable_factory'; import { CONTACT_CARD_EMBEDDABLE } from '../lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory'; import { SlowContactCardEmbeddableFactory } from '../lib/test_samples/embeddables/contact_card/slow_contact_card_embeddable_factory'; @@ -46,6 +45,7 @@ import { import { coreMock } from '../../../../core/public/mocks'; import { testPlugin } from './test_plugin'; import { of } from './helpers'; +import { esFilters } from '../../../../plugins/data/public'; async function creatHelloWorldContainerAndEmbeddable( containerInput: ContainerInput = { id: 'hello', panels: {} }, @@ -437,8 +437,8 @@ test('Test nested reactions', async done => { test('Explicit embeddable input mapped to undefined will default to inherited', async () => { const { start } = await creatHelloWorldContainerAndEmbeddable(); - const derivedFilter: Filter = { - $state: { store: FilterStateStore.APP_STATE }, + const derivedFilter: esFilters.Filter = { + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, alias: 'name', negate: false }, query: { match: {} }, }; diff --git a/src/plugins/embeddable/public/tests/explicit_input.test.ts b/src/plugins/embeddable/public/tests/explicit_input.test.ts index 6cde7bdc48ba1..47c4b0944cef2 100644 --- a/src/plugins/embeddable/public/tests/explicit_input.test.ts +++ b/src/plugins/embeddable/public/tests/explicit_input.test.ts @@ -18,7 +18,6 @@ */ import { skip } from 'rxjs/operators'; -import { Filter, FilterStateStore } from '@kbn/es-query'; import { testPlugin } from './test_plugin'; import { FILTERABLE_EMBEDDABLE, @@ -34,6 +33,7 @@ import { isErrorEmbeddable } from '../lib'; import { HelloWorldContainer } from '../lib/test_samples/embeddables/hello_world_container'; // eslint-disable-next-line import { coreMock } from '../../../../core/public/mocks'; +import { esFilters } from '../../../../plugins/data/public'; const { setup, doStart, coreStart, uiActions } = testPlugin( coreMock.createSetup(), @@ -50,8 +50,8 @@ setup.registerEmbeddableFactory(CONTACT_CARD_EMBEDDABLE, factory); setup.registerEmbeddableFactory(HELLO_WORLD_EMBEDDABLE_TYPE, new HelloWorldEmbeddableFactory()); test('Explicit embeddable input mapped to undefined will default to inherited', async () => { - const derivedFilter: Filter = { - $state: { store: FilterStateStore.APP_STATE }, + const derivedFilter: esFilters.Filter = { + $state: { store: esFilters.FilterStateStore.APP_STATE }, meta: { disabled: false, alias: 'name', negate: false }, query: { match: {} }, }; diff --git a/src/plugins/expressions/public/expression_types/kibana_context.ts b/src/plugins/expressions/public/expression_types/kibana_context.ts index 174517abc2c05..bcf8e2853dec8 100644 --- a/src/plugins/expressions/public/expression_types/kibana_context.ts +++ b/src/plugins/expressions/public/expression_types/kibana_context.ts @@ -17,8 +17,7 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; -import { TimeRange, Query } from 'src/plugins/data/public'; +import { TimeRange, Query, esFilters } from 'src/plugins/data/public'; const name = 'kibana_context'; export type KIBANA_CONTEXT_NAME = 'kibana_context'; @@ -26,7 +25,7 @@ export type KIBANA_CONTEXT_NAME = 'kibana_context'; export interface KibanaContext { type: typeof name; query?: Query | Query[]; - filters?: Filter[]; + filters?: esFilters.Filter[]; timeRange?: TimeRange; } diff --git a/src/plugins/expressions/public/types/index.ts b/src/plugins/expressions/public/types/index.ts index 2adb0d7794159..2d66216a9770b 100644 --- a/src/plugins/expressions/public/types/index.ts +++ b/src/plugins/expressions/public/types/index.ts @@ -17,13 +17,13 @@ * under the License. */ -import { Filter } from '@kbn/es-query'; import { ExpressionInterpret } from '../interpreter_provider'; import { TimeRange } from '../../../data/public'; import { Adapters } from '../../../inspector/public'; import { Query } from '../../../data/public'; import { ExpressionAST } from '../../../expressions/public'; import { ExpressionArgAST } from '../../../../plugins/expressions/public'; +import { esFilters } from '../../../../plugins/data/public'; export { ArgumentType } from './arguments'; export { @@ -76,7 +76,7 @@ export type Context = object; export interface SearchContext { type: 'kibana_context'; - filters?: Filter[]; + filters?: esFilters.Filter[]; query?: Query; timeRange?: TimeRange; } diff --git a/x-pack/legacy/plugins/canvas/canvas_plugin_src/functions/common/saved_map.ts b/x-pack/legacy/plugins/canvas/canvas_plugin_src/functions/common/saved_map.ts index 958d9c6a3a6f0..abaa16c4e3271 100644 --- a/x-pack/legacy/plugins/canvas/canvas_plugin_src/functions/common/saved_map.ts +++ b/x-pack/legacy/plugins/canvas/canvas_plugin_src/functions/common/saved_map.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { Filter as ESFilterType } from '@kbn/es-query'; import { ExpressionFunction } from 'src/legacy/core_plugins/interpreter/public'; import { TimeRange } from 'src/plugins/data/public'; import { EmbeddableInput } from 'src/legacy/core_plugins/embeddable_api/public/np_ready/public'; @@ -15,6 +14,7 @@ import { EmbeddableExpression, } from '../../expression_types'; import { getFunctionHelp } from '../../../i18n'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; interface Arguments { id: string; @@ -29,7 +29,7 @@ interface SavedMapInput extends EmbeddableInput { isPaused: boolean; interval: number; }; - filters: ESFilterType[]; + filters: esFilters.Filter[]; } type Return = EmbeddableExpression; diff --git a/x-pack/legacy/plugins/canvas/server/lib/build_embeddable_filters.ts b/x-pack/legacy/plugins/canvas/server/lib/build_embeddable_filters.ts index 8de813255a230..ca34246531bff 100644 --- a/x-pack/legacy/plugins/canvas/server/lib/build_embeddable_filters.ts +++ b/x-pack/legacy/plugins/canvas/server/lib/build_embeddable_filters.ts @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { buildQueryFilter, Filter as ESFilterType } from '@kbn/es-query'; import { TimeRange } from 'src/plugins/data/public'; import { Filter } from '../../types'; // @ts-ignore Untyped Local import { buildBoolArray } from './build_bool_array'; +import { esFilters } from '../../../../../../src/plugins/data/common'; export interface EmbeddableFilterInput { - filters: ESFilterType[]; + filters: esFilters.Filter[]; timeRange?: TimeRange; } @@ -30,8 +30,10 @@ function getTimeRangeFromFilters(filters: Filter[]): TimeRange | undefined { : undefined; } -function getQueryFilters(filters: Filter[]): ESFilterType[] { - return buildBoolArray(filters.filter(filter => filter.type !== 'time')).map(buildQueryFilter); +function getQueryFilters(filters: Filter[]): esFilters.Filter[] { + return buildBoolArray(filters.filter(filter => filter.type !== 'time')).map( + esFilters.buildQueryFilter + ); } export function buildEmbeddableFilters(filters: Filter[]): EmbeddableFilterInput { diff --git a/x-pack/legacy/plugins/lens/public/app_plugin/app.test.tsx b/x-pack/legacy/plugins/lens/public/app_plugin/app.test.tsx index a1710d67b31db..31d622c7089a8 100644 --- a/x-pack/legacy/plugins/lens/public/app_plugin/app.test.tsx +++ b/x-pack/legacy/plugins/lens/public/app_plugin/app.test.tsx @@ -7,12 +7,12 @@ import React from 'react'; import { ReactWrapper } from 'enzyme'; import { act } from 'react-dom/test-utils'; -import { buildExistsFilter } from '@kbn/es-query'; import { App } from './app'; import { EditorFrameInstance } from '../types'; import { Storage } from '../../../../../../src/plugins/kibana_utils/public'; import { Document, SavedObjectStore } from '../persistence'; import { mount } from 'enzyme'; +import { esFilters } from '../../../../../../src/plugins/data/public'; import { dataPluginMock } from '../../../../../../src/plugins/data/public/mocks'; const dataStartMock = dataPluginMock.createStartContract(); @@ -595,7 +595,7 @@ describe('Lens App', () => { const instance = mount(); args.data.query.filterManager.setFilters([ - buildExistsFilter({ name: 'myfield' }, { id: 'index1' }), + esFilters.buildExistsFilter({ name: 'myfield' }, { id: 'index1' }), ]); instance.update(); @@ -603,7 +603,7 @@ describe('Lens App', () => { expect(frame.mount).toHaveBeenCalledWith( expect.any(Element), expect.objectContaining({ - filters: [buildExistsFilter({ name: 'myfield' }, { id: 'index1' })], + filters: [esFilters.buildExistsFilter({ name: 'myfield' }, { id: 'index1' })], }) ); }); @@ -726,7 +726,7 @@ describe('Lens App', () => { }); args.data.query.filterManager.setFilters([ - buildExistsFilter({ name: 'myfield' }, { id: 'index1' }), + esFilters.buildExistsFilter({ name: 'myfield' }, { id: 'index1' }), ]); instance.update(); diff --git a/x-pack/legacy/plugins/lens/public/app_plugin/app.tsx b/x-pack/legacy/plugins/lens/public/app_plugin/app.tsx index a95e0450f614c..2815ac9ddda4e 100644 --- a/x-pack/legacy/plugins/lens/public/app_plugin/app.tsx +++ b/x-pack/legacy/plugins/lens/public/app_plugin/app.tsx @@ -18,7 +18,6 @@ import { SavedQuery, Query, } from 'src/legacy/core_plugins/data/public'; -import { Filter } from '@kbn/es-query'; import { IStorageWrapper } from 'src/plugins/kibana_utils/public'; import { start as navigation } from '../../../../../../src/legacy/core_plugins/navigation/public/legacy'; import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; @@ -26,6 +25,7 @@ import { Document, SavedObjectStore } from '../persistence'; import { EditorFrameInstance } from '../types'; import { NativeRenderer } from '../native_renderer'; import { trackUiEvent } from '../lens_ui_telemetry'; +import { esFilters } from '../../../../../../src/plugins/data/public'; interface State { isLoading: boolean; @@ -40,7 +40,7 @@ interface State { toDate: string; }; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; savedQuery?: SavedQuery; } diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/data_panel_wrapper.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/data_panel_wrapper.tsx index 115e8cbf002c3..a5509cdc94559 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/data_panel_wrapper.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/data_panel_wrapper.tsx @@ -6,7 +6,6 @@ import React, { useMemo, memo, useContext, useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { Filter } from '@kbn/es-query'; import { EuiPopover, EuiButtonIcon, EuiContextMenuPanel, EuiContextMenuItem } from '@elastic/eui'; import { Query } from 'src/plugins/data/common'; import { DatasourceDataPanelProps, Datasource } from '../../../public'; @@ -14,6 +13,7 @@ import { NativeRenderer } from '../../native_renderer'; import { Action } from './state_management'; import { DragContext } from '../../drag_drop'; import { StateSetter, FramePublicAPI } from '../../types'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; interface DataPanelWrapperProps { datasourceState: unknown; @@ -24,7 +24,7 @@ interface DataPanelWrapperProps { core: DatasourceDataPanelProps['core']; query: Query; dateRange: FramePublicAPI['dateRange']; - filters: Filter[]; + filters: esFilters.Filter[]; } export const DataPanelWrapper = memo((props: DataPanelWrapperProps) => { diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/editor_frame.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/editor_frame.tsx index 8e89d8edc9f23..6d782d119525d 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/editor_frame.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/editor_frame.tsx @@ -6,7 +6,6 @@ import React, { useEffect, useReducer } from 'react'; import { CoreSetup, CoreStart } from 'src/core/public'; -import { Filter } from '@kbn/es-query'; import { Query, SavedQuery } from '../../../../../../../src/legacy/core_plugins/data/public'; import { ExpressionRenderer } from '../../../../../../../src/legacy/core_plugins/expressions/public'; import { @@ -26,6 +25,7 @@ import { Document } from '../../persistence/saved_object_store'; import { getSavedObjectFormat } from './save'; import { WorkspacePanelWrapper } from './workspace_panel_wrapper'; import { generateId } from '../../id_generator'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; export interface EditorFrameProps { doc?: Document; @@ -41,7 +41,7 @@ export interface EditorFrameProps { toDate: string; }; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; savedQuery?: SavedQuery; onChange: (arg: { filterableIndexPatterns: DatasourceMetaData['filterableIndexPatterns']; diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/expression_helpers.ts b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/expression_helpers.ts index 1ddfc54cc187b..f03b64295641b 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/expression_helpers.ts +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/expression_helpers.ts @@ -6,9 +6,9 @@ import { TimeRange } from 'src/plugins/data/public'; import { Query } from 'src/legacy/core_plugins/data/public'; -import { Filter } from '@kbn/es-query'; import { Ast, fromExpression, ExpressionFunctionAST } from '@kbn/interpreter/common'; import { Visualization, Datasource, FramePublicAPI } from '../../types'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; export function prependDatasourceExpression( visualizationExpression: Ast | string | null, @@ -71,7 +71,7 @@ export function prependKibanaContext( }: { timeRange?: TimeRange; query?: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; } ): Ast { const parsedExpression = typeof expression === 'string' ? fromExpression(expression) : expression; diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/save.test.ts b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/save.test.ts index ef8194aa6f924..f223a9c06a2a7 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/save.test.ts +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/save.test.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { buildExistsFilter } from '@kbn/es-query'; import { getSavedObjectFormat, Props } from './save'; import { createMockDatasource, createMockVisualization } from '../mocks'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; describe('save editor frame state', () => { const mockVisualization = createMockVisualization(); @@ -37,7 +37,7 @@ describe('save editor frame state', () => { }, query: { query: '', language: 'lucene' }, dateRange: { fromDate: 'now-7d', toDate: 'now' }, - filters: [buildExistsFilter({ name: '@timestamp' }, { id: 'indexpattern' })], + filters: [esFilters.buildExistsFilter({ name: '@timestamp' }, { id: 'indexpattern' })], }, }; diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/workspace_panel.test.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/workspace_panel.test.tsx index 3b79172ea6572..fd35ecd702d23 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/workspace_panel.test.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/editor_frame/workspace_panel.test.tsx @@ -5,8 +5,6 @@ */ import React from 'react'; - -import { buildExistsFilter } from '@kbn/es-query'; import { ExpressionRendererProps } from '../../../../../../../src/legacy/core_plugins/expressions/public'; import { Visualization, FramePublicAPI, TableSuggestion } from '../../types'; import { @@ -22,6 +20,7 @@ import { ReactWrapper } from 'enzyme'; import { DragDrop, ChildDragDropProvider } from '../../drag_drop'; import { Ast } from '@kbn/interpreter/common'; import { coreMock } from 'src/core/public/mocks'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; const waitForPromises = () => new Promise(resolve => setTimeout(resolve)); @@ -382,7 +381,7 @@ describe('workspace_panel', () => { instance.setProps({ framePublicAPI: { ...framePublicAPI, - filters: [buildExistsFilter({ name: 'myfield' }, { id: 'index1' })], + filters: [esFilters.buildExistsFilter({ name: 'myfield' }, { id: 'index1' })], }, }); diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.test.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.test.tsx index d728457b7e3a3..95d39409c57de 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.test.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.test.tsx @@ -5,10 +5,9 @@ */ import { Embeddable } from './embeddable'; -import { TimeRange } from 'src/plugins/data/public'; +import { TimeRange, esFilters } from 'src/plugins/data/public'; import { Query } from 'src/legacy/core_plugins/data/public'; import { ExpressionRendererProps } from 'src/legacy/core_plugins/expressions/public'; -import { Filter } from '@kbn/es-query'; import { Document } from '../../persistence'; jest.mock('../../../../../../../src/legacy/ui/public/inspector', () => ({ @@ -63,7 +62,9 @@ describe('embeddable', () => { it('should re-render if new input is pushed', () => { const timeRange: TimeRange = { from: 'now-15d', to: 'now' }; const query: Query = { language: 'kquery', query: '' }; - const filters: Filter[] = [{ meta: { alias: 'test', negate: false, disabled: false } }]; + const filters: esFilters.Filter[] = [ + { meta: { alias: 'test', negate: false, disabled: false } }, + ]; const embeddable = new Embeddable( expressionRenderer, @@ -88,7 +89,9 @@ describe('embeddable', () => { it('should pass context to embeddable', () => { const timeRange: TimeRange = { from: 'now-15d', to: 'now' }; const query: Query = { language: 'kquery', query: '' }; - const filters: Filter[] = [{ meta: { alias: 'test', negate: false, disabled: false } }]; + const filters: esFilters.Filter[] = [ + { meta: { alias: 'test', negate: false, disabled: false } }, + ]; const embeddable = new Embeddable( expressionRenderer, @@ -112,7 +115,9 @@ describe('embeddable', () => { it('should not re-render if only change is in disabled filter', () => { const timeRange: TimeRange = { from: 'now-15d', to: 'now' }; const query: Query = { language: 'kquery', query: '' }; - const filters: Filter[] = [{ meta: { alias: 'test', negate: false, disabled: true } }]; + const filters: esFilters.Filter[] = [ + { meta: { alias: 'test', negate: false, disabled: true } }, + ]; const embeddable = new Embeddable( expressionRenderer, diff --git a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.tsx b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.tsx index e815a1951bdb7..0b5d4909c8e73 100644 --- a/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.tsx +++ b/x-pack/legacy/plugins/lens/public/editor_frame_plugin/embeddable/embeddable.tsx @@ -8,10 +8,9 @@ import _ from 'lodash'; import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; -import { TimeRange } from 'src/plugins/data/public'; +import { TimeRange, esFilters } from 'src/plugins/data/public'; import { Query, StaticIndexPattern } from 'src/legacy/core_plugins/data/public'; import { ExpressionRenderer } from 'src/legacy/core_plugins/expressions/public'; -import { Filter } from '@kbn/es-query'; import { Subscription } from 'rxjs'; import { Embeddable as AbstractEmbeddable, @@ -32,7 +31,7 @@ export interface LensEmbeddableConfiguration { export interface LensEmbeddableInput extends EmbeddableInput { timeRange?: TimeRange; query?: Query; - filters?: Filter[]; + filters?: esFilters.Filter[]; } export interface LensEmbeddableOutput extends EmbeddableOutput { @@ -50,7 +49,7 @@ export class Embeddable extends AbstractEmbeddable; visualization: unknown; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; }; } diff --git a/x-pack/legacy/plugins/lens/public/types.ts b/x-pack/legacy/plugins/lens/public/types.ts index 2b97f193a563c..b66bb7bee8f8a 100644 --- a/x-pack/legacy/plugins/lens/public/types.ts +++ b/x-pack/legacy/plugins/lens/public/types.ts @@ -6,7 +6,6 @@ import { Ast } from '@kbn/interpreter/common'; import { IconType } from '@elastic/eui/src/components/icon/icon'; -import { Filter } from '@kbn/es-query'; import { CoreSetup } from 'src/core/public'; import { Query } from 'src/plugins/data/common'; import { SavedQuery } from 'src/legacy/core_plugins/data/public'; @@ -14,6 +13,7 @@ import { KibanaDatatable } from '../../../../../src/legacy/core_plugins/interpre import { DragContextState } from './drag_drop'; import { Document } from './persistence'; import { DateRange } from '../common'; +import { esFilters } from '../../../../../src/plugins/data/public'; // eslint-disable-next-line export interface EditorFrameOptions {} @@ -32,7 +32,7 @@ export interface EditorFrameProps { doc?: Document; dateRange: DateRange; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; savedQuery?: SavedQuery; // Frame loader (app or embeddable) is expected to call this when it loads and updates @@ -179,7 +179,7 @@ export interface DatasourceDataPanelProps { core: Pick; query: Query; dateRange: DateRange; - filters: Filter[]; + filters: esFilters.Filter[]; } // The only way a visualization has to restrict the query building @@ -309,7 +309,7 @@ export interface FramePublicAPI { dateRange: DateRange; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; // Adds a new layer. This has a side effect of updating the datasource state addNewLayer: () => string; diff --git a/x-pack/legacy/plugins/maps/public/angular/map_controller.js b/x-pack/legacy/plugins/maps/public/angular/map_controller.js index 594548333cb8c..41c618d68a68e 100644 --- a/x-pack/legacy/plugins/maps/public/angular/map_controller.js +++ b/x-pack/legacy/plugins/maps/public/angular/map_controller.js @@ -53,9 +53,9 @@ import { MAP_SAVED_OBJECT_TYPE, MAP_APP_PATH } from '../../common/constants'; -import { FilterStateStore } from '@kbn/es-query'; import { start as data } from '../../../../../../src/legacy/core_plugins/data/public/legacy'; import { npStart } from 'ui/new_platform'; +import { esFilters } from '../../../../../../src/plugins/data/public'; const { savedQueryService } = data.search.services; @@ -247,7 +247,7 @@ app.controller('GisMapController', ($scope, $route, kbnUrl, localStorage, AppSta function addFilters(newFilters) { newFilters.forEach(filter => { - filter.$state = FilterStateStore.APP_STATE; + filter.$state = esFilters.FilterStateStore.APP_STATE; }); $scope.updateFiltersAndDispatch([...$scope.filters, ...newFilters]); } diff --git a/x-pack/legacy/plugins/maps/public/layers/tooltips/es_tooltip_property.js b/x-pack/legacy/plugins/maps/public/layers/tooltips/es_tooltip_property.js index dae56d5526b0a..446978a151d64 100644 --- a/x-pack/legacy/plugins/maps/public/layers/tooltips/es_tooltip_property.js +++ b/x-pack/legacy/plugins/maps/public/layers/tooltips/es_tooltip_property.js @@ -4,10 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { buildPhraseFilter } from '@kbn/es-query'; import { TooltipProperty } from './tooltip_property'; import _ from 'lodash'; - +import { esFilters } from '../../../../../../../src/plugins/data/public'; export class ESTooltipProperty extends TooltipProperty { constructor(propertyKey, propertyName, rawValue, indexPattern) { @@ -36,7 +35,7 @@ export class ESTooltipProperty extends TooltipProperty { async getESFilters() { return [ - buildPhraseFilter( + esFilters.buildPhraseFilter( this._indexPattern.fields.getByName(this._propertyName), this._rawValue, this._indexPattern) diff --git a/x-pack/legacy/plugins/ml/public/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/legacy/plugins/ml/public/datavisualizer/index_based/data_loader/data_loader.ts index 464be8a9157ae..f0bb998a27614 100644 --- a/x-pack/legacy/plugins/ml/public/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/legacy/plugins/ml/public/datavisualizer/index_based/data_loader/data_loader.ts @@ -4,8 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -// @ts-ignore -import { decorateQuery, luceneStringToDsl } from '@kbn/es-query'; import { i18n } from '@kbn/i18n'; import { toastNotifications } from 'ui/notify'; diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx index 1c712f874969c..b9c28105e99d1 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx @@ -5,7 +5,6 @@ */ import { EuiLink, EuiText } from '@elastic/eui'; -import { Filter } from '@kbn/es-query'; import React, { useEffect, useState } from 'react'; import { createPortalNode, InPortal } from 'react-reverse-portal'; import { Query } from 'src/plugins/data/common'; @@ -30,6 +29,7 @@ import { IndexPatternsMissingPrompt } from './index_patterns_missing_prompt'; import { MapToolTip } from './map_tool_tip/map_tool_tip'; import * as i18n from './translations'; import { MapEmbeddable, SetQuery } from './types'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; interface EmbeddableMapProps { maintainRatio?: boolean; @@ -75,7 +75,7 @@ EmbeddableMap.displayName = 'EmbeddableMap'; export interface EmbeddedMapProps { query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; startDate: number; endDate: number; setQuery: SetQuery; diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.tsx index 7f514b0e53b71..a50cfa98fc977 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import uuid from 'uuid'; import React from 'react'; import { OutPortal, PortalNode } from 'react-reverse-portal'; @@ -28,6 +27,7 @@ import { getLayerList } from './map_config'; // @ts-ignore Missing type defs as maps moves to Typescript import { MAP_SAVED_OBJECT_TYPE } from '../../../../maps/common/constants'; import * as i18n from './translations'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; /** * Displays an error toast for the provided title and message @@ -86,7 +86,7 @@ export const setupEmbeddablesAPI = (plugins: PluginsStart) => { * @throws Error if EmbeddableFactory does not exist */ export const createEmbeddable = async ( - filters: Filter[], + filters: esFilters.Filter[], indexPatterns: IndexPatternMapping[], query: Query, startDate: number, diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/types.ts b/x-pack/legacy/plugins/siem/public/components/embeddables/types.ts index b3d930a13ca35..10412ecdb5013 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/types.ts +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/types.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter as ESFilterType } from '@kbn/es-query'; import { Query } from 'src/plugins/data/common'; import { TimeRange } from 'src/plugins/data/public'; import { @@ -14,9 +13,10 @@ import { EmbeddableFactory, } from '../../../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public'; import { inputsModel } from '../../store/inputs'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; export interface MapEmbeddableInput extends EmbeddableInput { - filters: ESFilterType[]; + filters: esFilters.Filter[]; query: Query; refreshConfig: { isPaused: boolean; diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx index 13f0666b31212..6b79a6402586e 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx @@ -5,7 +5,7 @@ */ import { EuiPanel } from '@elastic/eui'; -import { Filter, getEsQueryConfig } from '@kbn/es-query'; +import { getEsQueryConfig } from '@kbn/es-query'; import { getOr, isEmpty, isEqual } from 'lodash/fp'; import React from 'react'; import styled from 'styled-components'; @@ -31,6 +31,7 @@ import { TimelineRefetch } from '../timeline/refetch_timeline'; import { isCompactFooter } from '../timeline/timeline'; import { ManageTimelineContext } from '../timeline/timeline_context'; import * as i18n from './translations'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; const DEFAULT_EVENTS_VIEWER_HEIGHT = 500; @@ -44,7 +45,7 @@ interface Props { columns: ColumnHeader[]; dataProviders: DataProvider[]; end: number; - filters: Filter[]; + filters: esFilters.Filter[]; height?: number; id: string; indexPattern: StaticIndexPattern; diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx index 9483c60dcc552..5681588cb44b7 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { isEqual } from 'lodash/fp'; import React, { useEffect, useState, useCallback } from 'react'; import { connect } from 'react-redux'; @@ -19,6 +18,7 @@ import { ColumnHeader } from '../timeline/body/column_headers/column_header'; import { DataProvider } from '../timeline/data_providers/data_provider'; import { Sort } from '../timeline/body/sort'; import { OnChangeItemsPerPage } from '../timeline/events'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; import { EventsViewer } from './events_viewer'; import { InputsModelId } from '../../store/inputs/constants'; @@ -33,7 +33,7 @@ interface StateReduxProps { activePage?: number; columns: ColumnHeader[]; dataProviders?: DataProvider[]; - filters: Filter[]; + filters: esFilters.Filter[]; isLive: boolean; itemsPerPage?: number; itemsPerPageOptions?: number[]; diff --git a/x-pack/legacy/plugins/siem/public/components/navigation/helpers.ts b/x-pack/legacy/plugins/siem/public/components/navigation/helpers.ts index 68aa115c965d6..0c44b8d44c317 100644 --- a/x-pack/legacy/plugins/siem/public/components/navigation/helpers.ts +++ b/x-pack/legacy/plugins/siem/public/components/navigation/helpers.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { isEmpty } from 'lodash/fp'; import { Location } from 'history'; import { Query } from 'src/plugins/data/common'; @@ -17,6 +16,7 @@ import { replaceStateKeyInQueryString, getQueryStringFromLocation, } from '../url_state/helpers'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; import { TabNavigationProps } from './tab_navigation/types'; import { SearchNavTab } from './types'; @@ -25,7 +25,7 @@ export const getSearch = (tab: SearchNavTab, urlState: TabNavigationProps): stri if (tab && tab.urlKey != null && URL_STATE_KEYS[tab.urlKey] != null) { return URL_STATE_KEYS[tab.urlKey].reduce( (myLocation: Location, urlKey: KeyUrlState) => { - let urlStateToReplace: UrlInputsModel | Query | Filter[] | Timeline | string = ''; + let urlStateToReplace: UrlInputsModel | Query | esFilters.Filter[] | Timeline | string = ''; if (urlKey === CONSTANTS.appQuery && urlState.query != null) { if (urlState.query.query === '') { diff --git a/x-pack/legacy/plugins/siem/public/components/navigation/tab_navigation/types.ts b/x-pack/legacy/plugins/siem/public/components/navigation/tab_navigation/types.ts index 1d5ebf2097974..856651e6f97dc 100644 --- a/x-pack/legacy/plugins/siem/public/components/navigation/tab_navigation/types.ts +++ b/x-pack/legacy/plugins/siem/public/components/navigation/tab_navigation/types.ts @@ -4,12 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; -import { Query } from 'src/plugins/data/common'; import { UrlInputsModel } from '../../../store/inputs/model'; import { CONSTANTS } from '../../url_state/constants'; import { Timeline } from '../../url_state/types'; import { HostsTableType } from '../../../store/hosts/model'; +import { esFilters, Query } from '../../../../../../../../src/plugins/data/public'; import { SiemNavigationComponentProps } from '../types'; @@ -18,7 +17,7 @@ export interface TabNavigationProps extends SiemNavigationComponentProps { pageName: string; tabName: HostsTableType | undefined; [CONSTANTS.appQuery]?: Query; - [CONSTANTS.filters]?: Filter[]; + [CONSTANTS.filters]?: esFilters.Filter[]; [CONSTANTS.savedQuery]?: string; [CONSTANTS.timerange]: UrlInputsModel; [CONSTANTS.timeline]: Timeline; diff --git a/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.test.tsx index 34e2bc01a4ea7..ed614d79174f0 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.test.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; @@ -13,9 +12,10 @@ import { apolloClientObservable, mockGlobalState, TestProviders } from '../../.. import { createStore, State } from '../../../store'; import { siemFilterManager } from '../../search_bar'; import { AddFilterToGlobalSearchBar } from '.'; +import { esFilters } from '../../../../../../../../src/plugins/data/public'; interface MockSiemFilterManager { - addFilters: (filters: Filter[]) => void; + addFilters: (filters: esFilters.Filter[]) => void; } const mockSiemFilterManager: MockSiemFilterManager = siemFilterManager as MockSiemFilterManager; jest.mock('../../search_bar', () => ({ diff --git a/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.tsx b/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.tsx index 6f3b56417173c..6e1e6545e5534 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/add_filter_to_global_search_bar/index.tsx @@ -5,12 +5,12 @@ */ import { EuiIcon, EuiPanel, EuiToolTip } from '@elastic/eui'; -import { Filter } from '@kbn/es-query'; import React from 'react'; import styled from 'styled-components'; import { WithHoverActions } from '../../with_hover_actions'; import { siemFilterManager } from '../../search_bar'; +import { esFilters } from '../../../../../../../../src/plugins/data/public'; import * as i18n from './translations'; @@ -18,7 +18,7 @@ export * from './helpers'; interface OwnProps { children: JSX.Element; - filter: Filter; + filter: esFilters.Filter; onFilterAdded?: () => void; } diff --git a/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx b/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx index e024a4e68492b..c885d001542e5 100644 --- a/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { getOr, isEqual, set } from 'lodash/fp'; import React, { memo, useEffect, useCallback, useMemo } from 'react'; import { connect } from 'react-redux'; @@ -37,6 +36,7 @@ import { toStrSelector, } from './selectors'; import { timelineActions, hostsActions, networkActions } from '../../store/actions'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; const { ui: { SearchBar }, @@ -67,7 +67,7 @@ interface SiemSearchBarDispatch { id: InputsModelId; savedQuery: SavedQuery | undefined; }) => void; - setSearchBarFilter: ({ id, filters }: { id: InputsModelId; filters: Filter[] }) => void; + setSearchBarFilter: ({ id, filters }: { id: InputsModelId; filters: esFilters.Filter[] }) => void; } interface SiemSearchBarProps { @@ -313,7 +313,7 @@ SearchBarComponent.displayName = 'SiemSearchBar'; interface UpdateReduxSearchBar extends OnTimeChangeProps { id: InputsModelId; - filters?: Filter[]; + filters?: esFilters.Filter[]; query?: Query; savedQuery?: SavedQuery; resetSavedQuery?: boolean; @@ -397,7 +397,7 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ updateSearch: dispatchUpdateSearch(dispatch), setSavedQuery: ({ id, savedQuery }: { id: InputsModelId; savedQuery: SavedQuery | undefined }) => dispatch(inputsActions.setSavedQuery({ id, savedQuery })), - setSearchBarFilter: ({ id, filters }: { id: InputsModelId; filters: Filter[] }) => + setSearchBarFilter: ({ id, filters }: { id: InputsModelId; filters: esFilters.Filter[] }) => dispatch(inputsActions.setSearchBarFilter({ id, filters })), }); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/helpers.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/helpers.tsx index a18e4d7962e95..6182fca6e2e99 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/helpers.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/helpers.tsx @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { isEmpty, isNumber, get } from 'lodash/fp'; import memoizeOne from 'memoize-one'; import { StaticIndexPattern } from 'ui/index_patterns'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { escapeQueryValue, convertToBuildEsQuery, EsQueryConfig } from '../../lib/keury'; @@ -106,7 +105,7 @@ export const combineQueries = ({ dataProviders: DataProvider[]; indexPattern: StaticIndexPattern; browserFields: BrowserFields; - filters: Filter[]; + filters: esFilters.Filter[]; kqlQuery: Query; kqlMode: string; start: number; diff --git a/x-pack/legacy/plugins/siem/public/components/url_state/helpers.ts b/x-pack/legacy/plugins/siem/public/components/url_state/helpers.ts index 9c49d356cd4bc..f7487d7a81a7a 100644 --- a/x-pack/legacy/plugins/siem/public/components/url_state/helpers.ts +++ b/x-pack/legacy/plugins/siem/public/components/url_state/helpers.ts @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { decode, encode, RisonValue } from 'rison-node'; import { Location } from 'history'; import { QueryString } from 'ui/utils/query_string'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { inputsSelectors, State, timelineSelectors } from '../../store'; import { SiemPageName } from '../../pages/home/types'; @@ -154,7 +153,7 @@ export const makeMapStateToProps = () => { let searchAttr: { [CONSTANTS.appQuery]?: Query; - [CONSTANTS.filters]?: Filter[]; + [CONSTANTS.filters]?: esFilters.Filter[]; [CONSTANTS.savedQuery]?: string; } = { [CONSTANTS.appQuery]: getGlobalQuerySelector(state), diff --git a/x-pack/legacy/plugins/siem/public/components/url_state/initialize_redux_by_url.tsx b/x-pack/legacy/plugins/siem/public/components/url_state/initialize_redux_by_url.tsx index fa3b278866704..013983c78a3a5 100644 --- a/x-pack/legacy/plugins/siem/public/components/url_state/initialize_redux_by_url.tsx +++ b/x-pack/legacy/plugins/siem/public/components/url_state/initialize_redux_by_url.tsx @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { get, isEmpty } from 'lodash/fp'; import { Dispatch } from 'redux'; import { SavedQuery } from 'src/legacy/core_plugins/data/public'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { inputsActions } from '../../store/actions'; import { InputsModelId, TimeRangeKinds } from '../../store/inputs/constants'; @@ -125,7 +124,7 @@ export const dispatchSetInitialStateFromUrl = ( } if (urlKey === CONSTANTS.filters) { - const filters: Filter[] = decodeRisonUrlState(newUrlStateString); + const filters: esFilters.Filter[] = decodeRisonUrlState(newUrlStateString); siemFilterManager.setFilters(filters || []); } diff --git a/x-pack/legacy/plugins/siem/public/components/url_state/types.ts b/x-pack/legacy/plugins/siem/public/components/url_state/types.ts index f858ffc32ddbc..44c050a1990ce 100644 --- a/x-pack/legacy/plugins/siem/public/components/url_state/types.ts +++ b/x-pack/legacy/plugins/siem/public/components/url_state/types.ts @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import ApolloClient from 'apollo-client'; import { ActionCreator } from 'typescript-fsa'; import { StaticIndexPattern } from 'ui/index_patterns'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { UrlInputsModel } from '../../store/inputs/model'; import { RouteSpyState } from '../../utils/route/types'; @@ -60,7 +59,7 @@ export interface Timeline { export interface UrlState { [CONSTANTS.appQuery]?: Query; - [CONSTANTS.filters]?: Filter[]; + [CONSTANTS.filters]?: esFilters.Filter[]; [CONSTANTS.savedQuery]?: string; [CONSTANTS.timerange]: UrlInputsModel; [CONSTANTS.timeline]: Timeline; diff --git a/x-pack/legacy/plugins/siem/public/components/url_state/use_url_state.tsx b/x-pack/legacy/plugins/siem/public/components/url_state/use_url_state.tsx index 5b9511f169744..f1eeb4e6fbec4 100644 --- a/x-pack/legacy/plugins/siem/public/components/url_state/use_url_state.tsx +++ b/x-pack/legacy/plugins/siem/public/components/url_state/use_url_state.tsx @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; + import { Location } from 'history'; import { isEqual, difference, isEmpty } from 'lodash/fp'; import { useEffect, useRef, useState } from 'react'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { UrlInputsModel } from '../../store/inputs/model'; import { useApolloClient } from '../../utils/apollo_context'; @@ -59,7 +59,7 @@ export const useUrlStateHooks = ({ const prevProps = usePrevious({ pathName, urlState }); const replaceStateInLocation = ( - urlStateToReplace: UrlInputsModel | Query | Filter[] | Timeline | string, + urlStateToReplace: UrlInputsModel | Query | esFilters.Filter[] | Timeline | string, urlStateKey: string, latestLocation: Location = { hash: '', @@ -94,7 +94,10 @@ export const useUrlStateHooks = ({ urlKey ); if (newUrlStateString) { - const queryState: Query | Timeline | Filter[] = decodeRisonUrlState(newUrlStateString); + const queryState: Query | Timeline | esFilters.Filter[] = decodeRisonUrlState( + newUrlStateString + ); + if ( urlKey === CONSTANTS.appQuery && queryState != null && diff --git a/x-pack/legacy/plugins/siem/public/lib/keury/index.ts b/x-pack/legacy/plugins/siem/public/lib/keury/index.ts index 7bd8560a1770a..bf8726d5ed377 100644 --- a/x-pack/legacy/plugins/siem/public/lib/keury/index.ts +++ b/x-pack/legacy/plugins/siem/public/lib/keury/index.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { buildEsQuery, Filter, fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; +import { buildEsQuery, fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { isEmpty, isString, flow } from 'lodash/fp'; import { StaticIndexPattern } from 'ui/index_patterns'; import { Query } from 'src/plugins/data/common'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; import { KueryFilterQuery } from '../../store'; @@ -83,7 +84,7 @@ export const convertToBuildEsQuery = ({ config: EsQueryConfig; indexPattern: StaticIndexPattern; queries: Query[]; - filters: Filter[]; + filters: esFilters.Filter[]; }) => { try { return JSON.stringify( diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx index 30744b3e24c4b..d3a242b41da7b 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx @@ -12,7 +12,6 @@ import { connect } from 'react-redux'; import { StickyContainer } from 'react-sticky'; import { inputsSelectors, State } from '../../../store'; - import { FiltersGlobal } from '../../../components/filters_global'; import { HeaderPage } from '../../../components/header_page'; import { KpiHostDetailsQuery } from '../../../containers/kpi_host_details'; diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/details/types.ts b/x-pack/legacy/plugins/siem/public/pages/hosts/details/types.ts index 9df57970176eb..4f3d34f51fb93 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/details/types.ts +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/details/types.ts @@ -5,9 +5,8 @@ */ import { StaticIndexPattern } from 'ui/index_patterns'; -import { Filter } from '@kbn/es-query'; import { ActionCreator } from 'typescript-fsa'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { InputsModelId } from '../../../store/inputs/constants'; import { HostComponentProps } from '../../../components/link_to/redirect_to_hosts'; @@ -19,7 +18,7 @@ import { hostsModel } from '../../../store'; interface HostDetailsComponentReduxProps { query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; } interface HostBodyComponentDispatchProps { diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/types.ts b/x-pack/legacy/plugins/siem/public/pages/hosts/types.ts index 980c5535129aa..afc577244f7e0 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/types.ts +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/types.ts @@ -6,8 +6,7 @@ import { StaticIndexPattern } from 'ui/index_patterns'; import { ActionCreator } from 'typescript-fsa'; -import { Filter } from '@kbn/es-query'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { SiemPageName } from '../home/types'; import { hostsModel } from '../../store'; @@ -19,7 +18,7 @@ export const hostDetailsPagePath = `${hostsPagePath}/:detailName`; export interface HostsComponentReduxProps { query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; } export interface HostsComponentDispatchProps { diff --git a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/types.ts b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/types.ts index 8b9ae7613d3a5..e0029d8d219eb 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/types.ts +++ b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/types.ts @@ -4,10 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { StaticIndexPattern } from 'ui/index_patterns'; import { ActionCreator } from 'typescript-fsa'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/public'; import { NetworkType } from '../../../store/network/model'; import { ESTermQuery } from '../../../../common/typed_json'; @@ -25,7 +24,7 @@ type SetAbsoluteRangeDatePicker = ActionCreator<{ }>; interface IPDetailsComponentReduxProps { - filters: Filter[]; + filters: esFilters.Filter[]; flowTarget: FlowTarget; query: Query; } diff --git a/x-pack/legacy/plugins/siem/public/pages/network/types.ts b/x-pack/legacy/plugins/siem/public/pages/network/types.ts index 46c868729b832..e440d0c27e467 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/types.ts +++ b/x-pack/legacy/plugins/siem/public/pages/network/types.ts @@ -4,10 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { RouteComponentProps } from 'react-router-dom'; import { ActionCreator } from 'typescript-fsa'; -import { Query } from 'src/plugins/data/common'; +import { Query, esFilters } from 'src/plugins/data/common'; import { GlobalTimeArgs } from '../../containers/global_time'; import { InputsModelId } from '../../store/inputs/constants'; @@ -19,7 +18,7 @@ export type SetAbsoluteRangeDatePicker = ActionCreator<{ }>; interface NetworkComponentReduxProps { - filters: Filter[]; + filters: esFilters.Filter[]; query: Query; setAbsoluteRangeDatePicker: SetAbsoluteRangeDatePicker; } diff --git a/x-pack/legacy/plugins/siem/public/store/inputs/actions.ts b/x-pack/legacy/plugins/siem/public/store/inputs/actions.ts index 598b2854b96eb..aefcd2ea8c696 100644 --- a/x-pack/legacy/plugins/siem/public/store/inputs/actions.ts +++ b/x-pack/legacy/plugins/siem/public/store/inputs/actions.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import actionCreatorFactory from 'typescript-fsa'; import { SavedQuery } from 'src/legacy/core_plugins/data/public'; import { InspectQuery, Refetch } from './model'; import { InputsModelId } from './constants'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; const actionCreator = actionCreatorFactory('x-pack/siem/local/inputs'); @@ -83,5 +83,5 @@ export const setSavedQuery = actionCreator<{ export const setSearchBarFilter = actionCreator<{ id: InputsModelId; - filters: Filter[]; + filters: esFilters.Filter[]; }>('SET_SEARCH_BAR_FILTER'); diff --git a/x-pack/legacy/plugins/siem/public/store/inputs/model.ts b/x-pack/legacy/plugins/siem/public/store/inputs/model.ts index a98ea1f5d0812..01cf386311d77 100644 --- a/x-pack/legacy/plugins/siem/public/store/inputs/model.ts +++ b/x-pack/legacy/plugins/siem/public/store/inputs/model.ts @@ -4,13 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Filter } from '@kbn/es-query'; import { Dispatch } from 'redux'; import { Query } from 'src/plugins/data/common/query'; import { SavedQuery } from 'src/legacy/core_plugins/data/public'; import { Omit } from '../../../common/utility_types'; import { InputsModelId } from './constants'; import { CONSTANTS } from '../../components/url_state/constants'; +import { esFilters } from '../../../../../../../src/plugins/data/public'; export interface AbsoluteTimeRange { kind: 'absolute'; @@ -84,7 +84,7 @@ export interface InputsRange { queries: GlobalQuery[]; linkTo: InputsModelId[]; query: Query; - filters: Filter[]; + filters: esFilters.Filter[]; savedQuery?: SavedQuery; } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/alerts/types.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/alerts/types.ts index 7db2db5538dbf..b8d7af5c45303 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/alerts/types.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/alerts/types.ts @@ -7,7 +7,7 @@ import { get } from 'lodash/fp'; import Hapi from 'hapi'; -import { Filter } from '@kbn/es-query'; +import { esFilters } from '../../../../../../../../src/plugins/data/common'; import { SIGNALS_ID } from '../../../../common/constants'; import { Alert, @@ -19,7 +19,7 @@ import { AlertsClient } from '../../../../../alerting/server/alerts_client'; import { ActionsClient } from '../../../../../actions/server/actions_client'; import { SearchResponse } from '../../types'; -export type PartialFilter = Partial; +export type PartialFilter = Partial; export interface SignalAlertParams { description: string;