mirror of
https://github.com/elastic/kibana.git
synced 2025-04-24 01:38:56 -04:00
[8.x] [ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions (#197538) (#199861)
# Backport This will backport the following commits from `main` to `8.x`: - [[ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions (#197538)](https://github.com/elastic/kibana/pull/197538) <!--- Backport version: 9.4.3 --> ### Questions ? Please refer to the [Backport tool documentation](https://github.com/sqren/backport) <!--BACKPORT [{"author":{"name":"Quynh Nguyen (Quinn)","email":"43350163+qn895@users.noreply.github.com"},"sourceCommit":{"committedDate":"2024-11-12T18:38:04Z","message":"[ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions (#197538)\n\n## Summary\r\n\r\nPart of https://github.com/elastic/kibana/issues/196995. This PR\r\ndisables field statistics tab and Dashboard embeddable when ES|QL is in\r\nused. In Index data visualizer, it is disabled when MATCH & QSRT is in\r\nused.\r\n\r\n**1. Hide Discover's Field statistics tab:** \r\n\r\n\r\nhttps://github.com/user-attachments/assets/07cbf6ab-4e8f-4430-852a-2fe14269f26a\r\n\r\n\r\n**2. ML's Index data visualizer:**\r\n\r\nMessage will popup and user will not be allowed to run query if it\r\ncontains `MATCH` or `QRST`\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n**3. Dashboard:**\r\n\r\nHide the option to add panel and show unavailable for existing ES|QL\r\npanel\r\n\r\n\r\n<img width=\"1728\" alt=\"Screenshot 2024-11-05 at 09 44 21\"\r\nsrc=\"https://github.com/user-attachments/assets/ef763c8d-cdd6-4ece-ae13-f45726e3ef16\">\r\n\r\nFor existing dashboards and saved searches with ES|QL field statistics:\r\n\r\n<img width=\"1209\" alt=\"Screenshot 2024-11-06 at 12 00 10\"\r\nsrc=\"https://github.com/user-attachments/assets/3c423d01-42b1-48bc-994c-3340dee94bdc\">\r\n\r\n\r\n\r\n\r\n### Checklist\r\n\r\nDelete any items that are not applicable to this PR.\r\n\r\n- [ ] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n- [ ]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [ ] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [ ] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is usable by keyboard only (learn more\r\nabout [keyboard accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI touched in this PR does not create any new axe failures\r\n(run axe in browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n- [ ] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [ ] This renders correctly on smaller devices using a responsive\r\nlayout. (You can test this [in your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n- [ ] This was checked for [cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n### Risk Matrix\r\n\r\nDelete this section if it is not applicable to this PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other developers to\r\nidentify risks that should be tested prior to the change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider some of the following examples\r\nand how they may potentially impact the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes |\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n| Multiple Spaces—unexpected behavior in non-default Kibana Space.\r\n| Low | High | Integration tests will verify that all features are still\r\nsupported in non-default Kibana Space and when user switches between\r\nspaces. |\r\n| Multiple nodes—Elasticsearch polling might have race conditions\r\nwhen multiple Kibana nodes are polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so executing them multiple times will not result\r\nin logical error, but will degrade performance. To test for this case we\r\nadd plenty of unit tests around this logic and document manual testing\r\nprocedure. |\r\n| Code should gracefully handle cases when feature X or plugin Y are\r\ndisabled. | Medium | High | Unit tests will verify that any feature flag\r\nor plugin combination still results in our service operational. |\r\n| [See more potential risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for breaking API changes and was [labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#_add_your_labels)\r\n- [ ] This will appear in the **Release Notes** and follow the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>\r\nCo-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>\r\nCo-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>","sha":"61cc4129a3419312f05b2168987aee146d6372ec","branchLabelMapping":{"^v9.0.0$":"main","^v8.17.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Feature:ES|QL","Team:ESQL","backport:version","v8.17.0"],"title":"[ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions","number":197538,"url":"https://github.com/elastic/kibana/pull/197538","mergeCommit":{"message":"[ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions (#197538)\n\n## Summary\r\n\r\nPart of https://github.com/elastic/kibana/issues/196995. This PR\r\ndisables field statistics tab and Dashboard embeddable when ES|QL is in\r\nused. In Index data visualizer, it is disabled when MATCH & QSRT is in\r\nused.\r\n\r\n**1. Hide Discover's Field statistics tab:** \r\n\r\n\r\nhttps://github.com/user-attachments/assets/07cbf6ab-4e8f-4430-852a-2fe14269f26a\r\n\r\n\r\n**2. ML's Index data visualizer:**\r\n\r\nMessage will popup and user will not be allowed to run query if it\r\ncontains `MATCH` or `QRST`\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n**3. Dashboard:**\r\n\r\nHide the option to add panel and show unavailable for existing ES|QL\r\npanel\r\n\r\n\r\n<img width=\"1728\" alt=\"Screenshot 2024-11-05 at 09 44 21\"\r\nsrc=\"https://github.com/user-attachments/assets/ef763c8d-cdd6-4ece-ae13-f45726e3ef16\">\r\n\r\nFor existing dashboards and saved searches with ES|QL field statistics:\r\n\r\n<img width=\"1209\" alt=\"Screenshot 2024-11-06 at 12 00 10\"\r\nsrc=\"https://github.com/user-attachments/assets/3c423d01-42b1-48bc-994c-3340dee94bdc\">\r\n\r\n\r\n\r\n\r\n### Checklist\r\n\r\nDelete any items that are not applicable to this PR.\r\n\r\n- [ ] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n- [ ]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [ ] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [ ] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is usable by keyboard only (learn more\r\nabout [keyboard accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI touched in this PR does not create any new axe failures\r\n(run axe in browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n- [ ] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [ ] This renders correctly on smaller devices using a responsive\r\nlayout. (You can test this [in your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n- [ ] This was checked for [cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n### Risk Matrix\r\n\r\nDelete this section if it is not applicable to this PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other developers to\r\nidentify risks that should be tested prior to the change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider some of the following examples\r\nand how they may potentially impact the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes |\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n| Multiple Spaces—unexpected behavior in non-default Kibana Space.\r\n| Low | High | Integration tests will verify that all features are still\r\nsupported in non-default Kibana Space and when user switches between\r\nspaces. |\r\n| Multiple nodes—Elasticsearch polling might have race conditions\r\nwhen multiple Kibana nodes are polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so executing them multiple times will not result\r\nin logical error, but will degrade performance. To test for this case we\r\nadd plenty of unit tests around this logic and document manual testing\r\nprocedure. |\r\n| Code should gracefully handle cases when feature X or plugin Y are\r\ndisabled. | Medium | High | Unit tests will verify that any feature flag\r\nor plugin combination still results in our service operational. |\r\n| [See more potential risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for breaking API changes and was [labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#_add_your_labels)\r\n- [ ] This will appear in the **Release Notes** and follow the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>\r\nCo-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>\r\nCo-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>","sha":"61cc4129a3419312f05b2168987aee146d6372ec"}},"sourceBranch":"main","suggestedTargetBranches":["8.x"],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/197538","number":197538,"mergeCommit":{"message":"[ES|QL] Hide field statistics tab and Dashboard when ES|QL is in use, disable Index data visualizer for MATCH and QSRT functions (#197538)\n\n## Summary\r\n\r\nPart of https://github.com/elastic/kibana/issues/196995. This PR\r\ndisables field statistics tab and Dashboard embeddable when ES|QL is in\r\nused. In Index data visualizer, it is disabled when MATCH & QSRT is in\r\nused.\r\n\r\n**1. Hide Discover's Field statistics tab:** \r\n\r\n\r\nhttps://github.com/user-attachments/assets/07cbf6ab-4e8f-4430-852a-2fe14269f26a\r\n\r\n\r\n**2. ML's Index data visualizer:**\r\n\r\nMessage will popup and user will not be allowed to run query if it\r\ncontains `MATCH` or `QRST`\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n**3. Dashboard:**\r\n\r\nHide the option to add panel and show unavailable for existing ES|QL\r\npanel\r\n\r\n\r\n<img width=\"1728\" alt=\"Screenshot 2024-11-05 at 09 44 21\"\r\nsrc=\"https://github.com/user-attachments/assets/ef763c8d-cdd6-4ece-ae13-f45726e3ef16\">\r\n\r\nFor existing dashboards and saved searches with ES|QL field statistics:\r\n\r\n<img width=\"1209\" alt=\"Screenshot 2024-11-06 at 12 00 10\"\r\nsrc=\"https://github.com/user-attachments/assets/3c423d01-42b1-48bc-994c-3340dee94bdc\">\r\n\r\n\r\n\r\n\r\n### Checklist\r\n\r\nDelete any items that are not applicable to this PR.\r\n\r\n- [ ] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n- [ ]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [ ] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [ ] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is usable by keyboard only (learn more\r\nabout [keyboard accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI touched in this PR does not create any new axe failures\r\n(run axe in browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n- [ ] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [ ] This renders correctly on smaller devices using a responsive\r\nlayout. (You can test this [in your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n- [ ] This was checked for [cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n### Risk Matrix\r\n\r\nDelete this section if it is not applicable to this PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other developers to\r\nidentify risks that should be tested prior to the change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider some of the following examples\r\nand how they may potentially impact the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes |\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n| Multiple Spaces—unexpected behavior in non-default Kibana Space.\r\n| Low | High | Integration tests will verify that all features are still\r\nsupported in non-default Kibana Space and when user switches between\r\nspaces. |\r\n| Multiple nodes—Elasticsearch polling might have race conditions\r\nwhen multiple Kibana nodes are polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so executing them multiple times will not result\r\nin logical error, but will degrade performance. To test for this case we\r\nadd plenty of unit tests around this logic and document manual testing\r\nprocedure. |\r\n| Code should gracefully handle cases when feature X or plugin Y are\r\ndisabled. | Medium | High | Unit tests will verify that any feature flag\r\nor plugin combination still results in our service operational. |\r\n| [See more potential risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for breaking API changes and was [labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#_add_your_labels)\r\n- [ ] This will appear in the **Release Notes** and follow the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>\r\nCo-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>\r\nCo-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>","sha":"61cc4129a3419312f05b2168987aee146d6372ec"}},{"branch":"8.x","label":"v8.17.0","branchLabelMappingKey":"^v8.17.0$","isSourceBranch":false,"state":"NOT_CREATED"}]}] BACKPORT--> Co-authored-by: Quynh Nguyen (Quinn) <43350163+qn895@users.noreply.github.com>
This commit is contained in:
parent
89686255ab
commit
f157662827
27 changed files with 350 additions and 335 deletions
|
@ -32,6 +32,7 @@ export {
|
|||
isESQLColumnSortable,
|
||||
isESQLColumnGroupable,
|
||||
TextBasedLanguages,
|
||||
queryCannotBeSampled,
|
||||
} from './src';
|
||||
|
||||
export { ENABLE_ESQL, FEEDBACK_LINK } from './constants';
|
||||
|
|
|
@ -22,6 +22,7 @@ export {
|
|||
retrieveMetadataColumns,
|
||||
getQueryColumnsFromESQLQuery,
|
||||
} from './utils/query_parsing_helpers';
|
||||
export { queryCannotBeSampled } from './utils/query_cannot_be_sampled';
|
||||
export { appendToESQLQuery, appendWhereClauseToESQLQuery } from './utils/append_to_query';
|
||||
export {
|
||||
getESQLQueryColumns,
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the "Elastic License
|
||||
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
|
||||
* Public License v 1"; you may not use this file except in compliance with, at
|
||||
* your election, the "Elastic License 2.0", the "GNU Affero General Public
|
||||
* License v3.0 only", or the "Server Side Public License, v 1".
|
||||
*/
|
||||
import { queryCannotBeSampled } from './query_cannot_be_sampled';
|
||||
describe('queryCannotBeSampled', () => {
|
||||
it('should return true if query contains "match" function', () => {
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where match(field, "value")' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where match()' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where MATCH()' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where MATCH(fieldName,)' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where MATCH(,)' })).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true if query contains "qstr" function', () => {
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where qstr(field, "value")' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where qstr()' })).toBe(true);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where QSTR()' })).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false if query contains names', () => {
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | eval match =' })).toBe(false);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | eval MATCH =' })).toBe(false);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | eval qstr =' })).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false if query does not contain unsamplable functions', () => {
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | eval otherFunction(field, "value")' })).toBe(
|
||||
false
|
||||
);
|
||||
expect(queryCannotBeSampled({ esql: 'FROM index | where otherFunction(field, "value")' })).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it('should return false if query is undefined', () => {
|
||||
expect(queryCannotBeSampled(undefined)).toBe(false);
|
||||
expect(queryCannotBeSampled(null)).toBe(false);
|
||||
});
|
||||
});
|
46
packages/kbn-esql-utils/src/utils/query_cannot_be_sampled.ts
Normal file
46
packages/kbn-esql-utils/src/utils/query_cannot_be_sampled.ts
Normal file
|
@ -0,0 +1,46 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the "Elastic License
|
||||
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
|
||||
* Public License v 1"; you may not use this file except in compliance with, at
|
||||
* your election, the "Elastic License 2.0", the "GNU Affero General Public
|
||||
* License v3.0 only", or the "Server Side Public License, v 1".
|
||||
*/
|
||||
import type { AggregateQuery, Query } from '@kbn/es-query';
|
||||
import { Walker } from '@kbn/esql-ast';
|
||||
import { parse } from '@kbn/esql-ast';
|
||||
import { isOfAggregateQueryType } from '@kbn/es-query';
|
||||
|
||||
/**
|
||||
* Check if the query contains any of the function names being passed in
|
||||
* @param query
|
||||
* @param functions list of function names to check for
|
||||
* @returns
|
||||
*/
|
||||
export const queryContainsFunction = (
|
||||
query: AggregateQuery | Query | { [key: string]: any } | undefined | null,
|
||||
functions: string[]
|
||||
): boolean => {
|
||||
if (query && isOfAggregateQueryType(query)) {
|
||||
const { root } = parse(query.esql);
|
||||
return functions.some(
|
||||
(f) =>
|
||||
Walker.hasFunction(root, f) ||
|
||||
// Walker API expects valid queries so we need to do additional check for partial matches
|
||||
root.commands.some((c) => c.text.toLowerCase().includes(`${f}(`))
|
||||
);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const UNSAMPLABLE_FUNCTIONS = ['match', 'qstr'];
|
||||
/**
|
||||
* Check if the query contains any function that cannot be used after LIMIT clause
|
||||
* @param query
|
||||
* @returns
|
||||
*/
|
||||
export const queryCannotBeSampled = (
|
||||
query: AggregateQuery | Query | { [key: string]: any } | undefined | null
|
||||
): boolean => {
|
||||
return queryContainsFunction(query, UNSAMPLABLE_FUNCTIONS);
|
||||
};
|
|
@ -12,8 +12,16 @@ import { EuiText } from '@elastic/eui';
|
|||
|
||||
export interface FieldSummaryMessageProps {
|
||||
message: string;
|
||||
dataTestSubj?: string;
|
||||
}
|
||||
|
||||
export const FieldSummaryMessage: React.FC<FieldSummaryMessageProps> = ({ message }) => {
|
||||
return <EuiText size="s">{message}</EuiText>;
|
||||
export const FieldSummaryMessage: React.FC<FieldSummaryMessageProps> = ({
|
||||
message,
|
||||
dataTestSubj,
|
||||
}) => {
|
||||
return (
|
||||
<EuiText size="s" data-test-subj={dataTestSubj}>
|
||||
{message}
|
||||
</EuiText>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -9,9 +9,10 @@
|
|||
|
||||
import React from 'react';
|
||||
import { useQuerySubscriber } from '@kbn/unified-field-list/src/hooks/use_query_subscriber';
|
||||
import { FieldStatisticsTable, type FieldStatisticsTableProps } from './field_stats_table';
|
||||
import { useDiscoverServices } from '../../../../hooks/use_discover_services';
|
||||
import { useAdditionalFieldGroups } from '../../hooks/sidebar/use_additional_field_groups';
|
||||
import { useDiscoverServices } from '../../../../hooks/use_discover_services';
|
||||
import { FieldStatisticsTable, type FieldStatisticsTableProps } from './field_stats_table';
|
||||
import { useIsEsqlMode } from '../../hooks/use_is_esql_mode';
|
||||
|
||||
export const FieldStatisticsTab: React.FC<Omit<FieldStatisticsTableProps, 'query' | 'filters'>> =
|
||||
React.memo((props) => {
|
||||
|
@ -20,8 +21,13 @@ export const FieldStatisticsTab: React.FC<Omit<FieldStatisticsTableProps, 'query
|
|||
data: services.data,
|
||||
});
|
||||
const additionalFieldGroups = useAdditionalFieldGroups();
|
||||
const isEsql = useIsEsqlMode();
|
||||
|
||||
// Quit early if we know it's in ES|QL mode
|
||||
if (isEsql && services.dataVisualizer?.FieldStatsUnavailableMessage) {
|
||||
return <services.dataVisualizer.FieldStatsUnavailableMessage />;
|
||||
}
|
||||
|
||||
if (!services.dataVisualizer) return null;
|
||||
return (
|
||||
<FieldStatisticsTable
|
||||
dataView={props.dataView}
|
||||
|
|
|
@ -107,15 +107,15 @@ describe('Document view mode toggle component', () => {
|
|||
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('should show document and field stats view if ES|QL', async () => {
|
||||
it('should not show document and field stats view if ES|QL', async () => {
|
||||
const component = await mountComponent({ isEsqlMode: true });
|
||||
expect(findTestSubject(component, 'dscViewModeToggle').exists()).toBe(true);
|
||||
expect(findTestSubject(component, 'dscViewModeToggle').exists()).toBe(false);
|
||||
expect(findTestSubject(component, 'discoverQueryTotalHits').exists()).toBe(true);
|
||||
|
||||
expect(findTestSubject(component, 'dscViewModeDocumentButton').exists()).toBe(true);
|
||||
expect(findTestSubject(component, 'dscViewModeDocumentButton').exists()).toBe(false);
|
||||
expect(findTestSubject(component, 'dscViewModePatternAnalysisButton').exists()).toBe(false);
|
||||
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(true);
|
||||
expect(findTestSubject(component, 'dscViewModeDocumentButton').text()).toBe('Results (10)');
|
||||
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(false);
|
||||
expect(findTestSubject(component, 'discoverQueryHits').text()).toBe('10');
|
||||
});
|
||||
|
||||
it('should set the view mode to VIEW_MODE.DOCUMENT_LEVEL when dscViewModeDocumentButton is clicked', async () => {
|
||||
|
|
|
@ -46,10 +46,16 @@ export const DocumentViewModeToggle = ({
|
|||
() => isLegacyTableEnabled({ uiSettings, isEsqlMode }),
|
||||
[uiSettings, isEsqlMode]
|
||||
);
|
||||
|
||||
const [showPatternAnalysisTab, setShowPatternAnalysisTab] = useState<boolean | null>(null);
|
||||
const showFieldStatisticsTab = useMemo(
|
||||
() => uiSettings.get(SHOW_FIELD_STATISTICS) && dataVisualizerService !== undefined,
|
||||
[dataVisualizerService, uiSettings]
|
||||
() =>
|
||||
// If user opens saved search with field stats in ES|QL,
|
||||
// we show the toggle with the mode disabled so user can switch to document view
|
||||
// instead of auto-directing
|
||||
(viewMode === VIEW_MODE.AGGREGATED_LEVEL && isEsqlMode) ||
|
||||
(!isEsqlMode && uiSettings.get(SHOW_FIELD_STATISTICS) && dataVisualizerService !== undefined),
|
||||
[dataVisualizerService, uiSettings, isEsqlMode, viewMode]
|
||||
);
|
||||
const isMounted = useMountedState();
|
||||
|
||||
|
@ -100,6 +106,12 @@ export const DocumentViewModeToggle = ({
|
|||
}
|
||||
`;
|
||||
|
||||
useEffect(() => {
|
||||
if (viewMode === VIEW_MODE.AGGREGATED_LEVEL && isEsqlMode) {
|
||||
setDiscoverViewMode(VIEW_MODE.DOCUMENT_LEVEL);
|
||||
}
|
||||
}, [viewMode, isEsqlMode, setDiscoverViewMode]);
|
||||
|
||||
return (
|
||||
<EuiFlexGroup
|
||||
direction="row"
|
||||
|
@ -157,6 +169,7 @@ export const DocumentViewModeToggle = ({
|
|||
|
||||
{showFieldStatisticsTab ? (
|
||||
<EuiTab
|
||||
disabled={isEsqlMode}
|
||||
isSelected={viewMode === VIEW_MODE.AGGREGATED_LEVEL}
|
||||
onClick={() => setDiscoverViewMode(VIEW_MODE.AGGREGATED_LEVEL)}
|
||||
data-test-subj="dscViewModeFieldStatsButton"
|
||||
|
|
|
@ -13,10 +13,10 @@ import { BehaviorSubject } from 'rxjs';
|
|||
import type { DataView } from '@kbn/data-views-plugin/common';
|
||||
import { FetchContext, useBatchedPublishingSubjects } from '@kbn/presentation-publishing';
|
||||
import { DocViewFilterFn } from '@kbn/unified-doc-viewer/types';
|
||||
|
||||
import { FieldStatisticsTable } from '../../application/main/components/field_stats_table';
|
||||
import { isEsqlMode } from '../initialize_fetch';
|
||||
import type { SearchEmbeddableApi, SearchEmbeddableStateManager } from '../types';
|
||||
import { useDiscoverServices } from '../../hooks/use_discover_services';
|
||||
|
||||
interface SavedSearchEmbeddableComponentProps {
|
||||
api: SearchEmbeddableApi & {
|
||||
|
@ -37,8 +37,13 @@ export function SearchEmbeddablFieldStatsTableComponent({
|
|||
api.fetchContext$,
|
||||
api.savedSearch$
|
||||
);
|
||||
|
||||
const isEsql = useMemo(() => isEsqlMode(savedSearch), [savedSearch]);
|
||||
const services = useDiscoverServices();
|
||||
|
||||
// Quit early if we know it's in ES|QL mode
|
||||
if (isEsql && services.dataVisualizer?.FieldStatsUnavailableMessage) {
|
||||
return <services.dataVisualizer.FieldStatsUnavailableMessage />;
|
||||
}
|
||||
|
||||
return (
|
||||
<FieldStatisticsTable
|
||||
|
|
|
@ -91,7 +91,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
|
|||
|
||||
expect(await testSubjects.exists('showQueryBarMenu')).to.be(false);
|
||||
expect(await testSubjects.exists('addFilter')).to.be(false);
|
||||
expect(await testSubjects.exists('dscViewModeDocumentButton')).to.be(true);
|
||||
expect(await testSubjects.exists('dscViewModeDocumentButton')).to.be(false);
|
||||
// when Lens suggests a table, we render an ESQL based histogram
|
||||
expect(await testSubjects.exists('unifiedHistogramChart')).to.be(true);
|
||||
expect(await testSubjects.exists('discoverQueryHits')).to.be(true);
|
||||
|
|
|
@ -64,13 +64,11 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
|
|||
await testSubjects.existOrFail('discoverDocTable');
|
||||
});
|
||||
|
||||
it('should show Field Statistics data in ES|QL mode', async () => {
|
||||
it('should not show Field Statistics data in ES|QL mode', async () => {
|
||||
await discover.selectTextBaseLang();
|
||||
await discover.waitUntilSearchingHasFinished();
|
||||
|
||||
await testSubjects.click('dscViewModeFieldStatsButton');
|
||||
await header.waitUntilLoadingHasFinished();
|
||||
await testSubjects.existOrFail('dataVisualizerTableContainer');
|
||||
await discover.waitUntilSearchingHasFinished();
|
||||
await testSubjects.missingOrFail('dscViewModeFieldStatsButton');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -95,25 +95,14 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
|
|||
|
||||
it('should not show', async function () {
|
||||
await testSubjects.missingOrFail('dscViewModePatternAnalysisButton');
|
||||
await retry.try(async () => {
|
||||
const documentTab = await testSubjects.find('dscViewModeDocumentButton');
|
||||
expect(await documentTab.getAttribute('aria-selected')).to.be('true');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should show Field Statistics tab', async () => {
|
||||
await testSubjects.click('dscViewModeFieldStatsButton');
|
||||
|
||||
await retry.try(async () => {
|
||||
const fieldStatsTab = await testSubjects.find('dscViewModeFieldStatsButton');
|
||||
expect(await fieldStatsTab.getAttribute('aria-selected')).to.be('true');
|
||||
});
|
||||
|
||||
it('should not show Field Statistics tab', async () => {
|
||||
await testSubjects.existOrFail('dscViewModeToggle');
|
||||
});
|
||||
|
||||
it('should still show view mode toggle for ES|QL searches', async () => {
|
||||
it('should not show view mode toggle for ES|QL searches', async () => {
|
||||
await testSubjects.click('dscViewModeDocumentButton');
|
||||
|
||||
await retry.try(async () => {
|
||||
|
@ -125,7 +114,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
|
|||
|
||||
await discover.selectTextBaseLang();
|
||||
|
||||
await testSubjects.existOrFail('dscViewModeToggle');
|
||||
await testSubjects.missingOrFail('dscViewModeToggle');
|
||||
await testSubjects.existOrFail('discoverQueryTotalHits');
|
||||
|
||||
if (!useLegacyTable) {
|
||||
await testSubjects.existOrFail('unifiedDataTableToolbar');
|
||||
|
|
|
@ -18,6 +18,7 @@ import {
|
|||
EuiFlexItem,
|
||||
EuiSuperDatePicker,
|
||||
type EuiSuperDatePickerProps,
|
||||
EuiToolTip,
|
||||
} from '@elastic/eui';
|
||||
|
||||
import type { TimeRange } from '@kbn/es-query';
|
||||
|
@ -103,6 +104,10 @@ interface DatePickerWrapperProps {
|
|||
* when EuiSuperDatePicker's 'Refresh'|'Update' button is clicked
|
||||
*/
|
||||
onRefresh?: () => void;
|
||||
/**
|
||||
* Tooltip message for the update button
|
||||
*/
|
||||
tooltipMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -122,6 +127,7 @@ export const DatePickerWrapper: FC<DatePickerWrapperProps> = (props) => {
|
|||
isDisabled = false,
|
||||
needsUpdate,
|
||||
onRefresh,
|
||||
tooltipMessage,
|
||||
} = props;
|
||||
const {
|
||||
data,
|
||||
|
@ -318,34 +324,40 @@ export const DatePickerWrapper: FC<DatePickerWrapperProps> = (props) => {
|
|||
recentlyUsedRanges={recentlyUsedRanges}
|
||||
dateFormat={dateFormat}
|
||||
commonlyUsedRanges={commonlyUsedRanges}
|
||||
isDisabled={isDisabled}
|
||||
updateButtonProps={{
|
||||
iconOnly: isWithinLBreakpoint,
|
||||
fill: false,
|
||||
...(needsUpdate ? { needsUpdate } : {}),
|
||||
}}
|
||||
width={width}
|
||||
isDisabled={isDisabled}
|
||||
/>
|
||||
</EuiFlexItem>
|
||||
{showRefresh === true || !isTimeRangeSelectorEnabled ? (
|
||||
<EuiFlexItem grow={false}>
|
||||
<EuiButton
|
||||
fill={false}
|
||||
color={needsUpdate ? 'success' : 'primary'}
|
||||
iconType={needsUpdate ? 'kqlFunction' : 'refresh'}
|
||||
onClick={handleRefresh}
|
||||
data-test-subj={`mlDatePickerRefreshPageButton${isLoading ? ' loading' : ' loaded'}`}
|
||||
isLoading={isLoading}
|
||||
>
|
||||
{needsUpdate ? (
|
||||
<FormattedMessage id="xpack.ml.datePicker.pageUpdateButton" defaultMessage="Update" />
|
||||
) : (
|
||||
<FormattedMessage
|
||||
id="xpack.ml.datePicker.pageRefreshButton"
|
||||
defaultMessage="Refresh"
|
||||
/>
|
||||
)}
|
||||
</EuiButton>
|
||||
<EuiToolTip content={tooltipMessage}>
|
||||
<EuiButton
|
||||
fill={false}
|
||||
color={needsUpdate ? 'success' : 'primary'}
|
||||
iconType={needsUpdate ? 'kqlFunction' : 'refresh'}
|
||||
onClick={handleRefresh}
|
||||
data-test-subj={`mlDatePickerRefreshPageButton${isLoading ? ' loading' : ' loaded'}`}
|
||||
isLoading={isLoading}
|
||||
isDisabled={isDisabled}
|
||||
>
|
||||
{needsUpdate ? (
|
||||
<FormattedMessage
|
||||
id="xpack.ml.datePicker.pageUpdateButton"
|
||||
defaultMessage="Update"
|
||||
/>
|
||||
) : (
|
||||
<FormattedMessage
|
||||
id="xpack.ml.datePicker.pageRefreshButton"
|
||||
defaultMessage="Refresh"
|
||||
/>
|
||||
)}
|
||||
</EuiButton>
|
||||
</EuiToolTip>
|
||||
</EuiFlexItem>
|
||||
) : null}
|
||||
</>
|
||||
|
|
|
@ -41,7 +41,6 @@
|
|||
"uiActions",
|
||||
"lens",
|
||||
"esql",
|
||||
"visualizations"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -65,7 +65,7 @@ interface DataVisualizerTableProps<T extends object> {
|
|||
error?: Error | string;
|
||||
}
|
||||
|
||||
export const DataVisualizerTable = <T extends DataVisualizerTableItem>({
|
||||
const UnmemoizedDataVisualizerTable = <T extends DataVisualizerTableItem>({
|
||||
items,
|
||||
pageState,
|
||||
updatePageState,
|
||||
|
@ -506,3 +506,7 @@ export const DataVisualizerTable = <T extends DataVisualizerTableItem>({
|
|||
</EuiResizeObserver>
|
||||
);
|
||||
};
|
||||
|
||||
export const DataVisualizerTable = React.memo(
|
||||
UnmemoizedDataVisualizerTable
|
||||
) as typeof UnmemoizedDataVisualizerTable;
|
||||
|
|
|
@ -24,12 +24,12 @@ import {
|
|||
EuiPanel,
|
||||
EuiProgress,
|
||||
EuiSpacer,
|
||||
EuiCallOut,
|
||||
} from '@elastic/eui';
|
||||
import type { DataView } from '@kbn/data-views-plugin/common';
|
||||
import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils';
|
||||
import { getOrCreateDataViewByIndexPattern } from '../../search_strategy/requests/get_data_view_by_index_pattern';
|
||||
import { useCurrentEuiTheme } from '../../../common/hooks/use_current_eui_theme';
|
||||
import type { FieldVisConfig } from '../../../common/components/stats_table/types';
|
||||
import { DATA_VISUALIZER_INDEX_VIEWER } from '../../constants/index_data_visualizer_viewer';
|
||||
import { useDataVisualizerKibana } from '../../../kibana_context';
|
||||
import type { GetAdditionalLinks } from '../../../common/components/results_links';
|
||||
|
@ -49,6 +49,7 @@ import type {
|
|||
import type { ESQLQuery } from '../../search_strategy/requests/esql_utils';
|
||||
import { isESQLQuery } from '../../search_strategy/requests/esql_utils';
|
||||
import { FieldStatsComponentType } from '../../constants/field_stats_component_type';
|
||||
import { getReasonIfFieldStatsUnavailableForQuery } from '../../utils/get_reason_fieldstats_unavailable_for_esql_query';
|
||||
|
||||
export interface IndexDataVisualizerESQLProps {
|
||||
getAdditionalLinks?: GetAdditionalLinks;
|
||||
|
@ -64,6 +65,8 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
const [query, setQuery] = useState<ESQLQuery>(DEFAULT_ESQL_QUERY);
|
||||
const [currentDataView, setCurrentDataView] = useState<DataView | undefined>();
|
||||
|
||||
const unsupportedReasonForQuery = getReasonIfFieldStatsUnavailableForQuery(localQuery);
|
||||
|
||||
const toggleShowEmptyFields = () => {
|
||||
setDataVisualizerListState({
|
||||
...dataVisualizerListState,
|
||||
|
@ -202,8 +205,11 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
const onTextLangQuerySubmit = useCallback(
|
||||
async (q: AggregateQuery | undefined) => {
|
||||
if (isESQLQuery(q)) {
|
||||
resetData();
|
||||
setQuery(q);
|
||||
const isUnsupported = getReasonIfFieldStatsUnavailableForQuery(q) !== undefined;
|
||||
if (!isUnsupported) {
|
||||
resetData();
|
||||
setQuery(q);
|
||||
}
|
||||
}
|
||||
},
|
||||
[resetData]
|
||||
|
@ -224,8 +230,19 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
data-test-subj="dataViewTitleHeader"
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
css={{ padding: `${euiTheme.euiSizeS} 0`, marginRight: `${euiTheme.euiSize}` }}
|
||||
/>
|
||||
css={{ padding: 0, marginRight: 0 }}
|
||||
>
|
||||
{unsupportedReasonForQuery ? (
|
||||
<EuiFlexItem grow={true}>
|
||||
<EuiCallOut
|
||||
size="s"
|
||||
iconType="warning"
|
||||
color="warning"
|
||||
title={unsupportedReasonForQuery}
|
||||
/>
|
||||
</EuiFlexItem>
|
||||
) : null}
|
||||
</EuiFlexGroup>
|
||||
|
||||
{isWithinLargeBreakpoint ? <EuiSpacer size="m" /> : null}
|
||||
<EuiFlexGroup
|
||||
|
@ -253,7 +270,8 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
width="full"
|
||||
needsUpdate={queryNeedsUpdate}
|
||||
onRefresh={handleRefresh}
|
||||
isDisabled={!hasValidTimeField}
|
||||
isDisabled={unsupportedReasonForQuery !== undefined}
|
||||
tooltipMessage={unsupportedReasonForQuery}
|
||||
/>
|
||||
</EuiFlexItem>
|
||||
</EuiFlexGroup>
|
||||
|
@ -276,6 +294,7 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
hideRunQueryText={false}
|
||||
isLoading={queryHistoryStatus ?? false}
|
||||
displayDocumentationAsFlyout
|
||||
disableSubmitAction={unsupportedReasonForQuery !== undefined}
|
||||
/>
|
||||
</EuiFlexItem>
|
||||
|
||||
|
@ -312,7 +331,7 @@ export const IndexDataVisualizerESQL: FC<IndexDataVisualizerESQLProps> = (dataVi
|
|||
<EuiSpacer size="s" />
|
||||
|
||||
<EuiProgress value={combinedProgress} max={100} size="xs" />
|
||||
<DataVisualizerTable<FieldVisConfig>
|
||||
<DataVisualizerTable
|
||||
items={configs}
|
||||
pageState={dataVisualizerListState}
|
||||
updatePageState={setDataVisualizerListState}
|
||||
|
|
|
@ -14,12 +14,14 @@ interface FieldStatsESQLEditorProps {
|
|||
query: AggregateQuery;
|
||||
setQuery: (query: AggregateQuery) => void;
|
||||
onQuerySubmit: (query: AggregateQuery, abortController?: AbortController) => Promise<void>;
|
||||
disableSubmitAction?: boolean;
|
||||
}
|
||||
export const FieldStatsESQLEditor = ({
|
||||
canEditTextBasedQuery = true,
|
||||
query,
|
||||
setQuery,
|
||||
onQuerySubmit,
|
||||
disableSubmitAction = false,
|
||||
}: FieldStatsESQLEditorProps) => {
|
||||
const prevQuery = useRef<AggregateQuery>(query);
|
||||
const [isVisualizationLoading, setIsVisualizationLoading] = useState(false);
|
||||
|
@ -48,8 +50,8 @@ export const FieldStatsESQLEditor = ({
|
|||
editorIsInline
|
||||
hideRunQueryText
|
||||
onTextLangQuerySubmit={onTextLangQuerySubmit}
|
||||
isDisabled={false}
|
||||
allowQueryCancellation
|
||||
allowQueryCancellation={false}
|
||||
disableSubmitAction={disableSubmitAction}
|
||||
isLoading={isVisualizationLoading}
|
||||
/>
|
||||
</EuiFlexItem>
|
||||
|
|
|
@ -38,6 +38,7 @@ import type {
|
|||
import { FieldStatsInitializerViewType } from '../grid_embeddable/types';
|
||||
import { isESQLQuery } from '../../search_strategy/requests/esql_utils';
|
||||
import { DataSourceTypeSelector } from './field_stats_initializer_view_type';
|
||||
import { getReasonIfFieldStatsUnavailableForQuery } from '../../utils/get_reason_fieldstats_unavailable_for_esql_query';
|
||||
|
||||
export interface FieldStatsInitializerProps {
|
||||
initialInput?: Partial<FieldStatisticsTableEmbeddableState>;
|
||||
|
@ -94,6 +95,12 @@ export const FieldStatisticsInitializer: FC<FieldStatsInitializerProps> = ({
|
|||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [dataViewId, viewType, esqlQuery.esql, isEsqlMode]);
|
||||
|
||||
const unsupportedReason = useMemo(
|
||||
() => getReasonIfFieldStatsUnavailableForQuery(esqlQuery),
|
||||
[esqlQuery]
|
||||
);
|
||||
|
||||
const onESQLQuerySubmit = useCallback(
|
||||
async (query: AggregateQuery, abortController?: AbortController) => {
|
||||
const adhocDataView = await getESQLAdHocDataview(query.esql, dataViews);
|
||||
|
@ -101,11 +108,14 @@ export const FieldStatisticsInitializer: FC<FieldStatsInitializerProps> = ({
|
|||
setDataViewId(adhocDataView.id);
|
||||
}
|
||||
|
||||
await onPreview({
|
||||
viewType,
|
||||
dataViewId: adhocDataView?.id,
|
||||
query,
|
||||
});
|
||||
const supported = getReasonIfFieldStatsUnavailableForQuery(query) === undefined;
|
||||
if (supported) {
|
||||
await onPreview({
|
||||
viewType,
|
||||
dataViewId: adhocDataView?.id,
|
||||
query,
|
||||
});
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[isEsqlMode]
|
||||
|
@ -202,6 +212,7 @@ export const FieldStatisticsInitializer: FC<FieldStatsInitializerProps> = ({
|
|||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{initialInput?.viewType === FieldStatsInitializerViewType.ESQL && !isEsqlEnabled ? (
|
||||
<>
|
||||
<DataSourceTypeSelector value={viewType} onChange={setViewType} />
|
||||
|
@ -247,6 +258,7 @@ export const FieldStatisticsInitializer: FC<FieldStatsInitializerProps> = ({
|
|||
query={esqlQuery}
|
||||
setQuery={setQuery}
|
||||
onQuerySubmit={onESQLQuerySubmit}
|
||||
disableSubmitAction={!!unsupportedReason}
|
||||
/>
|
||||
) : null}
|
||||
</EuiFlexGroup>
|
||||
|
@ -272,26 +284,39 @@ export const FieldStatisticsInitializer: FC<FieldStatsInitializerProps> = ({
|
|||
/>
|
||||
</EuiButtonEmpty>
|
||||
</EuiFlexItem>
|
||||
<EuiFlexItem grow={false}>
|
||||
<EuiButton
|
||||
onClick={onCreate.bind(null, updatedProps)}
|
||||
fill
|
||||
aria-label={i18n.translate(
|
||||
'xpack.dataVisualizer.fieldStatisticsDashboardPanel.config.applyFlyoutAriaLabel',
|
||||
{
|
||||
defaultMessage: 'Apply changes',
|
||||
}
|
||||
)}
|
||||
disabled={!isEsqlFormValid || !isDataViewFormValid}
|
||||
iconType="check"
|
||||
data-test-subj="applyFlyoutButton"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="xpack.dataVisualizer.fieldStatisticsDashboardPanel.config.applyAndCloseLabel"
|
||||
defaultMessage="Apply and close"
|
||||
/>
|
||||
</EuiButton>
|
||||
</EuiFlexItem>
|
||||
<EuiFlexGroup
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
justifyContent="flexEnd"
|
||||
gutterSize="xs"
|
||||
>
|
||||
{unsupportedReason ? (
|
||||
<EuiFlexItem grow={false}>
|
||||
<EuiIconTip type="warning" content={unsupportedReason} color="warning" />
|
||||
</EuiFlexItem>
|
||||
) : null}
|
||||
|
||||
<EuiFlexItem grow={false}>
|
||||
<EuiButton
|
||||
onClick={onCreate.bind(null, updatedProps)}
|
||||
fill
|
||||
aria-label={i18n.translate(
|
||||
'xpack.dataVisualizer.fieldStatisticsDashboardPanel.config.applyFlyoutAriaLabel',
|
||||
{
|
||||
defaultMessage: 'Apply changes',
|
||||
}
|
||||
)}
|
||||
disabled={!isEsqlFormValid || !isDataViewFormValid || !!unsupportedReason}
|
||||
iconType="check"
|
||||
data-test-subj="applyFlyoutButton"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="xpack.dataVisualizer.fieldStatisticsDashboardPanel.config.applyAndCloseLabel"
|
||||
defaultMessage="Apply and close"
|
||||
/>
|
||||
</EuiButton>
|
||||
</EuiFlexItem>
|
||||
</EuiFlexGroup>
|
||||
</EuiFlexGroup>
|
||||
</EuiFlyoutFooter>
|
||||
</>
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the Elastic License
|
||||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { EuiFlexItem } from '@elastic/eui';
|
||||
import { EmptyPlaceholder } from '@kbn/charts-plugin/public';
|
||||
import { i18n } from '@kbn/i18n';
|
||||
import { css } from '@emotion/react';
|
||||
const FIELD_STATS_UNAVAILABLE_TITLE = i18n.translate(
|
||||
'xpack.dataVisualizer.fieldStats.unavailableTitle',
|
||||
{
|
||||
defaultMessage: 'Field statistics not supported for ES|QL queries',
|
||||
}
|
||||
);
|
||||
|
||||
const FieldStatsUnavailableMessage = ({
|
||||
id,
|
||||
title = FIELD_STATS_UNAVAILABLE_TITLE,
|
||||
}: {
|
||||
id?: string;
|
||||
title?: string;
|
||||
}) => {
|
||||
return (
|
||||
<EuiFlexItem
|
||||
alignItems="center"
|
||||
fullWidth
|
||||
css={css`
|
||||
height: 100%;
|
||||
`}
|
||||
>
|
||||
<EmptyPlaceholder icon={'warning'} message={title} />
|
||||
</EuiFlexItem>
|
||||
);
|
||||
};
|
||||
|
||||
// Default export for lazy loading
|
||||
// eslint-disable-next-line import/no-default-export
|
||||
export default FieldStatsUnavailableMessage;
|
|
@ -16,11 +16,13 @@ import { DatePickerContextProvider } from '@kbn/ml-date-picker';
|
|||
import type { DatePickerDependencies } from '@kbn/ml-date-picker';
|
||||
import { UI_SETTINGS } from '@kbn/data-plugin/common';
|
||||
import { pick } from 'lodash';
|
||||
import { isOfAggregateQueryType } from '@kbn/es-query';
|
||||
import { getCoreStart, getPluginsStart } from '../../../../kibana_services';
|
||||
import type {
|
||||
FieldStatisticTableEmbeddableProps,
|
||||
ESQLDataVisualizerGridEmbeddableState,
|
||||
} from './types';
|
||||
import FieldStatsUnavailableMessage from './embeddable_error_msg';
|
||||
|
||||
const EmbeddableESQLFieldStatsTableWrapper = dynamic(
|
||||
() => import('./embeddable_esql_field_stats_table')
|
||||
|
@ -41,7 +43,10 @@ function isFieldStatisticTableEmbeddableState(
|
|||
|
||||
const FieldStatisticsWrapperContent = (props: FieldStatisticTableEmbeddableProps) => {
|
||||
if (isESQLFieldStatisticTableEmbeddableState(props)) {
|
||||
return (
|
||||
const isEsql = props.esqlQuery && isOfAggregateQueryType(props.esqlQuery);
|
||||
return isEsql ? (
|
||||
<FieldStatsUnavailableMessage id={props.id} />
|
||||
) : (
|
||||
<EmbeddableESQLFieldStatsTableWrapper
|
||||
id={props.id}
|
||||
dataView={props.dataView}
|
||||
|
|
|
@ -44,6 +44,7 @@ import type {
|
|||
} from '../../embeddables/grid_embeddable/types';
|
||||
import { getDefaultPageState } from '../../constants/index_data_visualizer_viewer';
|
||||
import { DEFAULT_ESQL_LIMIT } from '../../constants/esql_constants';
|
||||
import { getReasonIfFieldStatsUnavailableForQuery } from '../../utils/get_reason_fieldstats_unavailable_for_esql_query';
|
||||
|
||||
type AnyQuery = Query | AggregateQuery;
|
||||
|
||||
|
@ -160,9 +161,17 @@ export const useESQLDataVisualizerData = (
|
|||
|
||||
const tf = timefilter;
|
||||
|
||||
if (!buckets || !tf || (isESQLQuery(query) && query.esql === '')) return;
|
||||
const activeBounds = tf.getActiveBounds();
|
||||
if (!buckets || !tf || query.esql === '') return;
|
||||
|
||||
// Safeguard to not ever run query if not supported
|
||||
if (isESQLQuery(query)) {
|
||||
const unsupportedReasonForQuery = getReasonIfFieldStatsUnavailableForQuery(query);
|
||||
if (unsupportedReasonForQuery) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const activeBounds = tf.getActiveBounds();
|
||||
let earliest: number | undefined;
|
||||
let latest: number | undefined;
|
||||
if (activeBounds !== undefined && currentDataView?.timeFieldName !== undefined) {
|
||||
|
|
|
@ -1,213 +0,0 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the Elastic License
|
||||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import { i18n } from '@kbn/i18n';
|
||||
import type { PresentationContainer } from '@kbn/presentation-containers';
|
||||
import type { EmbeddableApiContext } from '@kbn/presentation-publishing';
|
||||
import type { UiActionsActionDefinition } from '@kbn/ui-actions-plugin/public';
|
||||
import type { CoreStart } from '@kbn/core-lifecycle-browser';
|
||||
import { COMMON_VISUALIZATION_GROUPING } from '@kbn/visualizations-plugin/public';
|
||||
import { ENABLE_ESQL } from '@kbn/esql-utils';
|
||||
|
||||
import type { DataVisualizerStartDependencies } from '../../common/types/data_visualizer_plugin';
|
||||
import type {
|
||||
FieldStatisticsTableEmbeddableApi,
|
||||
FieldStatsControlsApi,
|
||||
} from '../embeddables/field_stats/types';
|
||||
import type { FieldStatsInitialState } from '../embeddables/grid_embeddable/types';
|
||||
|
||||
const parentApiIsCompatible = async (
|
||||
parentApi: unknown
|
||||
): Promise<PresentationContainer | undefined> => {
|
||||
const { apiIsPresentationContainer } = await import('@kbn/presentation-containers');
|
||||
// we cannot have an async type check, so return the casted parentApi rather than a boolean
|
||||
return apiIsPresentationContainer(parentApi) ? (parentApi as PresentationContainer) : undefined;
|
||||
};
|
||||
|
||||
interface FieldStatsActionContext extends EmbeddableApiContext {
|
||||
embeddable: FieldStatisticsTableEmbeddableApi;
|
||||
}
|
||||
|
||||
async function updatePanelFromFlyoutEdits({
|
||||
api,
|
||||
isNewPanel,
|
||||
deletePanel,
|
||||
coreStart,
|
||||
pluginStart,
|
||||
initialState,
|
||||
}: {
|
||||
api: FieldStatisticsTableEmbeddableApi;
|
||||
isNewPanel: boolean;
|
||||
deletePanel?: () => void;
|
||||
coreStart: CoreStart;
|
||||
pluginStart: DataVisualizerStartDependencies;
|
||||
initialState: FieldStatsInitialState;
|
||||
fieldStatsControlsApi?: FieldStatsControlsApi;
|
||||
}) {
|
||||
const [
|
||||
{ getOrCreateDataViewByIndexPattern },
|
||||
{ FieldStatisticsInitializer },
|
||||
{ tracksOverlays },
|
||||
{ toMountPoint },
|
||||
{ KibanaContextProvider },
|
||||
{ isDefined },
|
||||
] = await Promise.all([
|
||||
import('../search_strategy/requests/get_data_view_by_index_pattern'),
|
||||
import('../embeddables/field_stats/field_stats_initializer'),
|
||||
import('@kbn/presentation-containers'),
|
||||
import('@kbn/react-kibana-mount'),
|
||||
import('@kbn/kibana-react-plugin/public'),
|
||||
import('@kbn/ml-is-defined'),
|
||||
]);
|
||||
const parentApi = api.parentApi;
|
||||
const overlayTracker = tracksOverlays(parentApi) ? parentApi : undefined;
|
||||
const services = {
|
||||
...coreStart,
|
||||
...pluginStart,
|
||||
};
|
||||
let hasChanged = false;
|
||||
const cancelChanges = () => {
|
||||
// Reset to initialState in case user has changed the preview state
|
||||
if (hasChanged && api && initialState) {
|
||||
api.updateUserInput(initialState);
|
||||
}
|
||||
|
||||
if (isNewPanel && deletePanel) {
|
||||
deletePanel();
|
||||
}
|
||||
flyoutSession.close();
|
||||
overlayTracker?.clearOverlays();
|
||||
};
|
||||
|
||||
const update = async (nextUpdate: FieldStatsInitialState) => {
|
||||
const esqlQuery = nextUpdate?.query?.esql;
|
||||
if (isDefined(esqlQuery)) {
|
||||
const dv = await getOrCreateDataViewByIndexPattern(
|
||||
pluginStart.data.dataViews,
|
||||
esqlQuery,
|
||||
undefined
|
||||
);
|
||||
if (dv?.id && nextUpdate.dataViewId !== dv.id) {
|
||||
nextUpdate.dataViewId = dv.id;
|
||||
}
|
||||
}
|
||||
if (api) {
|
||||
api.updateUserInput(nextUpdate);
|
||||
}
|
||||
|
||||
flyoutSession.close();
|
||||
overlayTracker?.clearOverlays();
|
||||
};
|
||||
const flyoutSession = services.overlays.openFlyout(
|
||||
toMountPoint(
|
||||
<KibanaContextProvider services={services}>
|
||||
<FieldStatisticsInitializer
|
||||
initialInput={initialState}
|
||||
onPreview={async (nextUpdate) => {
|
||||
if (api.updateUserInput) {
|
||||
api.updateUserInput(nextUpdate);
|
||||
hasChanged = true;
|
||||
}
|
||||
}}
|
||||
onCreate={update}
|
||||
onCancel={cancelChanges}
|
||||
isNewPanel={isNewPanel}
|
||||
/>
|
||||
</KibanaContextProvider>,
|
||||
coreStart
|
||||
),
|
||||
{
|
||||
ownFocus: true,
|
||||
size: 's',
|
||||
paddingSize: 'm',
|
||||
hideCloseButton: true,
|
||||
type: 'push',
|
||||
'data-test-subj': 'fieldStatisticsInitializerFlyout',
|
||||
onClose: cancelChanges,
|
||||
}
|
||||
);
|
||||
overlayTracker?.openOverlay(flyoutSession, { focusedPanelId: api.uuid });
|
||||
}
|
||||
|
||||
export function createAddFieldStatsTableAction(
|
||||
coreStart: CoreStart,
|
||||
pluginStart: DataVisualizerStartDependencies
|
||||
): UiActionsActionDefinition<FieldStatsActionContext> {
|
||||
return {
|
||||
id: 'create-field-stats-table',
|
||||
grouping: COMMON_VISUALIZATION_GROUPING,
|
||||
order: 10,
|
||||
getIconType: () => 'fieldStatistics',
|
||||
getDisplayName: () =>
|
||||
i18n.translate('xpack.dataVisualizer.fieldStatistics.displayName', {
|
||||
defaultMessage: 'Field statistics',
|
||||
}),
|
||||
disabled: !coreStart.uiSettings.get(ENABLE_ESQL),
|
||||
async isCompatible(context: EmbeddableApiContext) {
|
||||
return (
|
||||
Boolean(await parentApiIsCompatible(context.embeddable)) &&
|
||||
coreStart.uiSettings.get(ENABLE_ESQL)
|
||||
);
|
||||
},
|
||||
async execute(context) {
|
||||
const [
|
||||
{ IncompatibleActionError },
|
||||
{ FIELD_STATS_EMBEDDABLE_TYPE },
|
||||
{ FieldStatsInitializerViewType },
|
||||
] = await Promise.all([
|
||||
import('@kbn/ui-actions-plugin/public'),
|
||||
import('../embeddables/field_stats/constants'),
|
||||
import('../embeddables/grid_embeddable/types'),
|
||||
]);
|
||||
|
||||
const presentationContainerParent = await parentApiIsCompatible(context.embeddable);
|
||||
if (!presentationContainerParent) throw new IncompatibleActionError();
|
||||
|
||||
const isEsqlEnabled = coreStart.uiSettings.get(ENABLE_ESQL);
|
||||
try {
|
||||
const defaultIndexPattern = await pluginStart.data.dataViews.getDefault();
|
||||
const defaultInitialState: FieldStatsInitialState = isEsqlEnabled
|
||||
? {
|
||||
viewType: FieldStatsInitializerViewType.ESQL,
|
||||
query: {
|
||||
// Initial default query
|
||||
esql: `from ${defaultIndexPattern?.getIndexPattern()} | limit 10`,
|
||||
},
|
||||
}
|
||||
: {
|
||||
viewType: FieldStatsInitializerViewType.DATA_VIEW,
|
||||
};
|
||||
const embeddable = await presentationContainerParent.addNewPanel<
|
||||
object,
|
||||
FieldStatisticsTableEmbeddableApi
|
||||
>({
|
||||
panelType: FIELD_STATS_EMBEDDABLE_TYPE,
|
||||
initialState: defaultInitialState,
|
||||
});
|
||||
// open the flyout if embeddable has been created successfully
|
||||
if (embeddable) {
|
||||
const deletePanel = () => {
|
||||
presentationContainerParent.removePanel(embeddable.uuid);
|
||||
};
|
||||
|
||||
updatePanelFromFlyoutEdits({
|
||||
api: embeddable,
|
||||
isNewPanel: true,
|
||||
deletePanel,
|
||||
coreStart,
|
||||
pluginStart,
|
||||
initialState: defaultInitialState,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the Elastic License
|
||||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
|
||||
import type { CoreStart } from '@kbn/core-lifecycle-browser';
|
||||
import type { UiActionsSetup } from '@kbn/ui-actions-plugin/public';
|
||||
import type { DataVisualizerStartDependencies } from '../../common/types/data_visualizer_plugin';
|
||||
import { createAddFieldStatsTableAction } from './create_field_stats_table';
|
||||
|
||||
export function registerDataVisualizerUiActions(
|
||||
uiActions: UiActionsSetup,
|
||||
coreStart: CoreStart,
|
||||
pluginStart: DataVisualizerStartDependencies
|
||||
) {
|
||||
const addFieldStatsAction = createAddFieldStatsTableAction(coreStart, pluginStart);
|
||||
uiActions.addTriggerAction('ADD_PANEL_TRIGGER', addFieldStatsAction);
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
||||
* or more contributor license agreements. Licensed under the Elastic License
|
||||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
|
||||
import type { AggregateQuery } from '@kbn/es-query';
|
||||
|
||||
import type { Query } from '@kbn/es-query';
|
||||
import { queryCannotBeSampled } from '@kbn/esql-utils';
|
||||
import { i18n } from '@kbn/i18n';
|
||||
|
||||
export const getReasonIfFieldStatsUnavailableForQuery = (
|
||||
query?: AggregateQuery | Query | { [key: string]: any }
|
||||
): string | undefined => {
|
||||
if (queryCannotBeSampled(query)) {
|
||||
return i18n.translate('xpack.dataVisualizer.fieldStats.unavailableForESQLQueryDescription', {
|
||||
defaultMessage: `Field statistics are not available for ES|QL queries with 'MATCH' or 'QSTR' functions.`,
|
||||
});
|
||||
}
|
||||
};
|
|
@ -21,7 +21,6 @@ import type {
|
|||
DataVisualizerStartDependencies,
|
||||
} from './application/common/types/data_visualizer_plugin';
|
||||
import { registerEmbeddables } from './application/index_data_visualizer/embeddables/field_stats';
|
||||
import { registerDataVisualizerUiActions } from './application/index_data_visualizer/ui_actions';
|
||||
export type DataVisualizerPluginSetup = ReturnType<DataVisualizerPlugin['setup']>;
|
||||
export type DataVisualizerPluginStart = ReturnType<DataVisualizerPlugin['start']>;
|
||||
|
||||
|
@ -57,12 +56,6 @@ export class DataVisualizerPlugin
|
|||
registerEmbeddables(plugins.embeddable, core);
|
||||
}
|
||||
|
||||
const [coreStart, pluginStart] = await core.getStartServices();
|
||||
|
||||
if (plugins.uiActions) {
|
||||
registerDataVisualizerUiActions(plugins.uiActions, coreStart, pluginStart);
|
||||
}
|
||||
|
||||
if (plugins.home) {
|
||||
registerHomeAddData(plugins.home, this.resultsLinks);
|
||||
registerHomeFeatureCatalogue(plugins.home);
|
||||
|
@ -84,6 +77,12 @@ export class DataVisualizerPlugin
|
|||
getIndexDataVisualizerComponent,
|
||||
getDataDriftComponent,
|
||||
getMaxBytesFormatted,
|
||||
FieldStatsUnavailableMessage: dynamic(
|
||||
async () =>
|
||||
import(
|
||||
'./application/index_data_visualizer/embeddables/grid_embeddable/embeddable_error_msg'
|
||||
)
|
||||
),
|
||||
FieldStatisticsTable: dynamic(
|
||||
async () =>
|
||||
import(
|
||||
|
|
|
@ -86,7 +86,6 @@
|
|||
"@kbn/core-lifecycle-browser",
|
||||
"@kbn/presentation-containers",
|
||||
"@kbn/react-kibana-mount",
|
||||
"@kbn/visualizations-plugin",
|
||||
"@kbn/core-ui-settings-browser"
|
||||
],
|
||||
"exclude": [
|
||||
|
|
|
@ -90,8 +90,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
|
|||
|
||||
await testSubjects.missingOrFail('showQueryBarMenu');
|
||||
await testSubjects.missingOrFail('addFilter');
|
||||
await testSubjects.existOrFail('dscViewModeToggle');
|
||||
await testSubjects.existOrFail('dscViewModeDocumentButton');
|
||||
await testSubjects.missingOrFail('dscViewModeToggle');
|
||||
await testSubjects.missingOrFail('dscViewModeDocumentButton');
|
||||
// when Lens suggests a table, we render an ESQL based histogram
|
||||
await testSubjects.existOrFail('unifiedHistogramChart');
|
||||
await testSubjects.existOrFail('discoverQueryHits');
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue