Skip to content

Commit

Permalink
[8.x] [ES|QL] Hide field statistics tab and Dashboard when ES|QL is i…
Browse files Browse the repository at this point in the history
…n 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)](#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":"[email protected]"},"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 #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![image](https://github.com/user-attachments/assets/42251d13-8b49-4eee-a65c-e275a4a7312f)\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&mdash;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&mdash;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
<[email protected]>\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","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 #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![image](https://github.com/user-attachments/assets/42251d13-8b49-4eee-a65c-e275a4a7312f)\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&mdash;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&mdash;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
<[email protected]>\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","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 #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![image](https://github.com/user-attachments/assets/42251d13-8b49-4eee-a65c-e275a4a7312f)\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&mdash;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&mdash;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
<[email protected]>\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","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) <[email protected]>
  • Loading branch information
kibanamachine and qn895 authored Nov 12, 2024
1 parent 8968625 commit f157662
Show file tree
Hide file tree
Showing 27 changed files with 350 additions and 335 deletions.
1 change: 1 addition & 0 deletions packages/kbn-esql-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export {
isESQLColumnSortable,
isESQLColumnGroupable,
TextBasedLanguages,
queryCannotBeSampled,
} from './src';

export { ENABLE_ESQL, FEEDBACK_LINK } from './constants';
1 change: 1 addition & 0 deletions packages/kbn-esql-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
44 changes: 44 additions & 0 deletions packages/kbn-esql-utils/src/utils/query_cannot_be_sampled.test.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 46 additions & 0 deletions packages/kbn-esql-utils/src/utils/query_cannot_be_sampled.ts
Original file line number Diff line number Diff line change
@@ -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);
};
Original file line number Diff line number Diff line change
Expand Up @@ -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>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 & {
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion test/functional/apps/discover/esql/_esql_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 3 additions & 5 deletions test/functional/apps/discover/group6/_field_stats_table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
});
Expand Down
18 changes: 4 additions & 14 deletions test/functional/apps/discover/group6/_view_mode_toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
EuiFlexItem,
EuiSuperDatePicker,
type EuiSuperDatePickerProps,
EuiToolTip,
} from '@elastic/eui';

import type { TimeRange } from '@kbn/es-query';
Expand Down Expand Up @@ -103,6 +104,10 @@ interface DatePickerWrapperProps {
* when EuiSuperDatePicker's 'Refresh'|'Update' button is clicked
*/
onRefresh?: () => void;
/**
* Tooltip message for the update button
*/
tooltipMessage?: string;
}

/**
Expand All @@ -122,6 +127,7 @@ export const DatePickerWrapper: FC<DatePickerWrapperProps> = (props) => {
isDisabled = false,
needsUpdate,
onRefresh,
tooltipMessage,
} = props;
const {
data,
Expand Down Expand Up @@ -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}
</>
Expand Down
Loading

0 comments on commit f157662

Please sign in to comment.